text
stringlengths
28
935k
meta
stringlengths
137
139
red_pajama_subset
stringclasses
1 value
\section{Introduction} \label{sec_intro} \IEEEPARstart{A}{n} $[n,k,d]_q$ code is a $q$-ary linear code with length $n$, dimension $k$, and minimum Hamming distance $d$. Since we will only consider binary codes, we also speak of $[n,k,d]$ codes. Linear codes have numerous applications so that constructions or non-existence results for specific parameters were the topic of many papers. One motivation was the determination of the smallest integer $n(k,d)$ for which an $[n,k,d]$ code exists. As shown in \cite{baumert1973note} for every fixed dimension $k$ there exists an integer $D(k)$ such that $n(k,d)=g(k,d)$ for all $d\ge D(k)$, where $n(k,d)\ge g(k,d):=\sum_{i=0}^{k-1} \left\lceil\frac{d}{2^i}\right\rceil$, is the so-called Griesmer bound. Thus, the determination of $n(k,d)$ is a finite problem. In 2000 the determination of $n(8,d)$ was completed in \cite{bouyukhev2000smallest}. Not many of the open cases for $n(9,d)$ have been resolved since then and we only refer to most recent paper \cite{46_9_20}. The aim of this note is to to circularize a recent application of non-existence results of linear codes. In random linear network coding so-called constant-dimension codes are used. These are sets of $k$-dimensional subspaces of $\mathbb{F}_q^n$ with subspace distance $d_S(U,W):=\dim(U)+\dim(W)- 2\dim(U\cap W)$. By $A_q(n,d;k)$ we denote the maximum possible cardinality, where $A_q(n,d;k)=A_q(n,d;n-k)$, so that we assume $2k\le n$. In \cite{kiermaier2020lengths} the upper bounds $A_q(n,d;k) \le \leftllfloor\frac{\left(q^n-1\right)\cdot A_q(n-1,d;k-1)/(q-1)}{\left(q^k-1\right)/(q-1)}\rightrrfloor_{q^{k-1}}$ for $d>2k$ and $A_q(n,2k;k)\le \leftllfloor\frac{\left(q^n-1\right)/(q-1)}{\left(q^k-1\right)/(q-1)}\rightrrfloor_{q^{k-1}}$ were proven. Here $\leftllfloor a/b \rightrrfloor_{q^{r}}$ denotes the maximal integer $t$ such that there exists a $q^r$-divisible $q$-ary linear code of effective length $n=a-tb$ and a code is called $q^r$-divisible if the Hamming weights $\operatorname{wt}(c)$ of all codewords $c$ are divisible by $q^r$. For integers $r$ the possible length of $q^r$-divisible codes have been completely determined in \cite{kiermaier2020lengths} and except for the cases $(n,d,k,q)=(6,4,3,2)$ and $(8,4,3,2)$ no tighter bound for $A_q(n,d;k)$ with $d>2k$ is known. For the case $d=2k$, where the constant-dimension codes are also called partial spreads, the notion of $\leftllfloor a/b \rightrrfloor_{q^{r}}$ can be sharpened by requiring the existence of a projective $q^r$-divisible $q$-ary linear code of effective length $n=a-tb$. Doing so, all known upper bounds for $A_q(n,2k;k)$ follow from non-existence results of projective $q^r$-divisible codes, see e.g.\ \cite{honold2018partial}. For each field size $q$ and each integer $r$ there exists only a finite set $\mathcal{E}_q(r)$ such that there does not exist a projective $q^r$-divisible code of effective length $n$ iff $n\in \mathcal{E}_q(r)$. We have $\mathcal{E}_2(1)=\{1,2\}$, $\mathcal{E}_2(2)=\{1,2,3,4,5,6,9,10,11,12,13\}$, and remark that the determination of $\mathcal{E}_2(3)$ was recently completed in \cite{honold2019lengths} by excluding length $n=59$. In this paper we show the non-existence of $16$-divisible binary codes of effective length $n=131$, which e.g.\ implies $A_2(13,10;5)\le 259$. \section{Preliminaries} \label{sec_preliminaries} Since the minimum Hamming distance is not relevant in our context, we speak of $[n,k]$ codes. The dual code of an $[n,k]$ code $C$ is the $[n,n-k]$ code $C^*$ consisting of the elements of $\mathbb{F}_2^n$ that are perpendicular to all codewords of $C$. By $a_i$ we denote the number of codewords of $C$ of weight $i$. With this, the weight enumerator is given by $W(z)=\sum_{i\ge 0} a_iz^i$. The numbers $a_i^*$ of codewords of the dual code of weight $i$ are related by the so-called MacWilliams identities \begin{equation} \label{eq_macwilliams} \sum_{i\ge 0} a_i^* z^i=\frac{1}{2^k}\cdot \sum_{i\ge 0} a_i(1+z)^{n-i}(1-z)^i. \end{equation} Clearly we have $a_0=a_0^*=1$. In this paper we assume that all lengths are equal to the so-called effective length, i.e., $a_1^*=0$. A linear code is called projective if $a_2^*=0$. Let $C$ be a projective $[n,k]$ code. By comparing the coefficients of $z^0$, $z^1$, $z^2$, and $z^3$ on both sides of Equation~\ref{eq_macwilliams} we obtain: \begin{eqnarray} \sum_{i>0} a_i &=& 2^k-1,\label{mw0}\\ \sum_{i\ge 0} ia_i &=& 2^{k-1}n,\label{mw1}\\ \sum_{i\ge 0} i^2a_i &=& 2^{k-1}\cdot n(n+1)/2,\label{mw2}\\ \sum_{i\ge 0} i^3a_i &=& 2^{k-2}\cdot \left(\frac{n^2(n+3)}{2}-3a_3^*\right)\label{mw3} \end{eqnarray} The weight enumerator of a linear $[n,k]$ code $C$ can be refined to a so-called partition weight enumerator, see e.g.\ \cite{simonis1995macwilliams}. To this end let $r\ge 1$ be an integer and $\cup_{j=1}^r P_j$ be a partition of the coordinates $\{1,\dots,n\}$. By $I=\left(i_1,\dots,i_r\right)$ we denote a multi-index, where $0\le i_j\le p_j$ and $p_j=\#P_j$ for all $1\le j\le r$. With this, $a_I\in\mathbb{N}$ denotes the number of codewords $c$ such that $\#\left\{h\in P_j\,:\, c_h\neq 0\right\}=i_j$ for all $1\le j\le r$, which generalizes the notion of the counts $a_i$. By $a_I^*\in\mathbb{N}$ we denote the corresponding counts for the dual code $C^*$ of $C$. The generalized relation between the $a_I^*$ and the $a_I$ is given by: \begin{eqnarray} \!\!\!\!\!\!\!&& \sum_{I=\left(i_1,\dots,i_r\right)} a_I^* \prod_{j=1^r} z_j^{i_j} \notag\\ \!\!\!\!\!\!\!&=&\!\!\frac{1}{2^k}\cdot \!\!\!\!\sum_{I=\left(i_1,\dots,i_r\right)}\!\!\!\!\!\! a_I\prod_{j=1}^r \left(1+z_j\right)^{n-i_j}\left(1-z_j\right)^{i_j}\label{eq_macwilliams_partition} \end{eqnarray} The support $\operatorname{supp}(c)$ of a codeword $c\in\mathbb{F}_2^n$ is the set of coordinates $\left\{1\le i\le n\,:\, c_i\neq 0\right\}$. The residual of a linear code $C$ with respect of a codeword $c\in C$ is the restriction of the codewords of $C$ to those coordinates that are not in the support of $c$, i.e., the resulting effective length is given by $n-\operatorname{wt}(c)$. If $c$ is a codeword of a $q^r$-divisible $q$-ary code $C$, where $r\ge 1$, then the residual code with respect to $c$ is $q^{r-1}$-divisible, see e.g.\ \cite{honold2018partial}. The partition weight enumerator with respect to a codeword $c$ is given by Equation~(\ref{eq_macwilliams_partition}), where we choose $r=2$, $P_2=\operatorname{supp}(c)$, and $P_1=\{1,\dots,n\}\backslash P_2$, so that restricting to the coordinates in $P_1$ gives the residual code. \section{No projective $16$-divisible binary linear code of length $131$ exists} \label{sec_main_result} Assume that $C$ is a projective $16$-divisible $[131,k]$ code. Since for every codeword $c\in C$ the residual code is $8$-divisible and projective, we conclude from $\{3,19,35\}\subseteq \mathcal{E}_2(3)$, see e.g.\ \cite{honold2019lengths}, that the possible non-zero weights of the codewords in $C$ are contained in $\{16,32,48,64,80\}$. For codewords of weight $80$ the weight enumerator of the corresponding residual code can be uniquely determined: \begin{lemma} \label{lemma_8_div_n_51}(\cite[Lemma 24]{honold2018partial})\\ The weight enumerator of a projective $8$-divisible binary linear code of (effective) length $n=51$ is given by $W(z)=1+204z^{24}+51z^{32}$, i.e., it is an $8$-dimensional two-weight code. \end{lemma} \begin{lemma} \label{lemma_general_information} Each projective $16$-divisible $[131,k]$ code satisfies \begin{eqnarray*} a_{48} &=& -6 a_{16} - 3 a_{32} - 10 + 11\cdot 2^{k-9},\\ a_{64} &=& 8 a_{16} + 3 a_{32} + 15 +221\cdot 2^{k-8},\\ a_{80} &=& -3 a_{16} - a_{32} - 6 + 59\cdot 2^{k-9},\\ a_3^* &=& 2^{17-k} a_{16}+2^{15-k}a_{32} -311+5\cdot 2^{16-k}, \end{eqnarray*} $k\ge 9$, and $a_{80}\ge 4+3\cdot 2^{k-5}\ge 52$. \end{lemma} \begin{proof} Solving the constraints (\ref{mw0})-(\ref{mw3}) for $a_{48}$, $a_{64}$, $a_{80}$, and $a_3^*$ gives the stated equations for general dimension $k$. Since $a_{48}\in\mathbb{N}$ (or $a_{80}\in\mathbb{N}$) we have $k\ge 9$. Since $a_{48}\ge 0$, we have $6 a_{16} + 3 a_{32}\le 11\cdot 2^{k-9}-10$, so that $a_{80} = -3 a_{16} - a_{32} - 6 + 59\cdot 2^{k-9} \ge 4+3\cdot 2^{k-5}\ge 52$. \end{proof} First we exclude the case of dimension $k=9$: \begin{lemma} \label{lemma_exclude_k_9} No projective $16$-divisible $[131,9]$ code exists. \end{lemma} \begin{proof} For $k=9$ the equations of Lemma~\ref{lemma_general_information} yield \begin{eqnarray*} a_{48} &=& -6 a_{16} - 3 a_{32} + 1,\\ a_{64} &=& 8 a_{16} + 3 a_{32} + 457,\\ a_{80} &=& -3 a_{16} - a_{32} + 53, \text{ and}\\ a_3^* &=& 256 a_{16} + 64 a_{32} + 329 \end{eqnarray*} for a projective $16$-divisible $[131,9]$ code $C$. Since $a_{48}\ge 0$ and $a_{16},a_{32}\in \mathbb{N}$, we have $a_{16}=a_{32}=0$, so that $a_{48}=1$, $a_{64}=457$, $a_{80}=53$, and $a_3^*=329$. Now consider a codeword $c_{80}\in C$ of weight $80$ and the unique codeword $c_{48}\in C$ of weight $48$. In the residual code of $c_{80}$ the restriction of $c_{48}$ has weight $24$ or $32$ due to Lemma~\ref{lemma_8_div_n_51}. In the latter case the codeword $c_{80}+c_{48}\in C$ has weight $96$, which cannot occur in a projective $16$-divisible binary linear code of length $131$. Thus, we have that $c_{80}+c_{48}\in C$ gives another codeword of weight $80$. However, since $a_{80}$ is odd, this yields a contradiction and the code $C$ does not exist. \end{proof} \begin{lemma} \label{lemma_weight_16_or_32} A projective $16$-divisible binary linear code $C$ of length $131$ does not contain a codeword of weight $16$ or $32$. \end{lemma} \begin{proof} Let $c\in C$ be an arbitrary codeword of weight $80$ (which indeed exists, see Lemma~\ref{lemma_general_information}) and $c'\in C$ a codeword of weight $16$ or $32$. We consider the residual code $C'$ of $C$ with respect to the codeword $c$. From Lemma~\ref{lemma_8_div_n_51} we conclude that the restriction $\tilde{c}'$ of $c'$ in $C'$ has weight $0$, $24$, or $32$. Since $c+c'\in C$ has a weight of at most $80$, $\tilde{c}'$ is the zero codeword of weight $0$. In other words, we have $\operatorname{supp}(c')\subseteq\operatorname{supp}(c)$. If $L$ denotes the set of codewords of weight $80$ in $C$, then $ \operatorname{supp}(c') \subseteq \cap_{l\in L} \operatorname{supp}(l)=:M $, with $M\subseteq\{1,\dots 131\}$ and $\#M\ge 16$. Now let $D$ be the code generated by the elements in $M$, i.e., the codewords of weight $80$. By $k'$ we denote the dimension of $D$ and by $k$ the dimension of $C$. Since $D$ contains all codewords of weight $80$ and due to Lemma~\ref{lemma_general_information} we have \begin{equation} \label{ie_lb_ub} 4+3\cdot 2^{k-5}\le a_{80}\le 2^{k'}-1 \end{equation} for $C$. Since $\#M\ge 16$ each generator matrix $G$ of $D$ contains a column that occurs at least $16$ times, i.e., the maximum column multiplicity is at least $16$. If a row is appended to $G$ then the maximum column multiplicity can go down by a factor of at most the field size $q$, i.e., $2$ in our situation. Thus, we have $k'\le k-4$. Since Inequality~\ref{ie_lb_ub}) gives $$ 4+3\cdot 2^{k-5} \le 2^{k'}-1\le 2^{k-4}-1, $$ we obtain a contradiction. Thus, we conclude $a_{16}=a_{32}=0$. \end{proof} \begin{theorem} \label{main_thm} No projective $16$-divisible binary linear code of length $131$ exists. \end{theorem} \begin{proof} Assume that $C$ is a projective $16$-divisible $[131,k]$ code. From Lemma~\ref{lemma_weight_16_or_32} we conclude $a_{16}=a_{32}=0$, so that Lemma~\ref{lemma_general_information} yields $a_3^*=5\cdot 2^{16-k}-311$. Note that for $k\ge 11$ the non-negative integer $a_3^*$ would be negative. The case $k=9$ is excluded in Lemma~\ref{lemma_exclude_k_9}. In the remaining case $k=10$ we have $a_3^*=9$ and $a_{80}=112$. Now consider the residual code $C'$ of $C$ with respect to a codeword $c$ of weight $80$. Plugging in the weight enumerator for $C'$ from Lemma~\ref{lemma_8_div_n_51} in Equations~(\ref{mw0})-(\ref{mw3}) gives $a_3^*(C')=17$. Thus, we conclude $a_3^*(C)\ge 17$, which is a contradiction. \end{proof} We remark that some parts of our argument can be replaced using the partition weight enumerator from Equation~(\ref{eq_macwilliams_partition}). If we consider the partition weight enumerator with respect to a codeword $c$ of weight $80$, then we have $r=2$, $p_1=51$, and $p_2=80$. The possible indices where $a_I$ might be positive are given by $(0,0)$, $(0,16)$, $(0,32)$, $(0,48)$, $(0,64)$, $(0,80)$, $(24,24)$, $(24,40)$, $(24,56)$, $(32,32)$, and $(32,48)$. Clearly, we have $a_{(0,0)}=1$ and $a_{(0,80)}=1$. By considering the sums of a codeword with $c$ we conclude $a_{(0,16)}=a_{(0,64)}$, $a_{(0,32)}=a_{(0,48)}$, $a_{(24,24)}=a_{(24,56)}$, and $a_{(32,32)}=a_{(32,48)}$. From Lemma~\ref{lemma_8_div_n_51} we conclude $a_{(32,32)}=a_{(32,48)}=51\cdot 2^{k-9}$, $a_{(24,24)}=a_{(24,56)}=t$, and $a_{(24,40)}=204\cdot 2^{k-8}-2t$, where $k$ is the dimension of the code and $t\in \mathbb{N}$ a free parameter. Plugging into Equation~(\ref{eq_macwilliams_partition}) this gives $a_{(0,16)}+a_{(0,32)}=2^{k-9}-1$ for the coefficients of $t_1^0t_2^0$ since $a_{(0,0)}^*=1$. Using this equation automatically gives $a_{(1,0)}^*=0$, $a_{(2,0)}^*=0$, and $a_{(3,0)}^*=17$. Since $a_{(0,2)}^*=0$ the coefficient of $t_2^2$ gives $6320-7344\cdot 2^{k-9}+1024t+ 2224a_{(0,16)} + 176a_{(0,32)}=0$. Thus, we have $a_{(0,16)}=7\cdot 2^{k-10}-3-\tfrac{t}{2}$ and $a_{(0,32)}=2-5\cdot 2^{k-10}+\tfrac{t}{2}$. The coefficient of $t_1^1t_2^2$ then gives $a_{(1,2)}^*=408-3t\cdot 2^{14-k}$. For $k=9$ the non-negativity conditions $a_{(0,16)},a_{(0,32)}\ge 0$ force $t=1$, so that $a_{(0,0)}=1$, $a_{(0,16)}=a_{(0,64)}=0$, $a_{(0,32)}=a_{(0,48)}=0$, $a_{(0,80)}=1$, $a_{(24,40)}=406$, $a_{(24,24)}=a_{(24,56)}=1$, and $a_{(32,32)}=a_{(32,48)}=51$. It can be checked that all coefficients on the right hand side of Equation~(\ref{eq_macwilliams_partition}) are non-negative. $a_{(0,32)}\ge 0$ implies $t\ge 5\cdot 2^{k-9}-4$, so that $a_{(1,2)}^*$ would be negative for $k\ge 12$. Theorem~\ref{main_thm} implies a few further results. \begin{proposition} For $t\ge 0$ we have $A_2(8+5t,10;5)\le 3+2^8\cdot \frac{32^t-1}{31}$. \end{proposition} \begin{proof} Assume that $\mathcal{C}$ is a set of $4+2^8\cdot \frac{32^t-1}{31}$ $5$-dimensional subspaces in $\mathbb{F}_2^{8+5t}$ with pairwise trivial intersection. Then, the number of vectors in $\mathbb{F}_2^{8+5t}$ that are disjoint to the vectors of the elements of $\mathcal{C}$ is given by $\left(2^{8+5t}-1\right)-31\cdot \left(4+2^8\cdot \frac{32^t-1}{31}\right)=131$. Thus, by \cite[Lemma 16]{honold2018partial}, there exists a projective $2^{5-1}$-divisible binary linear code of length $n=131$, which contradicts Theorem~\ref{main_thm}. \end{proof} The recursive upper bound for constant-dimension codes mentioned in the introduction implies: \begin{corollary} We have $A_2(14,10;6)\le 67\,349$, $A_2(15,10;7)\le 17\,727\,975$, and $A_2(19,10,6)\le 70\,329\,353$. \end{corollary} As an open problem we mention that the non-existence of a projective $16$-divisible binary linear code of length $n=130$ would imply $A_2(15,12;6)\le 514$. \begin{lemma} \label{lemma_aux_1} For $k\ge 1$, $r\ge 3$, and $j\le 2r-1$ no projective $2^r$-divisible $\left[3+j\cdot 2^{r},k\right]$ code exists. \end{lemma} \begin{proof} In \cite[Theorem 12]{honold2018partial} it was proven that the length $n$ of a projective $2^r$-divisible binary linear code either satisfies $n>r2^{r+1}$ or can be written as $n=a\left(2^{r+1}-1\right)+b2^{r+1}$ for some non-negative integers $a$ and $b$. Using $r\ge 3$, we note that $3+j\cdot 2^{r}\le 3+(2r-1)\cdot 2^{r}= 3-2^r+r2^{r+1}<r2^{r+1}$. If $a\left(2^{r+1}-1\right)+b2^{r+1}=3+j\cdot 2^{r}$, then $3+a$ is divisible by $2^r$, so that $a\ge 2^r-3$. However, for $r\ge 3$ we have $a\left(2^{r+1}-1\right)+b2^{r+1}\ge \left(2^r-3\right)\cdot\left(2^{r+1}-1\right) >3+(2r-1)\cdot 2^r\ge 3+j\cdot 2^{r}$ -- contradiction. \end{proof} \begin{proposition} For $k\ge 1$, $r\ge 4$, and $j\le 2r$ no projective $2^r$-divisible $\left[3+j\cdot 2^{r},k\right]$ code exists. \end{proposition} \begin{proof} Due to Lemma~\ref{lemma_aux_1} it suffices to consider $j=2r$. The case $r=4$ is given by Theorem~\ref{main_thm}. For $r>4$ we proof the statement by induction on $r$. Assuming the existence of such a code, Equation~(\ref{mw1}) minus $r2^r$ times Equation~(\ref{mw0}) yields \begin{equation} \label{ie_special_2} \sum_{i>0} (i-r)2^r \cdot a_{i2^r}=3\cdot 2^{k-1}+r\cdot 2^r> 0. \end{equation} The residual code of a codeword of weight $i2^r$ is projective, $2^{r-1}$-divisible, and has length $3+(2r-i)\cdot 2^r$. If $i\ge r+2$, then we can apply Lemma~\ref{lemma_aux_1} to deduce $a_{i2^r}=0$. For $i=r+1$ the induction hypothesis gives $a_{i2^r}=0$. Since $(i-r)2^r \cdot a_{i2^r}\le 0$ for $i\le r$ the left hand side of Inequality~(\ref{ie_special_2}) is non-positive -- contradiction. \end{proof}
{'timestamp': '2020-06-19T02:12:34', 'yymm': '2006', 'arxiv_id': '2006.10382', 'language': 'en', 'url': 'https://arxiv.org/abs/2006.10382'}
arxiv
\section{Introduction} Small area estimation (SAE) describes the endeavor of producing estimates of quantities of interest, such as means and totals, for domains (usually areas) which have sparse or non-existent response data. SAE is carried out in many fields including health, demography, agriculture, business, education, and environmental planning. In this article we focus on health outcomes, for which SAE aids in highlighting geographical disparities, and is broadly useful for health planning, resource allocation and budgeting. SAE allows fundamental questions such as: ``how many people in my area have condition X or need treatment Y". Disease mapping which is traditionally based on a complete enumeration of disease cases, and differs from SAE which is typically based on a subset of individuals, selected via a survey, which may have a complex design. The standard reference on SAE is \cite{rao:molina:15}, while an excellent review is provided by \cite{pfefferman:13}. In survey sampling, inference has often focused on the {\it design-based} (or {\it randomization}) approach. This focus has carried over into SAE. This approach is quite distinct from the {\it model-based} approaches that are the bread and butter of mainstream spatial statistics. Both inferential approaches are discussed in \cite{skinner:wakefield:17}. Design-based methods assess the frequentist properties of estimators, averaging over all possible samples that could have been drawn, under the specified sampling design. Under this paradigm, the values of the responses in the population are viewed as fixed rather than random. Model-based approaches can be either frequentist or Bayesian. If a model-based approach is taken, a hypothetical infinite population model is specified for the responses, which are now viewed as random variables. Modeling may be carried out within the design-based paradigm via model-assisted approaches \citep{sarndal:etal:92} in which a model is specified but desirable design-based properties are retained, even under model misspecification. A cautious view \citep{lehtonen:veijanen:09} is that design-based (including model-assisted) inference may be reliable in situations when there are large or medium samples in areas, while if data are sparse, a model-based approach may be a necessity. In a companion article, \cite{datta:09} reviews, and is more enthusiastic toward, model-based approaches. Random effects modeling is popular under the model-based approach to SAE, and inference for these models is often frequentist through empirical Bayes estimation -- this is what we refer to as frequentist model-based inference, rather than the predictive approach described in \cite{valliant:etal:00}. If a model-based approach is taken, a key element of model specification (and a source of contention) is determining how to account for the sampling design. Models may be specified at the {\it area-level} or at the {\it unit-level}. For the former, an important reference is \cite{fay:herriot:79}, which introduced the idea of modeling a weighted estimate of an area-level characteristic. For the latter, \cite{battese:etal:88} describe a nested error regression model at the level of the sampling unit. Design-based inference from sample surveys aims to estimate finite population quantities using information about the sampling process. In a model-based framework, the finite population is itself a sample from a superpopulation a random process that can be described by some model. If, in an actual survey, the realized sample and the finite population can be described by the same model, then the sample design is ignorable. A simple random sample (SRS) is ignorable in this sense. However, most real-life household surveys have non-ignorable designs, and most SAE models depend on assumptions. When the design is not ignorable, one needs to incorporate the design into the model. Ideally, such incorporation would include the relevant aspects of the design including design weighting, non-response corrections, and weight adjustments (see Section \ref{sec:notation}). While this information may be available, many aspects of the sampling frame (such as the locations of all clusters in a design with cluster sampling) are typically not available, at least not in sufficient detail to be useful. For surveys such as the Demographic and Health Surveys (DHS), which are extensively carried out in low- and middle-income countries (LMIC), stratification, clustering and estimation weights will typically be available. For surveys in developed countries, little information may be available. Prevalence mapping \citep{wakefield:20:prevalence}, is a name that has been given to the production of maps displaying the prevalence of health and demographic outcomes, and this endeavor clearly has large overlaps with SAE. While SAE smoothing methods often use area-level models, prevalence mapping often uses model-based geostatistics (MBG) methods in which a continuous spatial model is specified. Examples of prevalence mapping using area-level SAE techniques include HIV prevalence \citep{gutreuter:etal:19} and the under-5 mortality rate (U5MR) \citep{dwyer:etal:2014,mercer:etal:15,li:etal:19}. Examples of prevalence mapping with MBG include HIV prevalence \citep{dwyer2019mapping}, malaria \citep{gething:etal:16}, U5MR \citep{golding:etal:17} and vaccination coverage \citep{utazi:etal:18}. \begin{figure}[htbp] \centering \includegraphics[width=0.8\linewidth]{figure1.png}\\ \caption{Estimates of HIV prevalence among females aged 15--29 in districts of Malawi in 2015--16. Top row estimates are from area-level models: direct estimates; smoothed direct estimates; smooth direct estimates with ANC HIV prevalence covariate. Bottom row estimates are from unit-level models: no urban/rural adjustment and no covariate; urban/rural adjusted only; urban/rural strata and ANC HIV prevalence covariate.} \label{fig:Malawi1} \end{figure} As a motivating example we consider SAE of HIV prevalence among females aged 15--29, in districts of Malawi, using data from the 2015--16 Malawi DHS. We will refer to the districts as admin-2 areas; in Malawi there are 3 admin-1 areas, 28 admin-2 areas and 243 admin-3 areas -- here we are using the GADM (database of global administrative areas) classification (\url{https://gadm.org/download_country_v3.html}). A two-stage stratified cluster sample was implemented, with the sampling clusters (enumeration areas) being stratified by district and urban/rural. The Malawi Population and Housing Census (MPHC), conducted in Malawi in 2008 provided the sampling frame for the survey. The sample for the 2015--16 Malawi DHS was designed to provide estimates of key indicators for the country as a whole, for urban and rural areas separately, and for each of the 28 districts. The sampling frame contained 12,558 clusters and our analyses use data from 827 sampled clusters (the supplementary materials give more details). In the 2015--16 DHS survey for Malawi, 8,497 women in the age range 15--49 were eligible for testing, and 93\% of them were tested. HIV prevalence data was obtained from voluntarily taken blood samples from DHS survey respondents. Testing is anonymous, and as such, respondents cannot receive their test results directly from DHS. Instead, they are given educational materials and referrals to voluntary, free counseling and testing. Blood samples are collected on filter paper via finger pricks before being sent to a laboratory for testing \citep{malawi2016}. Urban clusters were oversampled, relative to rural clusters (details are in the supplementary materials). We dropped the island district of Likoma, because it is spatially distinct (and quite culturally different from the nearest points on the mainland) and has a very small population. In the top left panel of Figure \ref{fig:Malawi1}, we plot the weighted prevalence estimates at the district level and see great variation and what appears to be an increasing gradient in HIV prevalence from north to south. However, the uncertainty (shown in the supplementary materials) is relatively large, particularly in the south. Ignoring the survey design gives a national prevalence estimate (standard error) of 6.28\% (0.37\%) for females aged 15--29, while the weighted estimate is 6.18\% (0.48\%). The weighted estimate is smaller because the weights account for the urban oversampling (HIV is more prevalent in urban areas) and the increased standard error is due to the clustering. The structure of this article is as follows. In Section \ref{sec:notation}, notation and basic ideas are presented before traditional methods of direct and indirect estimation are described in Section \ref{sec:traditional}. We focus on spatial methods that have not been covered in recent SAE reviews in Section \ref{sec:spatial}, with both area-level and unit-level models being described. Models of each kind are applied to the HIV prevalence data in Section \ref{sec:HIV}. The potential application of SAE methods to COVID-19 modeling is discussed in Section \ref{sec:COVID} and the paper concludes with a discussion in Section \ref{sec:discussion}. \section{Notation and Overview}\label{sec:notation} We will let $i$ index the areal units for which estimation is required, with $m$ areas in total. Assume there are $N_i$ individuals in the population with responses $y_{ik}$, $k=1,\dots,N_i$, in area $i$. We let $S_i$ represent the set of indices of the selected individuals in area $i$, with $n_i = |S_i|$ the number sampled in area $i$. From a design-based perspective $n_i$ may or may not be random, depending on the survey plan -- for example, if the small areas (domains) correspond to the strata in a stratified design (sometimes called {\it primary domains}) then the $n_i$ will be non-random. It is more typical for this not to be the case, and in this situation we have {\it secondary domains}. Under a model-based view, $n_i$ is conditioned upon and therefore fixed. We take as target of inference $m_i=\frac{1}{N_i} \sum_{k=1}^{N_i} y_{ik}$, the empirical mean of the response in the finite population. As examples of binary outcomes, interest may focus on the proportion of a population in an area that have a disease, have been vaccinated, or who are practicing social distancing (a much softer endpoint). This is a finite population characteristic, and such targets are common in survey sampling. Another common target is the total $ \sum_{k=1}^{N_i} y_{ik}$. In the model-based approach, the hypothetical infinite population mean in area $i$ is denoted $\mu_i$. This can be interpreted as the mean of the distribution from which the finite population was (hypothetically) drawn. We will focus on household surveys which are extremely popular, both in high-income countries (for example, in the United States, the National Crime Victimization Survey and the American Community Survey) and in LMIC (for example, the DHS, and Multiple Indicator Cluster Surveys). Sampling of respondents for household surveys based on face-to-face interviewing is usually conducted via stratified multi-stage cluster sampling. A sample of primary sampling units (PSUs) are drawn from what is typically an area-based sampling frame, such as enumeration areas in a population census. Most surveys employ stratification, usually by residence (urban and rural) and administrative units. Since stratification usually has very low cost, and somewhat reduces the variance of estimates, there is usually no reason to avoid stratification. From the point of view of estimating totals across the whole sample, an allocation of sampling units to strata that is proportional to the population size is preferable. Optimal allocation \citep[Section 3.4.2]{lohr:19}, where allocation of sampling units is proportional to the standard deviation of the estimator and size of the stratum, is preferable if the variances of the target estimator in each stratum are known and there is a single target estimator. In the case of most household surveys, the aim is to provide estimates of many different population quantities that all have different variances. Optimal allocation is, therefore, not possible. Proportional allocation ensures that the variances will not be worse than if the sample was by SRS. However, many surveys are disproportionally stratified because of the need to report on particular domains with similar precision, such as reporting by urban and rural or individual provinces. Nearly all surveys select PSUs by probability proportional to size (PPS), where the size measure is the number of households in each PSU as recorded in the sampling frame. A linear systematic PPS sample \citep[Section 8]{murthy:rao:88} can be obtained if the sampling units are arranged contiguously along the real number line, each unit occupying a space equal to its size $ N_i$. Let $T_i = T_{i-1}+N_i$, $i=1,\dots,m$, with $T_0=0$ and the sampling interval be $t=T_m/n$. Then, select a random point $r$ from 1 to $t$ and select unit $i$ if, $$ T_{i-1} < r+ j t \leq T_i,\qquad j=0,1,\dots,n-1. $$ If the size measure is constant for all sampling units, the sample becomes a linear systematic SRS. In a two-stage sample, which is the most common design, a list of households in each selected PSU is constructed, usually by mapping the cluster and listing every household by visiting every dwelling. A fixed number of households are then drawn using SRS or linear systematic SRS. The method has the benefit that the total sample size, both in total and in each cluster, is fixed by design. The fixed sample sizes thus reduce variance and ease the planning of the fieldwork. A key element in the design-based approach to inference are the {\it design weights}, which are the reciprocals of the {\it inclusion probabilities}. We now derive these probabilities for a stratified two-stage cluster design. Suppose there are $N_h$ households in strata $h$ with $N_{hc}$ being the number of households in cluster $c$, $c=1,\dots,C_h$, $h=1,\dots,H$. Hence, $H$ is the number of strata, and there are $C_h$ clusters in strata $h$. It is decided to sample $n_h$ clusters in strata $h$ using PPS sampling, so that the first stage inclusion probability for cluster $c$ in strata $h$ is $\pi_{1hc}=n_hN_{hc}/N_h$. Consequently, every cluster has a non-zero probability of being sampled. The number of households to sample in cluster $c$ of strata $h$ is $n_{hc}$. The second stage inclusion probability for sampling is $\pi_{2hc}=n_{hc}/N_{hc}$. The overall inclusion probability is therefore, $$\pi_{hc} = \pi_{1hc} \times \pi_{2hc}=\frac{n_hN_{hc}}{N_h} \times \frac{n_{hc}}{N_{hc}}=\frac{n_{h}n_{h,c}}{N_h}. $$ If a constant number of clusters is sampled at the second stage, i.e.,~$n_{h,c}=n$, then we write $m_h=n_h \times n$ and obtain $\pi_{hc}=m_h/N_h$, independent of $c$. Thus inclusion probabilities are equal within strata (self-weighting), provided the size measure (number of households) is equal for each PSU in the first and second stage. In sampling with more than two stages -- such as PSUs being districts, then second stage units being enumeration areas, and third stage units being households -- the second stage units are again selected by PPS to achieve equal probabilities of selection. Multi-stage sampling tends to increase variance substantially, because most of the variance accrues at the first stage of selection. Therefore, multi-stage sampling is usually avoided if possible. For SAE, surveys that use more than two stages are not ideal, because the sample becomes concentrated in the relatively few geographic areas that have been selected in the first stage. In stages selected with PPS, surveys in developing countries usually employ linear systematic PPS. The method has the benefit that it is simple and allows for implicit stratification if desired. Implicit stratification involves sorting the sampling frame by some variable, usually geographic location. If the selection is systematic, it is likely that adjacent selections will be more similar to each other than to non-adjacent selections. Pairs of adjacent clusters are therefore defined as implicit strata. The DHS used implicit stratification for early surveys but do not any longer. A great amount of energy is expended on calculating the variances of estimators. The drawback of linear systematic PPS is that the resulting selections of PSUs are dependent on each other. The lack of independence precludes the use of some variance estimators, such as the Yates-Grundy-Sen estimator \citep{yates:grundy:53}, that require the joint inclusion probabilities of PSUs, which cannot be defined. Therefore for variance calculation purposes, it is generally assumed that PSUs were sampled with replacement, even though this is not the case under linear systematic PPS. This assumption leads to a generally insignificant inflated variance estimate. Alternative PPS selection methods do exist, see \cite{brewer:hanif:13}, but are seldom used even though statistical suites such as SPSS and SAS provide them, as do several R-packages. Surveys in developed countries often employ different designs since more information is available to the sampler. Design based weights express the contribution of each selected sampling unit to the estimate of a population parameter. The starting point for weight construction is the design weights. They are the inverse of the product of the inclusion probabilities at each stage of sampling. The design weights thus directly reflect the sampling process. Imperfections, such as non-response, mar most surveys. A common way to deal with non-response is to adjust the weights, by up-weighting sampling units that are assumed to be similar to the non-responding sampling unit. The adjustment is typically carried out using neighboring units, for example, a group of geographically adjacent survey clusters, as adjustment cells. The estimation weight is then the product of the design weight and the inverse of the non-response rate for the cell. An alternative is predicting the response propensity of each sampling unit using, for example, logistic regression. The estimation weight then becomes the product of the design weight and the inverse of the predicted response probability for each sampling unit. Methods for adjusting for non-response are described in Chapter 8 of \cite{lohr:19}. Estimates of totals from sample surveys may also differ from known totals. For example, the age and gender distribution from a survey may be different from reliable population registration. To correct for the difference, post-stratification, raking, and calibration are sometimes used to adjust the weights so that the survey estimates match the known totals. Post-stratification divides the population into groups, for example by age and sex, and adjusts the weights within each group, so that known population totals are recovered. Raking does the same adjustment but to the marginals of the table formed by the classification variables. Calibration is similar but uses continuous variables instead of discrete. Post-stratification, raking, and calibration ideally impart information to the sample, and therefore reduce bias. These methods are commonly used in countries with good sources of information. They are sometimes used when the analyst believes that some sources, such as projections from a population census, are better than the survey estimates, but that is a practice that easily goes awry. In general, weight variation in household surveys increases variance with a factor of 1+$\mbox{CV}^2$ \citep{kish:92}, where CV is the coefficient of variation of the weights. Most household surveys strive for equal probability of selection, and therefore, constant weights at least within each stratum (as we saw with self-weighting). Equal weights are difficult to achieve in practice. Survey weight variation comes from three principal sources. The first source is disproportional allocation of sampling units to strata, which is a part of the design itself. The second are differences that arise because of differences between estimates of the number of sampling units in one stage of the sampling process and subsequent ones. For example, in a typical two stage cluster sample where the clusters are selected with PPS, inclusion probabilities will be equal for all households in a stratum if the number of households in each cluster used for selection in the first stage is the same as the number of households found in the listing of the clusters. Since the first stage numbers come from the sampling frame, which may be somewhat outdated, and the listing is carried out immediately before the survey, the difference between the two numbers is often large and leads to substantial weight variation. Third, weight variation may arise from non-response corrections, post-stratification, raking and calibration. Since the weight variation increases the variance, large weights are truncated in many surveys. The truncation trades the cost of a (hopefully) small bias for an often substantial reduction in variance, and therefore also MSE. As a result, the final data are the product of several random processes \citep{pfeffermann:11}. The first is the generating of population units. The second is the selection resulting from the application of the sampling design. The third is the selection of responding units, given that they have been included in the sample. Finally, there is usually an ad-hoc modeling step that is used to force sample statistics to resemble population parameters and reduce variance. \section{Traditional Methods}\label{sec:traditional} \subsection{Direct Estimation} A direct estimate of a quantity in a specific area and time period only uses data on the variable of interest from that area and time period. For simplicity of explanation, we assume that the strata correspond to the small areas of interest and that the weights are simply the reciprocal of the inclusion probabilities. We will also not explicitly index the clusters in this section, since we the discussion is relevant for general designs. The areas will be indexed by $i$, and let $d_{ik}$ be the design weight associated with individual $k$ in area $i$, whose response is $y_{ik}$. Within area $i$, the design-based weighted (direct) estimator \citep{horvitz:thompson:52,hajek:71} is \begin{equation}\label{eq:HT} \widehat m}^{\tiny{\mbox{HT}}}_i= \frac{\sum_{k \in s_{i}} d_{ik} Y_{ik} } {\sum_{k \in s_i} d_{ik} }, \end{equation} and its variance $V_i^\star$ may be calculated using standard methods; often the jackknife is used in a LMIC context \citep{pedersenandliu:2012}. A starting point for analysis is to map the weighted estimates. These weighted estimates have excellent properties (so long as the weights are reliable and stable), for example design consistency. If abundant data are available, no further modeling is needed. In general, the variance is $O(n_i^{-1})$ and so for small $n_i$ this approach will not be sufficient. In this case, models are necessary to allow for incorporation of covariate information and/or leveraging of spatial dependence between areas. \subsection{Indirect Estimation}\label{sec:indirect} We briefly describe a number of traditional indirect estimators, that are constructed to reduce the mean squared error (MSE), calculated under the randomization distribution. These estimators are generally design-based, but achieve a favorable MSE through variance reduction. Suppose we have covariates $\mbox{\boldmath $x$}_{ik}$, that are available on the complete population $k=1,\dots,N_i$, $i=1,\dots,m$. In a conventional regression analysis, attention focusses on the slope coefficients, but in SAE we are interested in $m_i$, and so it makes sense that we would want to make inferences about the responses of unobserved individuals. A {\it synthetic estimator} is, $$\widehat{m}_ ^{\tiny{\mbox{SYN}}} = \frac{1}{N_i} \sum_{k=1}^{N_i} \mbox{\boldmath $x$}_{ik}^{\mbox{\tiny{T}}} \widehat \mbox{\boldmath $B$}, $$ where, $$\widehat \mbox{\boldmath $B$}= \left[ \sum_{i=1}^m \sum_{k \in S_i}d_{ik} \mbox{\boldmath $x$}_{ik}^{\mbox{\tiny{T}}}\mbox{\boldmath $x$}_{ik} \right]^{-1} \sum_{i=1}^m \sum_{k \in S_i} d_{ik}\mbox{\boldmath $x$}_{ik}^{\mbox{\tiny{T}}}y_{ik},$$ are the slope estimates derived from the set of samples across {\it all} areas. The success of this estimator depends on how appropriate the regression model is for all areas. The variance will be $O(1/n)$, where $n=\sum_{i=1}^m n_i$ is the total sample size, but the possibility of large bias leads to this estimator being unpopular. Fitting separate models in each area is appealing, but then the small $n_i$ problem re-emerges. As a side note, one possible compromise would be to use spatially varying coefficient models in which each area has its own slope that is smoothed across areas. To deal with the potential large bias, the bias may be estimated to give the {\it survey-regression estimator}: \begin{eqnarray*} \widehat{m}_ ^{\tiny{\mbox{SR}}}&=& \frac{1}{N_i} \sum_{k=1}^{N_i} \mbox{\boldmath $x$}_{ik}^{\mbox{\tiny{T}}} \widehat \mbox{\boldmath $B$} + \frac{1}{N_i} \sum_{k \in S_i} w_{ik} (y_{ik} - \mbox{\boldmath $x$}_{ik}^{\mbox{\tiny{T}}} \widehat \mbox{\boldmath $B$}) \\ &=&\widehat{m}^{\tiny{\mbox{HT}}}_i + (\overline{\mbox{\boldmath $x$}}_i - \widehat{\overline{\mbox{\boldmath $x$}}}^{\tiny{\mbox{HT}}}_i)^{\mbox{\tiny{T}}} \widehat \mbox{\boldmath $B$} \end{eqnarray*} where $\widehat{m}^{\tiny{\mbox{HT}}}_i$ and $\widehat{\overline{\mbox{\boldmath $x$}}}^{\tiny{\mbox{HT}}}_i$ are the Horvitz-Thompson estimates of $m_i$ and $\overline{\mbox{\boldmath $x$}}_i$. This estimator is approximately design-unbiased but the variance is unfortunately back to $O(1/n_i)$. A composite estimator is of the form $$\widehat{m}_i^{\tiny{\mbox{COM}}} = \delta_i \widehat{m}_i^{\tiny{\mbox{SR}}} + (1-\delta_i) \widehat{m}_i^{\tiny{\mbox{SYN}}} $$ with $0 \leq \delta_i \leq 1$ estimated in such a way that for larger $n_i$ we have $\delta_i$ closer to 1. This estimator is intuitively appealing, and when motivated by a random effects model leads to a principled approach to estimation of $\delta_i$. \section{Spatial Smoothing Models}\label{sec:spatial} \subsection{Area-Level Models}\label{sec:arealevel} In this section and the next we focus on binary outcomes, because the Malawi HIV prevalence example falls under this umbrella. In a major advance, \cite{fay:herriot:79} introduced a very clever approach that models a transform of the weighted estimate, in order to gain precision by using a random effects model. For binary outcomes, one choice of transform is $Z_i= \mbox{logit} \left(\widehat m_i^{\tiny{\mbox{HT}}} \right)$, and let the associated design-based variance estimate be denoted $V_i$. An area-level model is, \begin{eqnarray} Z_i &\sim & \mbox{N}(\theta_i , V_i)\label{eq:smoothed1}\\ \theta_i &=& \mbox{\boldmath $x$}_i^{\tiny{\mbox{T}}} \mbox{\boldmath $\beta$} + e_i + S_i,\label{eq:smoothed2} \end{eqnarray} where $\theta_i$ is the logit of the true proportion in area $i$. Area-specific deviations from the regression model are modeled using a pair of random effects. The independent and identically distributed (iid) terms are $e_i \sim_{iid} \mbox{N}(0,\sigma_\epsilon^2)$ while the collection $\mbox{\boldmath $S$}=[S_1,\dots,S_n]$ are assigned a spatial distribution. The Fay-Herriot model did not include the spatial random effects $\mbox{\boldmath $S$}$, but the iid random effects only. Choices for the spatial distribution are described in \cite{banerjee:etal:15}, with common forms being the conditional autoregressive (CAR) and intrinsic CAR (ICAR) models. Both of these choices captures the concept that, in general, many outcomes are likely to be similar in locations that are close-by. \cite{mercer:etal:15} and \cite{li:etal:19} used these {\it smoothed direct} models in a space-time context, using spatial ICAR and temporal random walk components, along with a space-time interaction term. Both the CAR and ICAR choices are Markov random field (MRF) models, which offer computational advantages \citep{rue:knorrheld:05}. This model may be fit using a frequentist approach or a Bayesian approach in which priors are placed on the fixed effects (the $\mbox{\boldmath $\beta$}$'s) and on the variances/spatial dependence parameters. Design-based consistency is achieved (so long as the priors don't assign zero mass to the true $\theta_i$) since the $V_i$ term will tend to zero and the bias due to the random effects smoothing disappears asymptotically. Two practical difficulties with this approach are that the direct estimates may be on the boundary for a summary parameter that is not on the whole real line. For example, in the binary case we may have $\widehat m_i^{\tiny{\mbox{HT}}}$ equal to 0 or 1. In this case, $Z_i$ will be undefined. Further, a transform of the weighted estimator may not share the same design-based properties as the untransformed estimator, such as being design unbiased. These problems may be alleviated by using an unmatched sampling and linking model \citep{you:rao:02}. A second difficulty is that reliable variance estimates $V_i$ may be unavailable, particularly for areas with few/no samples. In this case, variance smoothing models can be used \citep[Section 6.4.1]{rao:molina:15}. \subsection{Unit-Level Models}\label{sec:unitlevel} In this section, we assume the units of analysis are clusters within a multi-stage cluster design. We let $\mbox{\boldmath $s$}_{ic}$ represent the geographical location of cluster $c$ in area $i$, and explicitly index the counts and sample sizes as $Y_{ic}$ and $n_{ic}$, respectively. A crucial assumption here (Section 4.3 of \cite{rao:molina:15}) is that the probability of selection, given covariates, does not depend on the values of the response (as discussed in the context of {\it ignorability} in Section \ref{sec:notation}). This implies that if stratified random sampling is used, stratification variables must be included in the model. One would expect cluster sampling to lead to correlated responses within clusters, and cluster-level random effects are introduced to accommodate this aspect \citep{scott:smith:69}. Another situation in which care is required is when PPS sampling is carried out. If the model used mis-specifies the relationship between the response and size then incorrect inference will result. To provide some protection against this, \cite{zheng:little:03} and \cite{chen:etal:10} model the response as a spline function of size for continuous and binary outcomes, respectively. For a binary response, a common model \citep{diggle:giorgi:19} is, \begin{eqnarray*} Y_{ic} | p_{ic} &\sim& \mbox{Binomial}(n_{ic},p_{ic}). \end{eqnarray*} Care must be taken when modeling $p_{ic}=p(\mbox{\boldmath $s$}_{ic})$, the response probability associated with location $\mbox{\boldmath $s$}_{ic}$. For a stratified design it is, in general, important to include fixed effects for each strata \citep{paige:etal:20}. In practice, there are a number of options when we have a design with strata that consist of urban/rural crossed with geographical districts. If there were no random effects, then strictly we would need interactions between district and urban/rural. However, the models we describe include spatial random effects (to leverage spatial dependence) and interactions would produce an unidentifiable model. Consequently, we include a single urban/rural effect and so are tacitly assuming that the association between the response and the urban/rural variable is approximately constant across areas. Another possibility, would be to include a spatially varying urban/rural coefficient, or model the associations separately in larger regions, in the spirit of what is sometimes done with synthetic estimation. One candidate model is, \begin{eqnarray} p_{ic} &=&\mbox{expit} \left( \beta_0+ \mbox{\boldmath $x$}(\mbox{\boldmath $s$}_{ic})^{\tiny{\mbox{T}}} \mbox{\boldmath $\beta$}_1 + z(\mbox{\boldmath $s$}_{ic}) \gamma+S(\mbox{\boldmath $s$}_{ic}) + \epsilon_{ic} \right) \end{eqnarray} where $z(\mbox{\boldmath $s$}_{ic})$ is the strata within which cluster $c$ lies, $\exp(\gamma)$ is the associated odds ratio, $\mbox{\boldmath $x$}(\mbox{\boldmath $s$}_{ic})$ are covariates available at location $\mbox{\boldmath $s$}_{ic}$, with odds ratios $\exp(\mbox{\boldmath $\beta$}_1)$. The spatial random effect $S(\mbox{\boldmath $s$}_{ic})$ is associated with cluster location $\mbox{\boldmath $s$}_{ic}$, and may be continuous or discrete. The cluster-level error $\epsilon_{ic} \sim \mbox{N}(0,\sigma_\epsilon^2)$ is the so-called {\it nugget}, which is traditionally taken to represent short scale variation and/or ``measurement error''. A model-based geostatistical model takes $S(\mbox{\boldmath $s$}_{ic})$, as a realization of a zero-mean Gaussian process (GP). GP models are common choices for continuous spatial models and imply that any collection of spatial random effects have a multivariate normal distribution. A popular choice for the variance-covariance \citep{stein:99} is the Mat\'ern covariance function, for which the covariance between is, $$ \mbox{cov}(S(\mbox{\boldmath $s$}_1),S(\mbox{\boldmath $s$}_2)) = \sigma_\mathrm{S}^2 \frac{2^{1-\nu_\mathrm{S}}}{\Gamma(\nu_\mathrm{S})} \left(\sqrt{8\nu_\mathrm{S}}\frac{||\boldsymbol{s}_2-\boldsymbol{s}_1||}{\rho_\mathrm{S}}\right) \mathrm{K}_{\nu_\mathrm{S}}\left(\sqrt{8\nu_\mathrm{S}}\frac{||\boldsymbol{s}_2-\boldsymbol{s}_1||}{\rho_\mathrm{S}}\right), $$ where $\rho_\mathrm{S}$ is the spatial range corresponding to the distance at which the correlation is approximately 0.1, $\sigma_\mathrm{S}$ is the marginal standard deviation, $\nu_\mathrm{S}$ is the smoothness (which is usually fixed, since it is difficult to estimate), and $\mathrm{K}_{\nu_\mathrm{S}}$ is a modified Bessel function of the second kind, of order $\nu_{\mathrm{S}}$. When the number of clusters $C$ is large, computation is an issue, because we need to manipulate $C \times C$ matrices which involves $O(C^3)$ operations \citep{rue:knorrheld:05}. Various approximations have been proposed to overcome this problem, for example, the stochastic partial differential equations (SPDE) approach pioneered by \cite{lindgren:etal:11} -- this is the approach we use in Section \ref{sec:HIV}. Other approaches are described by \cite{heaton:etal:18}. Aggregation to the area-level is carried out via, \begin{equation}\label{eq:area} p_i = \int_{A_i} p(\mbox{\boldmath $s$}) \times q(\mbox{\boldmath $s$})~d\mbox{\boldmath $s$} \approx \sum_{l=1}^{M_i} p(\mbox{\boldmath $s$}_l) \times q(\mbox{\boldmath $s$}_l) \end{equation} where $p(\mbox{\boldmath $s$}) = \mbox{expit}( \beta_0+ \mbox{\boldmath $x$}(\mbox{\boldmath $s$})^{\tiny{\mbox{T}}} \mbox{\boldmath $\beta$}_1+z(\mbox{\boldmath $s$}_{ic}) \gamma + S(\mbox{\boldmath $s$}))$ is the risk at location $\mbox{\boldmath $s$}$ (the nugget is, for better or worse, frequently left out, since it is viewed as measurement error) and $q(\mbox{\boldmath $s$})$ is the population density at $\mbox{\boldmath $s$}$, which is needed at all locations on the approximating mesh, $\mbox{\boldmath $s$}_l$, $l=1,\dots,M_i$. Cluster level covariate models are appealing when compared to area-level covariate alternatives, since they are closer to the mechanism of action, and reduce the possibility of ecological bias \citep{wakefield:08}. A large disadvantage in an SAE context is that to aggregate to the area-level, at which inference is required, one needs to know the values of the covariates on the mesh, including the design variables. Obtaining reliable population density and covariate surfaces is not straightforward. The direct and smoothed direct approaches avoid the need for a population surface, since the weights implicitly include population information from the original sampling frame. An alternative, overdispersed binomial, unit-level model that we use for the HIV prevalance data is, \begin{eqnarray} Y_{ic} | p_{ic},\lambda &\sim& \mbox{BetaBinomial}(n_{ic},p_{ic},\lambda )\label{eq:BB1}\\ p_{ic} &=&\mbox{expit} \left( \beta_0+ \mbox{\boldmath $x$}_{i}^{\tiny{\mbox{T}}} \mbox{\boldmath $\beta$}_1 + z_{ic} \gamma+ e_i + S_i \right)\label{eq:BB2} \end{eqnarray} where $\lambda$ is the overdispersion parameter and we have taken the spatial random effect to be decomposed as $S(\mbox{\boldmath $s$}_{ic})=e_i + S_i$, with $e_i$ and $S_i$ as in (\ref{eq:smoothed2}). The marginal variance is $\mbox{var}(Y_{ic}) = n_{ic}p_{ic}(1-p_{ic})[1+(n_{ic}-1)\lambda]$ so that small values of $\lambda$ correspond to little overdisperison. The aggregate risk is far easier to evaluate than the continuous spatial model, i.e.,~as calculated via (\ref{eq:area}), since all clusters in the same strata have identical risk, to give, \begin{equation} p_i = (1-q_i)\times \mbox{expit}( \beta_0+ e_i + S_i ) +q_i\times \mbox{expit} ( \beta_0+ \mbox{\boldmath $x$}_{i}^{\tiny{\mbox{T}}} \mbox{\boldmath $\beta$}_1+ e_i + S_i ) \label{eq:aggmesh} \end{equation} where $q_i$ is the proportion of the relevant population in the area that is urban. Dyed-in-the-wool ,design-based aficionados are wary of models such as the ones described in this section, because establishing design consistency is very difficult. \section{SAE for HIV Prevalence Mapping}\label{sec:HIV} We return to the HIV prevalence example, and fit both area-level and unit-level models. All fitting was done in the {\tt R} programming environment. The smoothing models were fit using the {\tt INLA} package, which provides Bayesian inference via a fast implementation using the method described in \cite{rue:etal:09} and \cite{rue:etal:17}. To obtain the weighted estimates and variances for the areas, the {\tt survey} package \citep{lumley:04} was used. A number of the models can be conveniently fitted in the {\tt SUMMER} package \citep{martin:etal:18}. For the discrete spatial model we use the BYM2 parameterization \citep{riebler:etal:16} in which we have $b_i=e_i+S_i$ (in equation (\ref{eq:smoothed2})) and an overall variance parameter $\sigma^2_b$ for $b_i$, and a parameter, $\phi$, that represents the proportion of the variance that is spatial. In all analyses we use penalized complexity (PC) priors \citep{simpson:etal:17}, details of which may be found in the supplementary materials. \subsection{Area-Level Models} In high-income countries, the census (and other sources) provide variables on all of the population in small areas of interest. In this case, weighted estimates can be obtained from model-assisted procedures, such as those described in Section \ref{sec:indirect}, which can be smoothed, if needed. Unfortunately, in LMIC, there are few candidate variables, and so instead we use the smoothed direct model (\ref{eq:smoothed1})--(\ref{eq:smoothed2}) and include as a covariate the (logit of) the prevalence estimates obtained from antenatal care (ANC) facilities. Specifically, we use data from 2016, taken from Malawi Ministry of Health quarterly integrated HIV program reports. This covariate corresponds to the HIV prevalence of pregnant women attending health facilities to receive ANC, aggregated to the district level (a map of this covariate can be found in the supplementary materials). The left panel of Figure \ref{fig:various} shows the logits of the direct estimates against the logits of the ANC prevalence estimates, with a reference line added. Not surprisingly, we see a strong association. The smoothed direct model estimates without the ANC covariate are shown in the top middle panel of Figure \ref{fig:Malawi1}. The shrinkage (overall via the iid random effects, and locally via the ICAR random effects) is apparent, with a flatter map compared to the direct estimates. The posterior uncertainty is reduced (see supplementary materials). The average standard error of the direct estimates is 0.018 and the average posterior standard deviations under the smoothed direct model is reduced by 17\%. When moving from the no covariate, smoothed direct model to the model including the ANC covariate, the posterior median of $\sigma_b$ (reflecting the amount of residual variation) changes from 0.40 to 0.14, and $\phi$ (the proportion of spatial variation) goes from 0.56 to 0.26. The odds ratio (95\% credible interval) associated with the logit ANC covariate is 2.8 (2.0, 3.8) so the association is very strong, which explains why the across-district residual variability is so reduced when the covariate is added. The strong spatial structure of the covariate explains why $\phi$ is reduced. The dream of spatial modeling is to find covariates that make the area-level random effects ``go away". The top right panel of Figure \ref{fig:Malawi1} shows the estimates from the smoothed direct model that includes the ANC covariate. The supplementary materials contain comparison plots of the estimates and their uncertainties under various models. The smoothed direct model with the ANC covariate has a 39\% reduction in the uncertainty, when compared to the direct estimates. The pattern of lower prevalence in the north, with higher levels in the south is still apparent in the smoothed estimates. Even with the spatial smoothing and use of the covariate, the uncertainty in the ranking of areas is still large. The supplementary materials contains distributions on the rankings under six different models. Mulanje consistently comes out as the district with the highest HIV prevalence among women ages 15--29. \begin{figure}[htbp] \centering \includegraphics[width=0.4\linewidth]{fig2_left.pdf} \includegraphics[width=0.45\linewidth]{fig2_right.pdf} \caption{Left: logit of direct prevalence estimates versus logit of ANC prevalence estimates -- we see a strong association. Right: District prevalence estimates from two unit-level models. On the y-axis, the prevalence estimates are from a model with no urban/rural adjustment, while on the x-axis the model has an adjustment. The estimates from the no adjustment model are too high because of the oversampling of urban areas, which have higher HIV prevalence.} \label{fig:various} \end{figure} \subsection{Unit-Level Models} We fit three betabinomial models (\ref{eq:BB1})--(\ref{eq:BB2}): (1) no urban/rural and no covariates, (2) urban/rural and no covariates, (3) urban/rural and ANC covariate. Model (1) should not be used, as it does not account for the urban/rural stratification; we include to demonstrate the bias this introduces. The bottom row of Figure \ref{fig:Malawi1} shows the fits from these three models. Again, the smoothness compared to the direct estimates is apparent, and the fits are quite similar to the smoothed direct models. Closer examination reveals differences, however. The supplementary materials gives comparisons of all the estimates. It is clear that leaving the urban/rural covariate out of the model leads to bias. From the sampling frame we know the number of clusters that are urban and rural (this information is given in the supplementary materials) which can be directly used for the aggregation to the admin-2 level, via (\ref{eq:aggmesh}). In the no covariate model the odds ratio associated with being urban is 2.3 (1.8,2.9) and this hardly changes when the ANC variable is added. This more than doubling of the odds is a cluster level association. The odds ratio associated with the ANC covariate is 2.3 (1.7, 3.1), so the association is also strong. The reductions in the total spatial residual terms, and the proportion of this variance that is spatial both plummeted when the ANC covariate was included in the model. As compared to the average standard errors of the direct estimates, the average posterior standard deviations for models (1)--(3) above were 18\%, 29\% and 43\% lower., respectively So there is a greater reduction in uncertainty under the unit-level models than under the area-level models. The estimates from model (1) are clearly biased (they are too high) because of the non-adjustment for urban/rural. For the three models the posterior medians of $\sigma_b$ (representing the standard deviation of the residual variation on the logistic scale) are 0.39, 0.38, 0.18. The proportion of the variation that is spatial is 0.60, 0.67, 0.30. Hence, we see the same pattern as the area-level modeling with the inclusion of the ANC covariate greatly reducing the residual uncertainty and the proportion that is spatial. We also calculate estimates for the 243 admin-3 areas, which is more difficult with the smoothed direct model, because of data sparsity (26 of the areas contain no data). The supplementary materials contain summaries of this analysis. These results should be viewed with some caution, since model-checking at this level is very difficult, and the aggregation depends on knowing the proportion of each admin-3 area that is urban. Finally, we fit the continuous spatial model, with and without the area-level covariate and produce pixel-level estimates of the HIV prevalence. This analysis should also be viewed with caution, particularly for the admin-2 summaries, since the aggregation required a mesh specific estimate of urban/rural. We use WorldPop population density estimates \citep{stevens:etal:15,wardrop:etal:18}. Specifically, using the known proportion of clusters that are labeled as urban in the sampling frame we create a population density threshold (to give the correct urban proportion of the population when a geographic partition is formed, based on this threshold), and then we can obtain an urban/rural mesh to use in (\ref{eq:aggmesh}). Results of these analyses are contained in the supplementary materials. There are a number of outstanding issues with the unit-level model-based analyses that need further consideration. In general, the weights have three components: design, non-response and post-stratification/raking and one needs to consider all three. We have discussed the stratification aspect, but further thought is required for non-response, while post-stratification from a modeling perspective has been considered \citep{gelman:07}. In practice, the urban/rural covariate is not known with any great accuracy geographically, and the impact of this on inference needs to be investigated. \subsection{Model Assessment} One of the hardest parts of SAE is model assessment. The direct estimates, $\widehat{m}^{\tiny{\mbox{HT}}}_i$ if available, provide one standard for comparison. Asymptotically, $\widehat{m}^{\tiny{\mbox{HT}}}_i \sim \mbox{N}( m_i,V^\star_i)$. One strategy is to systematically remove one area at a time, and then obtain a prediction of the missing area's prevalence, based on the remaining 26 districts. The supplementary materials contain plots of the direct estimates versus the predicted estimates, and we see systematic problems with the models that leave out the urban/rural covariate. The performance of both the smoothed direct (area-level) model with the ANC covariate and the unit-level model with urban/rural and ANC prevalence is superior to the other models. The DIC and log CPO summary measures supported this conclusion. Checking the admin-3 estimates is far more difficult because there is no reliable direct estimates for comparison in a cross-validation exercise. \section{Application of SAE Techniques to COVID-19 Modeling}\label{sec:COVID} Coronavirus disease (COVID-19) is an infectious disease caused by the SARS-CoV-2 virus. There are many endpoints that are of interest in geographical studies including: disease prevalence, disease incidence, the number and fraction of people who have been infected with SARS-CoV-2 (via an antibody test), measures of social distancing, and excess mortality. Estimating each of these responses over time and by age, gender, and race is also highly desirable. Many study/data types would not fall under the heading of SAE because they are based on routine surveillance data and are nominally a complete enumeration. Surveillance data are often examined via space-time {\it disease mapping} or {\it cluster detection} techniques \citep{waller:gotway:04}. Seroprevalence studies, in which blood samples are taken from sampled individuals and examined for antibodies, have been carried out to estimate the number of infections due to SARS-CoV-2. With an appropriate sampling design, and a reliable test, such studies can be used to estimate the proportion of the population, by demographic groups, who have been previously infected by SARS-CoV-2. These studies can be used for SAE, if the numbers sampled are sufficiently large. \cite{stringhini:etal:20} describe a seroprevalence study carried out in Geneva, Switzerland, with participants taken from an existing study that contained a stratified sample from the study population (the canton of Geneva). The selection of individuals is key since, for example, those reporting at health facilities (who are subsequently tested) are not representative of the population. Unfortunately, many of the early seroprevalence studies came (justifiably) under fire for data quality issues and for sampling from ill-defined populations, which leads to great difficulties with interpretation. This is well-documented by \cite{vogel:20}, who gives a number of examples. Health researchers are under intense pressure, given they are working in the context of the political and press feeding-frenzy for results to be made available. This has lead to inadequate validation of the antibody tests used and limited scientific scrutiny of the design of studies through peer-review. It has been documented that certain subgroups (for example, based on age, sex, race) are disproportionately affected by COVID 19, and as such, a stratified analysis may be used to reliably estimate outcomes of interest. But the numbers required will be large if a small area analysis is envisaged, given the relative rarity of death from COVID-19, in particular. A potential drawback with traditional survey sampling and SAE in the context of COVID-19 is the possibility that seroprevalence or incidence is highly clustered. There are two notions of clustering that are important here. The first is infectious network clustering, i.e.,~that an infected person infects others in his or her network. Such clustering, while intrinsic to any infectious disease, may or may not lead to the other form of clustering, namely geographic clustering. Geographic clustering of COVID-19 is common, both in communities and in institutions (there are many factors which may lead to this, including the propensity for individuals of common demographic groups, or having high-risk, tending to live in close proximity). When geographic clustering is present, a large proportion of the infected population may be located in relatively few survey clusters, many of which may be geographically adjacent. Since a typical cluster sample design spreads out the sample clusters over a geographic region, there is a large chance that the sample will not pick up the high prevalence areas. One may solve the problem by increasing the sample size, but that rapidly becomes costly. An alternative is adaptive cluster sampling \citep{thompson:92, thompson:seber:96}. An ordinary cluster sample is first drawn. Then, each selected cluster is listed and target individuals identified (e.g.,~persons with a positive test for Sars-CoV-2). If the number of target individuals is larger than a given threshold, then clusters that share a border with the initial cluster are included in the survey. The process is repeated for each of the adjacent clusters, until a network of clusters is formed that has no adjacent cluster thst satisfies the threshold. If the threshold is well selected, then the adaptive cluster sample will pick up geographically based networks of infection well. If it is set too low, then all clusters in the frame will be included. If the threshold is too high, the sample limits itself to the initial sample. With a target population that is clustered and judicious setting of the threshold value, adaptive cluster sampling can be very efficient. Unfortunately, there is no optimal sampling strategy for adaptive cluster sampling \citep{turk:borkowski:05,thompson:seber:96}, so the exact choice of design must be piloted. A potential disadvantage of adaptive cluster sampling is that while it may be efficient for the estimator that informs the design, such as the prevalence of a disease, it is not necessarily efficient for estimators of other population quantities. Thus, if the survey aims to estimate additional quantities other than the one designed for, one might have to consider other designs. This problem is, to some extent, mitigated by the fact that many other quantities may be both easy to estimate and not require narrow confidence bands. For example, the proportion of people using face masks may not require as precise an estimate as a seroprevalence estimate. Looking into the future, given the successful development of a vaccine, one could use SAE techniques to estimate vaccination coverage rates. Such an approach has been used in many different settings: BCG, DPT, OPV, and measles in India \citep{pramanik:etal:15} and DPT in Africa \citep{mosser:etal:19}. In the United States (US), in the absence of a national register, particular outcomes can be geographically examined using survey data. \cite{albright:etal:19} carried out SAE at the county level in Alabama for human papillomavirus (HPV) in counties of Alabama using data from the National Immunization Survey. To get at transmission dynamics, one needs to fit more complex models such as susceptible-exposed-infected-removed (SEIR) models. Unfortunately, there are a number of serious drawbacks for using such models in a SAE enterprise. The first is that the data required are not routinely available, with the usual problems of under- and mis-reporting being a serious problem. The second is that fitting stochastic models is very challenging, see the references in \cite{fintzi:etal:17}. To avoid the computational difficulties one may use deterministic compartmental models \citep{anderson:may:91} and then map summary statistics such as the reproductive number $R_0$. In large populations such models may perform well, but such models may perform poorly when the system is far from its deterministic limit \citep{andersson:britton:00}; inference is also difficult because error terms are ``added on" rather than the stochastic and deterministic parts of the models being entwined, as is the ideal for a statistical model. However, such models are far preferable to simple curve-fitting exercises in which some generic function is fit to data -- such approaches are likely to perform very poorly for predictions of complex phenomena because they (basically) contain little of the science or relevant context. The impact of interventions, such as social distancing and vaccination campaigns is also impossible to determine with such approaches. \section{Discussion}\label{sec:discussion} SAE is a huge topic and we have been selective in this review, focusing on the use of Bayesian spatial models for analyzing survey data. There is a disconnect between the spatial statistics and SAE research communities. The former are very cavalier about ignoring the survey design and the latter tend to use simple discrete spatial models (or include iid spatial random effects only) and empirical Bayes estimation. Regular spatial modeling with binary data does not emphasize consistency, perhaps because the parameters of nonlinear random effects models are not generally consistent, unless the model is correctly specified. Outside of the linear model, results on frequentist (model-based) consistency for the parameters of spatial models are few and far between. It is desirable that when area-level estimates are aggregated they are in agreement with estimates for larger areas within which they are nested. The estimates in the larger areas may be well estimated due to larger sample sizes and additional data. Such benchmarking is an important endeavor in many applications. For example, \cite{li:etal:19} produced small area estimates of under-5 mortality in 25 countries using DHS data and benchmarked to the official UN national estimates, which use far more extensive data sources. Many approaches have been suggested. In particular, we find the Bayesian method of \cite{zhang:bryant:20} very appealing, and it could be used with the area-level and unit-level models we have described. We have discussed both discrete and continuous spatial models. The former have dominated the SAE literature, and have many appealing features including computational efficiency, a wealth of experience in their use, and robustness to different data generating mechanisms \citep{paige:etal:20}. However, the discrete spatial models always have an ad hoc neighborhood specification, which is unfortunate. Continuous spatial model are far more appealing in this respect, and also allow data that are aggregated to different levels to be combined \citep{wilson:wakefield:20}. But continuous spatial models have greater computational challenges, and careful prior specification is required \citep{fuglstad:etal:19}. There is a growing literature on accounting for errors in the covariates used for modeling in the SAE literature with various errors-in-variables models being considered \citep{ybarra:lohr:08,barber:etal:16,burgard:etal:19}; see Section 6.4.4 of Rao and Molina (2015)\nocite{rao:molina:15} for a review. Finally, as more and more data streams become available, there is a growing need for methods that combine data in appropriate ways, and this is especially true of SAE. For example, in a LMIC context, data may be available from a variety of surveys with different designs, sample vital registration systems and censuses. Synthesizing such data is not straightforward but can offer great benefits if carried out successfully. \vspace{.3in} \noindent {\bf Acknowledgments:} The authors would like to thank the Malawi Ministry of Health for allowing the use of the ANC data, and Jeff Eaton for helpful comments on the manuscript. \bibliographystyle{natbib}
{'timestamp': '2020-06-19T02:08:21', 'yymm': '2006', 'arxiv_id': '2006.10266', 'language': 'en', 'url': 'https://arxiv.org/abs/2006.10266'}
arxiv
\section{Introduction}\label{sec:intro} The multi-branch architecture of neural networks, where each block consists of more than one parallel components, is one of the key ingredients to the success of deep neural models and has been well studied in computer vision. Typical structures include the inception architectures~\cite{szegedy2015going,szegedy2016rethinking,szegedy2017inception}, ResNet~\cite{he2016deep}, ResNeXt~\cite{xie2017aggregated}, DenseNet~\cite{huang2017densely}, and the network architectures discovered by neural architecture search algorithms~\cite{pham2018efficient,liu2019darts}. Models for sequence learning, a typical natural language processing problem, also benefit from multi-branch architectures. Bi-directional LSTM (BiLSTM) models can be regarded as a two-branch architecture, where a left-to-right LSTM and a right-to-left LSTM are incorporated into one model. BiLSTM has been applied in neural machine translation (briefly, NMT)~\cite{zhou2016deep,wu2016google} and pre-training~\cite{peters2018elmo}. Transformer~\cite{vaswani2017attention}, the state-of-the-art model for sequence learning, also leverages multi-branch architecture in its multi-head attention layers. Although multi-branch architecture plays an important role in Transformer, it has not been well studied and explored. Specifically, using hybrid structures with both averaging and concatenation operations, which has been widely used in image classification tasks~\cite{xie2017aggregated,szegedy2016rethinking}, are missing in current literature for sequence learning. This motivates us to explore along this direction. We propose a simple yet effective variant of Transformer, which treats a multi-head attention layer as a branch, duplicates such an attention branch for multiple times, and averages the outputs of those branches. Since both the concatenation operation (for the multiple attention heads) and the averaging operation (for the multiple attention branches) are used in our model, we call our model {\em multi-branch attentive Transformer} (briefly, MAT) and such an attention layer with both the concatenation and adding operations as the multi-branch attention layer. Due to the increased structure complexity, it is challenging to directly train MAT. Thus, we leverage two techniques for MAT training. (1) {\em Drop branch}: During training, each branch should be independently dropped so as to avoid possible co-adaption between those branches. Note that similar to Dropout, during inference, all branches are used. (2) {\em Proximal initialization}: We initialize MAT with the corresponding parameters trained on a standard single-branch Transformer. Our contributions are summarized as follows: \noindent(1) We propose a simple yet effective variant of Transformer, multi-branch attentive Transformer (MAT). We leverage two techniques, drop branch and proximal initialization, to train this new variant. \noindent(2) We conduct experiments on three sequence learning tasks: neural machine translation, code generation and natural language understanding. On these tasks, MAT significantly outperforms the standard Transformer baselines, demonstrating the effectiveness of our method. \noindent(3) We explore another variant which introduces multiple branches into feed-forward layers. We find that such a modification slightly hurts the performance. \section{Background}\label{sec:background} \subsection{Introduction to Transformer} A Transformer model consists of an encoder and a decoder. Both the encoder and the decoder are stacks of blocks. Each block is mainly made up of two types of layers: the multi-head attention layer and the feed-forward layer (briefly, FFN). We will mathematically describe them. Let $\texttt{concat}(\cdots)$ denote the concatenation operation, where all inputs are combined into a larger matrix along the last dimension. Let $\multiattn{M}$ and $\texttt{attn}$ denote a multi-head attention layer with $M$ heads ($M\in\mathbb{Z}_+$) and a standard attention layer. A standard attention layer~\cite{bahdanau2015neural,vaswani2017attention} takes three elements as inputs, including query $Q$, key $K$ and value $V$, whose sizes are $T_q\times d$, $T\times d$ and $T\times d$ ($T_q, T, d$ are integers). $\texttt{attn}$ is defined as follows: \begin{equation} \texttt{attn}(Q,K,V)=\texttt{softmax}\Big(\frac{QK^\top}{\sqrt{d}}\Big)V, \end{equation} where \texttt{softmax} is the softmax operation. A multi-head attention layer aggregates multiple attention layers in the concatenation way: \begin{equation} \begin{aligned} & \multiattn{M}(Q,K,V)=\texttt{concat}(H_1,H_2,\cdots,H_M); \;H_i=\texttt{attn}(QW^i_Q,KW^i_K,VW^i_V),\;i\in[M], \end{aligned} \label{eq:multi_head_attention} \end{equation} where $[M]$ denotes the set $\{1,2,\cdots,M\}$. In Eqn.\eqref{eq:multi_head_attention}, the $W$'s are the parameters to be learned. Each $W$ is of dimension $T\times (d/M)$. The output of $\multiattn{M}$ is the same size as $Q$, i.e., $T_q\times d$. In standard Transformer, an FFN layer, denoted by $\texttt{FFN}$, is implemented as follows: \begin{equation} \texttt{FFN}(x)=\max(xW_1 + b_1, 0)W_2 + b_2, \end{equation} where $x$ is a $1\times d$-dimension input, $\max$ is an element-wise operator, $W_1$ and $W_2$ are $d\times d_h$ and $d_h\times d$ matrices, $b_1$ and $b_2$ are $d_h$ and $d$ dimension vectors. Usually, $d_h>d$. In the encoder of a Transformer, each block consists of a self-attention layer, implemented as a $\multiattn{M}$ where the query $Q$, key $K$ and value $V$ are the outputs of previous layer, and an FFN layer. In the decoder side, an additional multi-head attention is inserted between the self-attention layer and FFN layer, which is known as the encoder-decoder attention: $Q$ is the output of the previous block, $K$ and $V$ are the outputs of the last block in the encoder. \subsection{Multi-branch architectures for sequence learning} As shown in Section~\ref{sec:intro}, multi-branch architectures have been well investigated in image processing. In comparison, the corresponding work for sequence learning is limited. The bidirectional LSTM, a two-branch architecture, has been applied in machine translation~\cite{zhou2016deep,wu2016google} and pre-training techniques like ELMo~\cite{peters2018elmo}. \cite{song2018double} proposed two use both convolutional neural networks and Transformer in the encoder and decoder. Similar idea is further expanded in \cite{zhao2019muse}. A common practice of the previous work is that they focus on which network components (convolution, attention, etc.) should be used in a multi-branch architecture. In this work, we do not want to introduce additional operations into Transformer but focus on how to boost Transformer with its own components, especially, where and how to apply the multi-branch topology, and figure out several useful techniques to train multi-branch architectures for sequence learning. Such aspects are missing in previous literature. \section{Multi-branch attentive Transformer}\label{sec:alg} In this section, we first introduce the structure of multi-branch attentive Transformer (MAT) in Section~\ref{sec:network_arch}, and then we introduce the drop branch technique in Section~\ref{sec:drop_branch}. The proximal initialization is described in Section~\ref{sec:prox_init}. \subsection{Network architecture}\label{sec:network_arch} The network architecture of our proposed MAT adopts the backbone of standard Transformer, except that all multi-head attention layers (including both self-attention layers and encoder-decoder attention layers) are replaced with the {\em multi-branch attention layers}. Let $\texttt{mAttn}_{N_a,M}(Q,K,V)$ denote a multi-branch attention layer, where $N_a$ represents the number of branches and each branch is a multi-head attention layer with $M$ heads $\multiattn{M}$. $Q$, $K$ and $V$ denote query, key and value, which are defined in Section~\ref{sec:background}. Mathematically, $\texttt{mAttn}_{N_a,M}(Q,K,V)$ works as follows: \begin{equation} \texttt{mAttn}_{N_a,M}(Q,K,V)=Q + \frac{1}{N_a}\sum_{i=1}^{N_a}\multiattn{M}(Q,K,V;\theta_i), \label{eq:multi-branch_attention_layer_infer} \end{equation} where $\theta_i = \{W^i_Q,W^i_K,W^i_V\}_{i=1}^{M}$ (see Eqn.\eqref{eq:multi_head_attention}) is the collection of all parameters of the $i$-th multi-head attention layer. \subsection{Drop branch technique}\label{sec:drop_branch} As mentioned above, multiple branches in multi-branch attention layers have the same structure. To avoid the co-adaptation among them, we leverage the drop branch technique. The inspiration comes from the dropout~\cite{srivastava2014dropout} and drop path technique~\cite{larsson2017fractalnet}, where some branches are randomly dropped during training. Let $\texttt{mAttn}_{N_a,M}(Q,K,V;\rho)$ denote a multi-branch attention layer with drop branch rate $\rho\in[0,1]$, which is an extension of that in Section~\ref{sec:network_arch}. Equipped with drop branch technique, the $i$-th branch of the multi-branch attention layer, denoted as $\beta^M_i(Q,K,V;\rho,\theta_i)$, works as follows: \begin{equation} \beta^M_i(Q,K,V;\rho,\theta_i)=\frac{\mathbb{I}\{U_i \ge \rho\}}{1-\rho}\multiattn{M}(Q,K,V;\theta_i), \end{equation} where $U_i$ is uniformly sampled from $[0,1]$ (briefly, $U_i\sim\texttt{unif}[0,1]$); $\mathbb{I}$ is the indicator function. During training, we may set $\rho\ge0$, where any branch might be skipped with probability $\rho$. During inference, we must set $\rho=0$, where all branches are leveraged with equal weights $1$. The multi-branch attention layer $\texttt{mAttn}_{N_a,M}(Q,K,V;\rho)$ works as follows: \begin{equation} \texttt{mAttn}_{N_a,M}(Q,K,V;\rho)=Q + \frac{1}{N_a}\sum_{i=1}^{N_a}\beta^M_i(Q,K,V;\rho,\theta_i). \label{eq:multi-branch_attention_layer} \end{equation} Note when $\rho=0$, Eqn.\eqref{eq:multi-branch_attention_layer} degenerates to Eqn.\eqref{eq:multi-branch_attention_layer_infer}. During training, it is possible that all branches in multi-branch attention layer are dropped. The residual connection ensures that even if all branches are dropped, the output from the previous layer can be fed to top layers through the identical mapping. That is, the network is never blocked. When $N_a=1$ and $\rho=0$, a multi-branch attention layer degenerates to a vanilla multi-head attention layer. When $N_a=1$ and $\rho>0$, it is the standard Transformer with randomly dropped attention layers during training, which is similar to the drop layer~\cite{fan2020reducing}. (See Section~\ref{sec:hyper_explore} for more discussions.) We also apply the drop branch technique to FFN layers. That is, the revised FFN layer is defined as \begin{equation} x +\frac{\mathbb{I}\{U\ge\rho\}}{1-\rho}\texttt{FFN}(x),\;U\sim\texttt{unif}[0,1] \end{equation} where $x$ is the output of the previous layer. An illustration of multi-branch attentive Transformer is in Figure~\ref{fig:arch_multi_branch}. Each block in the encoder consists of a multi-branch attentive self-attention layer and an FFN layer. Each block in the decoder consists of another multi-branch attentive encoder-decoder attention layer. Layer normalization~\cite{ba2016layer} remains unchanged. \begin{figure}[!htbp] \centering \includegraphics[width=0.95\linewidth]{HAT_arch_encoder.png} \vspace{-3mm} \caption{Architecture of a block in the encoder of MAT. ``LN'' refers to layer normalization.} \label{fig:arch_multi_branch} \vspace{-3mm} \end{figure} \subsection{Proximal initialization}\label{sec:prox_init} MAT can be optimized like the standard version by first randomly initializing all parameters and training until convergence. However, the multi-branch attention layer increases the training complexity of MAT, since there are multiple branches to be optimized. Recently, proximal algorithms~\cite{neal2013proximal} have been widely used in pretraining-and-finetuning framework to regularize training~\cite{jiang2019smart}. Then main idea of proximal algorithms is to balance the trade-off between minimizing the objective function and minimizing the weight distance with a pre-defined weight. Inspired by those algorithms, we design a two-stage warm-start training strategy: \noindent(1) Train a standard Transformer with embedding dimension $d$, FFN dimension $d_h$. \noindent(2) Duplicate both the self-attention layers and encoder-decoder attention layers for $N_a$ times to initialize MAT. Train this new model until convergence. We empirically find that the proximal initialization scheme can boost the performance than that obtained by training from scratch. \section{Application to neural machine translation} In this section, we conduct two groups of experiments: one with relatively small scale data, including IWSLT'14 German$\to$English, IWSLT'14 Spanish$\leftrightarrow$English and IWSLT'17 French$\leftrightarrow$English translation tasks; the other with larger training corpus, WMT'14 English$\to$German translation and WMT'19 German$\to$French translation. We briefly denote English, German, Spanish and French as En, De, Es and Fr respectively. \subsection{Settings} \noindent{\em Data preprocessing}: Our implementation of NMT experiments is based on fairseq\footnote{\url{https://github.com/pytorch/fairseq}}. For IWSLT'14 De$\leftrightarrow$En, we follow~\cite{edunov2018classical} to get and preprocess the training, validation and test data\footnote{The URLs of scripts we used in this paper are summarized in Appendix C.}, including lowercasing all words, tokenization and applying BPE~\cite{sennrich2016bpe}. For the other two IWSLT tasks, we do not lowercase the words and keep them case-sensitive. We apply tokenization and BPE as those used in preprocessing IWSLT De$\leftrightarrow$En. Training data sizes for IWSLT De$\to$En, Es$\leftrightarrow$En and Fr$\leftrightarrow$En are $160k$, $183k$ and $236k$ respectively. We choose IWSLT'13 Es$\leftrightarrow$En, IWSLT'16 Fr$\leftrightarrow$En for validation purpose, and choose IWSLT'14 Es$\leftrightarrow$En and IWSLT'17 Fr$\leftrightarrow$En as test sets. The numbers of BPE merge operation for the three tasks are all $10k$. The source and target data are merged to get the BPE table. For WMT'14 English$\to$German translation, we follow \cite{ott2018scaling} to preprocess the data , and eventually obtain $4.5M$ training data. We use newstest 2013 as the validation set, and choose newstest 2014 as the test set. The number of BPE merge operation is $32k$. The preprocess steps for WMT'19 De$\to$Fr are the same as those for WMT'14 En$\to$De, and we eventually get $9M$ training data in total. We concatenate newstest2008 to newstest 2014 together as the validation set and use newstest 2019 as the test set. \noindent{\em Model configuration and training strategy}: For the three IWSLT tasks, we choose the default setting provided by fairseq official code\footnote{\url{https://github.com/pytorch/fairseq/blob/master/fairseq/models/transformer.py}} as the baseline with embedding dimension $d=512$, hidden dimension $d_h=1024$ and number of heads $M=4$. For WMT'14 En$\to$De, we mainly follow the big transformer setting, where the above three numbers are $1024$, $4096$ and $16$ respectively. The dropout rates are $0.3$. For the more detailed parameters like $\rho$ and $N_a$, we will introduce the details in corresponding subsections. We use the Adam~\cite{kingma2015adam} optimizer with initial learning rate $5\times10^{-4}$, $\beta_1=0.9$, $\beta_2=0.98$ and the \texttt{inverse\_sqrt} learning rate scheduler~\cite{vaswani2017attention} to control training. Each model is trained until convergence. The source embedding, target embedding and output embedding of each task are shared. The batch size is 4096 for both IWSLT and WMT tasks. For IWSLT tasks, we train on single P40 GPU; for WMT tasks, we train on eight P40 GPUs \noindent{\em Evaluation} We evaluate the translation quality by BLEU scores. For IWSLT'14 De$\to$En and WMT'14 En$\to$De, following the common practice, we use \texttt{multi-bleu.perl}. For other tasks, we choose \texttt{sacreBLEU}. \subsection{Exploring hyper-parameters of MAT}\label{sec:hyper_explore} Due to resource limitation, we first explore hyper-parameters and proximal initialization on IWSLT'14 De$\to$En dataset to get some empirical results, then transfer them to larger datasets. We try different combination of $N_a$, $d$ and $d_h$. We ensure the number of total parameters not exceeding $36.7M$, the size of the default model for IWSLT'14 De$\to$En. All results are reported in Table~\ref{tab:iwslt_deen_multi-branch_attn}, where the network architecture is described by a four-element tuple, with each position representing the number of branches $N_a$, embedding dimension $d$, hidden dimension $d_h$ and model sizes. \begin{table}[!htbp] \vspace{-1mm} \centering \small \caption{Results on IWSLT'14 De$\to$En with different architectures. The left and right subtables are experiments of standard transformer and MAT respectively. From left to right in each subtable, the columns represent the network architecture, number of parameters, BLEU scores with $\rho$ ranging from $0.0$ to $0.3$.} \begin{tabular}{p{2.44cm}p{.62cm}p{.56cm}p{.56cm}p{.56cm}|p{2.44cm}p{.56cm}p{.56cm}p{.56cm}p{.56cm}} \toprule $N_a/d/d_h/\text{Param}$ & $0.0$ & $0.1$ & $0.2$ & $0.3$ & $N_a/d/d_h/\text{Param}$ & $0.0$ & $0.1$ & $0.2$ & $0.3$ \\ \midrule \multicolumn{5}{c|}{Standard Transformer + Drop Branch} & \multicolumn{5}{c}{MAT + Drop Branch} \\ \midrule $1/512/1024/36.7M$ & $34.95^\triangle$ & $3.94$ & $22.43$ & $0.78$ & $2/256/1024/18.4M$ & $34.42$ & $35.19$ & $35.52$ & $35.11$ \\ $1/256/1024/13.7M$ & $35.04$ & $35.39$ & $34.53$ & $29.34$ & $2/256/2048/24.7M$ & $34.51$ & $35.46$ & $35.59$ & $35.33$ \\ $1/256/2048/20.0M$ & $34.66$ & $35.45$ & $32.75$ & $1.37$ & $3/256/1024/23.1M$ & $34.01$ & $34.92$ & $35.39$ & $35.44$ \\ $1/256/3072/26.3M$ & $34.41$ & $35.37$ & $34.64$ & $25.05$ & $3/256/2048/29.4M$ & $33.98$ & $35.03$ & $35.40$ & $\bm{35.70}$ \\ & & & & & $4/256/1024/27.9M$ & $33.77$ & $34.84$ & $35.08$ & $35.14$ \\ & & & & & $4/256/2048/34.2M$ & $33.79$ & $34.81$ & $35.08$ & $35.46$ \\ \bottomrule \end{tabular} \label{tab:iwslt_deen_multi-branch_attn} \vspace{-1mm} \end{table} The baselines correspond to the architectures with $N_a=1$ and $\rho=0$. The most widely adopted baseline (marked with $^\triangle$) is $34.95$ and the model size is $36.7$M. Reducing $d$ to $256$ results in slightly BLEU score $35.04$. We have the following observations: \noindent(1) Using multi-branch attention layers with more than one branches can boost the translation BLEU scores, with a proper $\rho$. When setting $d_h=1024$ and increasing $N_a$ from $2$ to $3$, the BLEU scores are $35.52$ (with $\rho=0.2$) and $35.44$ (with $\rho=0.3$), outperforming the standard baseline $34.95$, as well as the BLEU score obtained from architecture $1/256/1024$. However, it is not always good to enlarge $N_a$. The BLEU score of MAT with $N_a=4$ is $35.14$, which is a minor improvement over the baseline. Multi-branch attention layers also benefits from larger hidden dimension $d_f$. When setting $d_f=2048$, we obtain consistent improvement compared to $d_f=1024$ with the same $N_a$. Among all architectures, we find that the model $3/256/2048$ achieves the best BLEU score, which is $35.70$ (we also evaluate the validation perplexity of all architectures, and the model $3/256/2048$ still get the lowest perplexity $4.71$). Compared with the corresponding Transformer $1/256/2048$ with $\rho=0$, we get $1.04$ improvement. We also enlarge $\rho$ to $0.4$ and $0.5$, but the BLEU scores drop. Results are shown in Appendix A. \noindent(2) The drop branch is important technique for training multi-branch attention layers. Take the network architecture $3/256/1024$ as an example: If we do not use drop branch technique, i.e., $\rho=0$, we can only get $34.01$ BLEU score, which is $0.94$ point below the baseline. As we increase $\rho$ from $0$ to $0.3$, the BLEU scores become better and better, demonstrating the effectiveness of drop branch. \noindent(3) When setting $N_a=1$ and $\rho_B>0$, the architecture still benefits from the drop branch technique. For architecture $1/256/1024$, the vanilla baseline is $35.04$. As we increase $\rho$ to $0.1$, we can obtain $0.35$ point improvement. Wider networks with $d_f$ also benefits from this technique, which shows that drop branch is generally a useful trick for Transformer. This is consistent with the discoveries in~\cite{fan2020reducing}. With $\rho=0.1$, enlarging the hidden dimension to $2048$ and $3072$ lead to $35.45$ and $35.37$ BLEU scores, corresponding to $0.79$ and $0.96$ score improvements compared with that without using drop branch. But we found that when $N_a=1$, drop branch might lead to unstable results. For example, when $\rho=0.1$, $1/512/1024$ cannot lead to a reasonable result. We re-run the experiments with five random seeds but always fail. In comparison, MAT can always obtain reasonable results with drop branch. We also try to turn off the drop branch at the FFN layers. In this case, we found that by ranging $\rho$ from $0$ to $0.3$, architecture $3/256/2048$ can achieve $34.63$, $34.78$ and $34.98$ BLEU scores, which are worse than those obtained by using drop branch at all layers. This shows that the drop branch at every layers is important for our proposed model. \subsection{Exploring proximal initialization}\label{sec:proximal_init} In this section, we explore the effect of proximal initialization, i.e., warm start from an existing standard Transformer model. The results are reported in Table~\ref{tab:result_iwslt_deen}. Generally, compared with the results without proximal initialization, the models can achieve more than $0.5$ BLEU score improvement. Specifically, with $N_a=3$ and $d_h=2048$, we can achieve a $36.22$ BLEU score, setting a state-of-the-art record on this task. We also evaluate the validation perplexity of all architectures in Table~\ref{tab:result_iwslt_deen}, and the model with $N_a=3$ and $d_h=2048$ still get the lowest perplexity $4.56$. \begin{table}[!htbp] \vspace{-2mm} \centering \caption{Results of using proximal initialization. Columns from left to right represent the network architecture, BLEU scores with drop branch ratio $\rho$ from $0.0$ to $0.3$, and the increment compared to the best results without proximal initialization.} \begin{tabular}{cccccccc} \toprule $(N_a,d_h)$& $0.0$ & $0.1$ & $0.2$ & $0.3$ & $\Delta$ \\ \midrule $(2,2048)$ & $34.99$ & $35.50$ & $35.85$ & $36.12$ & $0.79$ \\ $(3,1024)$ & $35.33$ & $35.77$ & $35.94$ & $35.83$ & $0.50$ \\ $(3,2048)$ & $34.83$ & $35.63$ & $36.08$ & $\bm{36.22}$ & $0.52$ \\ $(4,1024)$ & $35.45$ & $35.72$ & $36.07$ & $36.02$ & $0.88$ \\ $(4,2048)$ & $35.06$ & $35.61$ & $35.81$ & $36.09$ & $0.63$ \\ \bottomrule \end{tabular} \label{tab:result_iwslt_deen} \vspace{-1mm} \end{table} In summary, according to the exploration in Section~\ref{sec:hyper_explore} and Section~\ref{sec:proximal_init}, we empirically get the following conclusions: (1) A multi-branch attention layer is helpful to improve Transformer. We suggest to try $N_a=2$ or $N_a=3$ first. (2) A larger $d_h$ is helpful to bring better performance. Enlarging $d_h$ to consume the remaining parameters of reducing $d$ (of the standard Transformer) is a better choice. (3) The drop branch and proximal initialization are two key techniques to the success of MAT in NMT. \subsection{Application to other NMT tasks}\label{sec:results_apply} \noindent{\it Results of other IWSLT tasks}: We apply the discoveries to Spanish$\leftrightarrow$English and French$\leftrightarrow$English, and report the results in Table~\ref{tab:results_iwslt_esfren}. For each setting, both the highest BLEU scores according to validation performance as well as the corresponding $\rho$'s are reported. We choose $1/512/1024$ as the default baseline, whose model size is the upper bound of our MAT models. We also implement two other baselines, one with smaller $d$ and the other with larger $d_h$. In baselines, the $\rho$ is fixed as zero. Compared to the standard Transformer with one branch, various MAT with different model configurations outperform the baseline. The architecture $2/256/2048$ with $\rho=0.2$ generally obtains promising results. Compared with the default baseline $1/512/1024$, it achieves $1.74$, $1.90$, $1.31$, $1.25$ improvement on Es$\to$En, En$\to$Es, Fr$\to$En and En$\to$Fr. \begin{table}[!htbp] \vspace{-2mm} \centering \caption{Results on IWSLT \{Es, Fr\}$\leftrightarrow$En. } \begin{tabular}{c|ccc|ccccccc} \toprule $N_a$/$d$/$d_h$ & \#Params(M) & Es$\to$En / $\rho$ & En$\to$Es / $\rho$ & \#Params(M) & Es$\to$En / $\rho$ & En$\to$Es / $\rho$ \\ \midrule 1/512/1024 & $36.8$ & $40.37$ / $0.0$ & $38.56$ / $0.0$ & $36.8$ & $36.10$ / $0.0$ & $35.99$ / $0.0$ \\ 1/256/1024 & $13.7$ & $40.60$ / $0.0$ & $39.42$ / $0.0$ & $13.7$ & $36.21$ / $0.0$ & $36.16$ / $0.0$ \\ 1/256/2048 & $20.0$ & $40.18$ / $0.0$ & $38.78$ / $0.0$ & $20.0$ & $36.38$ / $0.0$ & $36.73$ / $0.0$ \\ \hline 2/256/1024 & $18.4$ & $41.02$ / $0.1$ & $39.56$ / $0.1$ & $18.4$ & $36.37$ / $0.2$ & $36.57$ / $0.2$ \\ 2/256/2048 & $24.7$ & $42.11$ / $0.2$ & $40.46$ / $0.2$ & $24.7$ & $37.41$ / $0.2$ & $37.24$ / $0.2$ \\ 3/256/1024 & $23.1$ & $41.39$ / $0.1$ & $40.08$ / $0.2$ & $23.2$ & $37.44$ / $0.2$ & $37.30$ / $0.1$ \\ 3/256/2048 & $29.4$ & $41.79$ / $0.3$ & $40.40$ / $0.3$ & $29.5$ & $37.28$ / $0.2$ & $37.44$ / $0.2$ \\ \bottomrule \end{tabular} \label{tab:results_iwslt_esfren} \vspace{-4mm} \end{table} \noindent{\it Results on larger datasets}: After obtaining results on small-scale datasets, we apply our discoveries to three larger datasets: WMT'14 En$\to$De translation, WMT'19 De$\to$Fr translation and WMT'19 En$\to$De translation. The results of WMT'14 En$\to$De are shown in Table~\ref{tab:wmt14_en2de}. The standard baseline is $29.13$ BLEU score, and the model contains $209.8M$ parameters. We implement an MAT with $N_a=2,d_h=12288$ and another with $N_a=3,d_h=10240$. We can see that our MAT also works for the large-scale dataset. When $N_a=2$, we can obtain $29.90$ BLEU score. When increasing $N_a$ to $3$, we can get $29.85$, which is comparable with the the $N_a=2$ variant. Besides, for large-scale datasets, the drop branch technique is important too. $\rho=0.2$ works best of all settings. \begin{table}[!htbp] \vspace{-2mm} \centering \caption{Results on WMT'14 En$\to$De translation. } \begin{tabular}{lccccc} \toprule $N_a/d/d_h$ & \#Param (M) & $\rho$ & BLEU \\ \midrule $1/1024/4096$ & $209.8$ & $0.0$ & $29.08$ \\ $1/512/10240$ & $161.7$ & $0.0$ & $28.86$ \\ $1/512/12288$ & $186.9$ & $0.0$ & $28.95$ \\ \midrule $2/512/12288$ & $205.8$ & $0.1$ & $29.64$\\ $2/512/12288$ & $205.8$ & $0.2$ & $29.90$ \\ $2/512/12288$ & $205.8$ & $0.3$ & $29.06$ \\ $3/512/10240$ & $199.5$ & $0.1$ & $29.62$ \\ $3/512/10240$ & $199.5$ & $0.2$ & $29.85$ \\ $3/512/10240$ & $199.5$ & $0.3$ & $29.05$ \\ \bottomrule \end{tabular} \label{tab:wmt14_en2de} \vspace{-1mm} \end{table} We summarize previous results on WMT'14 En$\to$De in Table~\ref{tab:prev_wmt14_en2de}. MAT can achieve comparable or slightly better results than carefully designed architectures like weighted Transformer and DynamicConv, and than the evolved Transformer discovered by neural architecture search. The results of WMT'19 De$\to$Fr are shown in Table~\ref{tab:wmt19_de2fr}. Compared with standard big transformer model of architecture $1/1024/4096$, MAT with $\rho=0.1$ can improve the baseline by $0.58$ point. \begin{table}[!htbp] \vspace{-3mm} \begin{minipage}{0.49\linewidth} \vspace{-4mm} \centering \caption{BLEU scores of WMT'14 En$\to$De \\ in previous work.} \begin{tabular}{lc} \toprule Algorithm & BLEU \\ \midrule Weighted Transformer~\cite{ahmed2017weighted}& $28.9$ \\ Evolved Transformer~\cite{so2019evolved} & $29.8$ \\ DynamicConv~\cite{wu2019pay} & $29.7$ \\ \midrule Our MAT & $29.9$\\ \bottomrule \label{tab:prev_wmt14_en2de} \end{tabular} \end{minipage} \hfill \begin{minipage}{0.49\linewidth} \centering \caption{Results on WMT'19 De$\to$Fr translation.} \begin{tabular}{lccccc} \toprule $N_a/d/d_h$ & \#Param (M) & $\rho$ & BLEU \\ \midrule $1/1024/4096$ & $223.6$ & $0.0$ & $34.07$ \\ $1/512/12288$ & $193.7$ & $0.0$ & $33.90$ \\ \midrule $2/512/12288$ & $212.6$ & $0.0$ & $33.92$ \\ $2/512/12288$ & $212.6$ & $0.1$ & $34.65$ \\ $2/512/12288$ & $212.6$ & $0.2$ & $34.53$ \\ $2/512/12288$ & $212.6$ & $0.3$ & $34.49$ \\ \bottomrule \label{tab:wmt19_de2fr} \end{tabular} \end{minipage} \vspace{-3mm} \end{table} \noindent{\it Results with larger models}: Finally, we explore whether our proposed MAT works for larger models. We conduct experiments on WMT'19 En$\to$De translation task. The data is downloaded from WMT'19 website\footnote{The data is available at \url{http://www.statmt.org/wmt19/translation-task.html}. We concatenate \texttt{Europarl v9}, \texttt{Common Crawl corpus}, \texttt{News Commentary v14} and \texttt{Document-split Rapid} corpus. }. We change the number of encoder layers to $12$, set \texttt{attention-dropout} and \texttt{activation-dropout} as $0.1$, and keep the other settings the same as WMT'14 En$\to$De. To validate the effectiveness of MAT, we evaluate the trained models on three test sets: WMT'14 En$\to$De, WMT'18 En$\to$De and WMT'19 En$\to$De. We use \texttt{sacreBLEU} to evaluate the translation quality. Furthermore, to facilitate comparison with previous work, we also use \texttt{multi-bleu.perl} to calculate the BLEU score for WMT'14 En$\to$De. The results are shown in Table~\ref{tab:wmt19_en2de}. Compared with the standard big transformer model of architecture $1/1024/4096$, in terms of \texttt{sacreBLEU}, MAT with $\rho=0.2$ can improve the baseline by $1.0$, $1.0$ and $1.1$ points on WMT14, WMT18 and WMT19 test sets respectively. Specially, on WMT'14 En$\to$De, in terms of \texttt{multi-bleu}, we achieve $30.8$ BLEU score, setting a new record on this work under the supervised setting. \begin{table}[!htbp] \vspace{-2mm} \centering \caption{Results of En$\to$De with larger models. For WMT'14, both \texttt{multi-bleu} (left) and \texttt{sacreBLEU} (right) are reported.} \begin{tabular}{lcccccccc} \toprule $N_a/d/d_h$ & \#Param (M) & $\rho$ & WMT14 & WMT18 & WMT19 \\ \midrule $1/1024/4096$ & $325.7$ & $0.0$ & $29.8$ / $29.2$ & $42.7$ & $39.3$ \\ $1/512/12288$ & $288.9$ & $0.0$ & $29.5$ / $29.0$ & $41.3$ & $37.4$ \\ \midrule $2/512/12288$ & $314.1$ & $0.0$ & $30.0$ / $29.6$ & $42.5$ & $38.5$ \\ $2/512/12288$ & $314.1$ & $0.1$ & $29.9$ / $29.4$ & $43.1$ & $39.5$ \\ $2/512/12288$ & $314.1$ & $0.2$ & $30.8$ / $30.2$ & $43.7$ & $40.4$ \\ $2/512/12288$ & $314.1$ & $0.3$ & $30.1$ / $29.7$ & $43.8$ & $40.3$ \\ \bottomrule \end{tabular} \label{tab:wmt19_en2de} \vspace{-2mm} \end{table} \section{Application to code generation} We verify our proposed method on code generation, which is to map natural language sentences into code. \noindent{\em Datasets} Following~\cite{wei2019code}, we conduct experiments on a Java dataset\footnote{The urls of the datasets and tools we used for code generation are summarized in Appendix C.\label{foot:codegen_script}}~\cite{ijcai2018-314} and a Python dataset~\cite{wan2018improving}. In the Java dataset, the numbers of training, validation and test sequences are $69708$, $8714$ and $8714$ respectively, and the corresponding numbers for Python are $55538$, $18505$ and $18502$. All samples are tokenized. We use the downloaded Java dataset without further processing and use Python standard AST modul to further process the python code. The source and target vocabulary sizes in natural language to Java code generation are $27k$ and $50k$, and those for natural language to Python code generation are $18k$ and $50k$. In this case, following~\cite{wei2019code}, we do not apply subword tokenization like BPE to the sequences. \noindent{\em Model configuration} We set $N_a=4$, $d=256$ and $d_h=1024$ respectively. Both the encoder and the decoder consist of three blocks. The MAT model contains about $37M$ parameters. For the Transformer baseline, we set $d=512$ and $d_h=1024$, with $55$M parameters. \noindent{\em Evaluation} Following~\cite{wei2019code,ijcai2018-314}, we use sentence-level BLEU scores, which is the average BLEU score of all sequences to evaluate the generation quality. We choose the percentage of valid code (PoV) as another metric for evaluation, which is the percentage of code that can be parsed into an AST. \iffalse \noindent{\em Baselines} We compare our results with the following baselines: \begin{enumerate} \item {\textbf{Dual}~\cite{wei2019code}}: This approach proposes a dual training framework between code summarization and code generation to train the two tasks simultaneously. The approach uses two 3-layer LSTM models with the attention mechanism, more than $53M$ parameters in total. Compared with Transformer and our method, the dual framework requires extra data and more training cost. \item {\textbf{Transformer}~\cite{vaswani2017attention}}: We use the standard Transformer architecture, with $d=512$, $d_h=1024$, number of encoder layers and decoder layers set to $3$. The model size is about $55M$. \end{enumerate} \fi We report the results on code generation task in Table~\ref{tab:results_codegen}. It is obvious that Transformer-based models (standard Transformer and MAT) is significantly better than the LSTM-based dual model. Compared with standard Transformer, our MAT can get $4.2$ and $1.2$ BLEU score improvement in Java and Python datasets respectively. MAT reaches the best BLEU scores when $\rho=0.1$ on both on Java and Python datasets, which shows that the drop branch technique is important in code generation task. When $\rho=0.1$, in terms of PoV, our MAT can boost the Transformer baseline by $5.8\%$ and $6.6\%$ points. \begin{table}[!htbp] \centering \caption{Results on code generation.} \begin{tabular}{lcccc} \toprule \multirow{2}{*}{Algorithm} & \multicolumn{2}{c}{Java} & \multicolumn{2}{c}{Python} \\ & BLEU & PoV & BLEU & PoV \\ \hline Dual~\cite{wei2019code} & $17.17$ & $27.4\%$ & $12.09$ & $51.9\%$ \\ Transformer & $23.30$ & $83.1\%$ & $15.49$ & $73.3\%$ \\ \hline Ours, $\rho=0.0$ & $26.97$ & $77.5\%$ & $16.35$ & $65.5\%$ \\ Ours, $\rho=0.1$ & $\bm{27.53}$ & $88.9\%$ & $\bm{16.66}$ & $79.9\%$ \\ Ours, $\rho=0.2$ & $26.06$ & $90.8\%$ & $15.63$ & $84.0\%$ \\ Ours, $\rho=0.3$ & $24.72$ & $90.2\%$ & $12.85$ & $75.3\%$ \\ \bottomrule \end{tabular} \label{tab:results_codegen} \end{table} \section{Application to natural language understanding} We verify our proposed MAT on natural language understanding (NLU) tasks. Pre-training techniques have achieved state-of-the-art results on benchmark datasets/tasks like GLUE~\cite{wang2019glue}, RACE~\cite{lai2017large}, etc. To use pre-training, a masked language model is first pre-trained on large amount of unlabeled data. Then the obtained model is used to initialize weights for downstream tasks. We choose RoBERTa~\cite{liu2019roberta} as the backbone. For GLUE tasks, we focus more on accuracy. Therefore, we do not control the parameters subconsciously. We set $N_a=2$ for all experiments. Following~\cite{fan2020reducing}, we conduct experiments on MNLI-m, MPRC, QNLI abd SST-2 tasks in GLUE benchmark~\cite{wang2019glue}. SST-2 is a single-sentence task, which is to check whether the input movie review is a positive one or negative. The remaining tasks are two-sentence tasks. In MNLI, given a premise sentence and a hypothesis sentence, the task is to predict whether the premise entails the hypothesis (entailment), contradicts the hypothesis (contradiction), or neither (neutral). In MRPC, the task is to check whether the two inputs are matched. In QNLI, the task is to determine whether the context sentence contains the answer to the question. We choose the 24-layer RoBERTa$_{\text{large}}$\footnote{Models from page \url{https://github.com/pytorch/fairseq/tree/master/examples/roberta}.} to initialize our MAT. We report the validation accuracy following~\cite{fan2020reducing}. \begin{table}[!htpb] \centering \caption{Validation results on various NLU tasks. Results of RoBERTa and RoBERTa + LayerDrop (briefly, ``+LayerDrop'') are from \cite{fan2020reducing}.} \begin{tabular}{lcccc} \toprule Algorithm & MNLI-m & MRPC & QNLI & SST-2 \\ \midrule RoBERTa & $90.2$ & $90.9$ & $94.7$ & $96.4$ \\ + LayerDrop & $90.1$ & $91.0$ & $94.7$ & $96.8$ \\ \midrule Ours & $90.7$ & $91.9$ & $95.0$ & $97.0$ \\ \bottomrule \end{tabular} \label{tab:result_glue} \end{table} The results are reported in Table~\ref{tab:result_glue}. Compared with vanilla RoBERTa model, on the four tasks MNLI-m, MRPC, QNLI abd SST-2, we can improve them by $0.5$, $1.0$, $0.3$ and $0.6$ scores. Compared with the layer drop technique~\cite{fan2020reducing}, we also achieve promising improvement on these four tasks. The results demonstrate that our method not only works for sequence generation tasks, but also for text classification tasks. Drop branch also plays a central role on NLU tasks. We take the MRPC task as an example. The results are shown in Table~\ref{tab:mrpc_rho}. MRPC achieves the best result at $\rho=0.3$. \begin{table}[!htbp] \centering \caption{MRPC validation accuracy w.r.t. $\rho$. } \begin{tabular}{ccccccc} \toprule $\rho$ & $0.1$ & $0.2$ & $0.3$ & $0.4$ & $0.5$ \\ \midrule accuracy & $90.9$ & $90.0$ & $91.9$ & $91.2$ & $91.7$ \\ \bottomrule \end{tabular} \label{tab:mrpc_rho} \end{table} \section{Exploring other variants} In this section, we first discuss whether applying multi-branch architectures to FFN layers is helpful. Then we discuss a new variant of drop branch technique. Finally we verify the importance of the multi-branch architecture, where both concatenation and averaging operations are used. We mainly conduct experiments on IWSLT tasks to verify the variants. We conduct experiments on IWSLT'14 De$\to$En. \subsection{Multi-branch FFN layer} \noindent{\em Algorithm}: Denote the revised FFN layer as $\texttt{hFFN}_{N_f}$ with $N_f(\in\mathbb{Z}_+)$ branches. Mathematically, given an input $x$ from the previous layer, \begin{equation} \texttt{hFFN}_{N_f}(x)=x + \frac{1}{N_f}\sum_{i=1}^{N_f}\texttt{FFN}(x;\omega_i)\frac{\mathbb{I}\{U_i\ge \rho\}}{1-\rho}, \end{equation} where $\omega_i$ is the parameter of the $i$-th branch of the FFN layer, $x$ is the output from the previous layer. \noindent{\em Experiments}: We fix $d$ as $256$ and change $N_f$. We set the attention layers as both standard multi-head attention layers $(N_a=1)$ and multi-branch attention layers with $N_a=2$. We set $N_fd_h=2048$ to ensure the number of parameters unchanged with different number of branches. Results are reported in Table~\ref{tab:iwslt_deen_diff_ffn_branch}. \begin{table}[!htbp] \centering \caption{Results on IWSLT'14 De$\to$En with multi-branch FFN layers. From left to right, the columns represent the network architecture (with the number of parameters included), BLEU scores with $\rho$ ranging from $0.0$ to $0.3$.} \begin{tabular}{lccccc} \toprule $N_a/N_f/d_h/$\#Param & $0.0$ & $0.1$ & $0.2$ & $0.3$ \\ \midrule $1/1/2048/20.0 \text{M}$ & $34.66$ & $35.45$ & $32.75$ & $1.37$\\ $1/2/1024/20.0 \text{M}$ & $34.85$ & $35.38$ & $35.30$ & $34.39$ \\ $1/4/512/20.0 \text{M}$ & $34.51$ & $34.83$ & $34.71$ & $34.56$ \\ $1/8/256/20.0 \text{M}$ & $34.35$ & $34.36$ & $34.38$ & $33.86$ \\ \midrule $2/1/2048/24.7 \text{M}$ & $34.51$ & $35.46$ & $35.59$ & $35.33$ \\ $2/2/1024/24.7 \text{M}$ & $34.39$ & $35.18$ & $35.55$ & $35.42$ \\ $2/4/512/24.7 \text{M}$ & $33.86$ & $34.90$ & $35.00$& $35.07$ \\ $2/8/256/24.7 \text{M}$ & $34.05$ & $34.59$ & $34.70$& $34.55$ \\ \bottomrule \end{tabular} \label{tab:iwslt_deen_diff_ffn_branch} \end{table} We can see that increasing the branches of FFN layer while decreasing the corresponding hidden dimension (i.e., $d_h$) will hurt the performance. For standard Transformer with $N_a=1$, as we increase $N_f$ from $1$ to $2$, $4$, $8$, the BLEU scores drop from $35.45$ to $35.38$, $34.83$ and $34.38$. For MAT with $N_a=2$, as $N_f$ grows from $1$ to $8$, the BLEU decreases from $35.59$ to $35.55$, $35.00$ and $34.70$. That is, constraint by the number of total parameters, we do not need to separate FFN layers into multiple branches. \subsection{Variants of drop branch} \noindent{\em Algorithm}: In drop branch, the attention heads within a branch are either dropped together or kept together. However, we are not sure whether dropping a complete branch is the best choice. Therefore, we design a more general way to leverage dropout. Mathematically, the $j$-th attention head of the $i$-th branch, denoted as $\beta^{i,j}(Q,K,V;\rho,\theta_{i,j})$, works as follows: \begin{equation} \begin{aligned} \beta^{i,j}(Q,K,V;\rho,\theta_{i,j})=\texttt{attn}(QW^{i,j}_Q, KW^{i,j}_K, VW^{i,j}_V)\frac{\mathbb{I}\{U_{i,j}\ge\rho\}}{1-\rho}, \end{aligned} \label{eq:general_head} \end{equation} where superscripts $i$ and $j$ represent the branch id and head id in a multi-head attention layer respectively, $U^{i,j}\sim\texttt{unif}[0,1]$, $\theta_{i,j}=\{W^{i,j}_Q,W^{i,j}_K,W^{i,j}_V\}$. Based on Eqn.\eqref{eq:general_head}, we can define a more general multi-branch attentive architecture: \begin{equation} \begin{aligned} &\frac{1}{N_a}\sum_{i=1}^{N_a}\texttt{concat}\big(\beta^{i,1}(Q,K,V;\rho,\theta_{i,1}), \beta^{i,2}(Q,K,V;\rho,\theta_{i,2}),\cdots,\beta^{i,M}(Q,K,V;\rho,\theta_{i,M}) \big). \end{aligned} \label{eq:general_dropout} \end{equation} Keep in mind that Eqn.\eqref{eq:general_dropout} is associated with $U^{i,j}$ for any $i\in[N_a],j\in[M]$. We apply several constraints to $U^{i,j}$, which can lead to different ways to regularize the training: \begin{enumerate} \item For any $i\in[N_a]$, sample $U^i\sim\texttt{unif}[0,1]$ and set $U^{i,j}=U^i$ for any $j\in[M]$. This is the drop branch as we introduced in Section~\ref{sec:network_arch} \item Each $U^{i,j}$ is independently sampled \end{enumerate} \iffalse \begin{figure}[!htbp] \centering \subfigure[Drop a complete branch.]{ \includegraphics[width=0.46\linewidth]{figures/dropout_branch.png} } \subfigure[Randomly drop heads.]{ \includegraphics[width=0.46\linewidth]{figures/dropout_head_rand.png} } \caption{Variants of drop branch. In this figure, we show a $3$-branch $4$-head multi-branch attention. In each figure, the bottom row represents input and top row is the output. Red dashed lines represented dropped parts, i.e., vectors with all elements zero.} \label{fig:diff_dropout_scheme} \end{figure} \fi \noindent{\em Experiments}: We conduct experiments on IWSLT'14 De$\to$En and the results are reported in Table~\ref{tab:iwslt_deen_diff_dr_var}. Proximal initialization is leveraged. From left to right, each column represents architecture, number of parameters, BLEU scores with $\rho$ ranging from $0.0$ to $0.3$. The last column marked with $\Delta$ represents the improvement/decrease of the best results compared to those in Table~\ref{tab:result_iwslt_deen}. \begin{table}[!htbp] \vspace{-2mm} \begin{minipage}{0.48\linewidth} \centering \small \caption{Results on IWSLT'14 De$\to$En with randomly dropping heads technique. Embedding dimension $d$ is fixed as $256$.} \begin{tabular}{p{1.0cm}p{0.57cm}p{0.57cm}p{0.57cm}p{0.57cm}p{0.57cm}} \toprule $(N_a,d_h)$ & $0.0$ & $0.1$ & $0.2$ & $0.3$ & $\Delta$ \\ \midrule $(2,2048)$ & $34.99$ & $35.53$ & $35.95$ & $\bm{35.96}$ & $-0.26$ \\ $(3,1024)$ & $35.33$ & $35.67$ & $35.90$ & $\bm{35.95}$ & $+0.01$\\ $(3,2048)$ & $34.83$ & $35.45$ & $35.76$ & $\bm{36.07}$ & $-0.15$\\ $(4,1024)$ & $35.45$ & $35.72$ & $\bm{35.83}$ & $35.77$ & $-0.24$\\ $(4,2048)$ & $35.06$ & $35.79$ & $35.72$ & $\bm{36.03}$ & $-0.06$\\ \bottomrule \end{tabular} \label{tab:iwslt_deen_diff_dr_var} \end{minipage} \hfill \begin{minipage}{0.48\linewidth} \vspace{-11mm} \centering \small \caption{Results on IWSLT'14 De$\to$En \\ with different numbers of heads.} \begin{tabular}{lcccc} \toprule $\rho$ & $0.1$ & $0.2$ & $0.3$\\ \midrule $M=1$ & $35.01$ & $34.83$ & $34.52$\\ $M=2$ & $35.11$ & $35.45$ & $35.15$\\ $M=4$ & $35.19$ & $35.52$ & $35.11$\\ \bottomrule \end{tabular} \label{tab:iwslt_deen_m_heads_multi-branch} \end{minipage} \vspace{-2mm} \end{table} We can see that randomly dropping heads leads to slightly worse results than the drop branch technique. Take the network architecture with $N_a=3$, $d_h=1024$ as an example. The best BLEU score that drop branch technique achieves is $36.22$, and that obtained with randomly dropping heads is $36.07$. Similarly observations can be found from other settings in Table~\ref{tab:iwslt_deen_diff_dr_var}. Therefore, we suggest to use the drop branch technique, which requires minimal revision to the benchmark code. \subsection{Ablation study on multi-branch attentions} MAT introduces multi-branch attention, in addition to the multi-head attention with the concatenation manner.\footnote{The multi-head attention in standard Transformer is also one kind of multi-branch attention. For simplicity, we use multi-head attention to denote the original attention layer in standard Transformer, and multi-branch attention to denote the newly introduced multi-branch attention in the multi-branch manner (both averaging and concatenation manner).} It is interesting to know whether the multi-head attention is still needed given the multi-branch attention. We conduct experiments with $N_a=2$, $d=256$, $d_h=1024$ and vary the number of heads $M$ in $\texttt{mAttn}_{N_a,M}$. Results are reported in Table~\ref{tab:iwslt_deen_m_heads_multi-branch}. We can see that the multi-head attention is still helpful. When $M=1$, i.e., removing multiple heads and using a single head, it performs worse than multiple heads (e.g., $M=4$). Therefore, the multi-branch of them is the best choice. \section{Conclusion and future work} In this work, we proposed a simple yet effective variant of Transformer called multi-branch attentive Transformer and leveraged two techniques, drop branch and proximal initialization, to train the model. Rich experiments on neural machine translation, code generation and natural language understanding tasks have demonstrated the effectiveness of our model. For future work, we will apply our model to more sequence learning tasks. We will also combine our discoveries with neural architecture search, i.e., searching for better neural models for sequence learning in the search space with enriched multi-branch structures.
{'timestamp': '2020-07-28T02:21:52', 'yymm': '2006', 'arxiv_id': '2006.10270', 'language': 'en', 'url': 'https://arxiv.org/abs/2006.10270'}
arxiv
\section{Introduction} \label{sec:intro} The emergence of social media has changed how political campaigns take place around the world~\cite{Kearney2013}. Political actors (parties, action committees, candidates) utilize social media platforms, Twitter, Facebook, or Instagram, to communicate with and engage voters~\cite{Skogerb2015}. Hence, researchers must analyze these campaigns for several reasons, including enforcement of the laws on campaign contribution limits, implementation of freedom and fairness in electoral campaigns or protection against slander, hate-speech, or foreign interference. Unlike U.S. federal or state law, European jurisdictions present a rather lukewarm attitude to unrestrained online campaigning. Freedom of expression in Europe has more limits~\cite{Rosenfeld2003HateAnalysis}, and that can be seen in various electoral codes in Europe (e.g. in France, Poland) or statutes imposing mandatory systems of notice-and-takedown (e.g. the German Network Enforcement Act, alias the Facebook Act). In Poland, \textit{agitation} (an act of campaigning) may commonly be designated 'political advertisement', corporate jargon originating from such as Twitter's or Facebook's terms of service. Primarily, however, it has a normative definition in article 105 of the Electoral Code. It covers any committees' or voters' public acts of inducement or encouragement to vote for a candidate or in a certain way, regardless of form. Election promises may appear in such activities, but do not constitute a necessary component. A verbal expression on Twitter falls into this category. There exist some natural language resources for the analysis of political content in social media. These include collections related to elections in countries such as Spain~\cite{Taule2018a}, France~\cite{Lai2019b}, and Italy~\cite{Lai2018}. \newcite{Vamvas2020X-Stance:Detection} created an X-stance dataset that consists of German, French, and Italian text, allowing for a cross-lingual evaluation of stance detection. While the datasets on political campaigning are fundamental for studies on social media manipulation~\cite{Aral2019ProtectingManipulation}, there are no Polish language datasets related to either political advertising or stance detection problems. We want to fill this gap and expand natural language resources for the analysis of political content in the Polish language. Our contributions are as follows: (1) a novel, publicly open dataset for detecting specific text chunks and categories of political advertising in the Polish language, (2) a publicly available neural-based model for tagging social media content with political advertising that achieves a 70\% F1 score, and (3) an initial analysis of the political advertising during the Polish 2020 Presidential Election campaign. \section{Political Advertising Dataset Annotation} \label{sec:dataset} We created nine categories of political advertising (incl. election promises) based on manually extracted claims of candidates (see sample of examples in Table \ref{tab:examples}) and a taxonomy proposed by \newcite{Vamvas2020X-Stance:Detection}. We gathered political advertising topics (incl. election promises) provided by presidential candidates and committee websites, Facebook fanpages, and other websites (such as news agencies). We tried to fit them into the \newcite{Vamvas2020X-Stance:Detection} taxonomy. However, we spotted that some categories should be corrected or omitted, such as the economy. It was particularly hard to divide whether political advertising should fall into the category of welfare or economy. The final version of categories was created after a couple of iterations with our annotator team, and we chose categories for which we got a consensus and repeatable annotations. By repeatable, we understand that the same or another annotator will consistently choose the same categories for repeated examples or very similar examples. To the best of our knowledge, there do not exist any commonly used political advertising categories. Moreover, we are aware that they can evolve in future election campaigns. We shall be ready to update the dataset according to political advertising types, categories, and any concept drift in the data. We extracted all Polish tweets related to the election based on appearances in the tweet of (1) specific hashtags such as \emph{wybory} (\emph{elections}), \emph{wybory2020} (\emph{elections2020}), \emph{wyboryprezydenckie} (\emph{presidentialelections}), \emph{wyboryprezydenckie2020} (\emph{presidentialelections2020}), and (2) unigram and bigram collocations\footnote{Collocation extracted using NLTK library (\url{https://www.nltk.org/}).} generated using examples of political advertising from all categories (as in Table~\ref{tab:examples}). We name these sets of hashtags and collocations together as \emph{search keywords or search terms}. We gathered almost 220,000 tweets covering approximately ten weeks, between February 5, 2020 and April 11, 2020 using the search terms mentioned. We assigned sentiment orientation for each tweet using an external Brand24 API\footnote{\url{https://brand24.com/}}. Then we sampled tweets using a two stage procedure: (1) we divided all tweets into three sets based on sentiment orientation (positive, neutral, negative) to have representations of various attitudes, and (2) for each sentiment category we randomly selected $log_{2}(|E_{k}|)$ examples, where $E$ is a set of all tweets for a particular \emph{search keyword} $k$. We used almost 200 different \emph{search keywords} and finally reached 1,705 tweets for the annotation process. The dataset was annotated by two expert native speaker annotators (linguists by training). The annotation procedure was similar to Named Entity Tagging or Part-of-Speech Tagging, so the annotators marked each chunk of non-overlapping text that represents a~particular category. They could annotate a single word or multi-word text spans. Table \ref{tab:examples} presents an example of political advertising with corresponding categories. These kinds of examples (they could be named as seed examples) were presented to the annotators as a starting point for annotating tweets. However, the annotators could also mark other chunks of text related to political advertising when the chunk is semantically similar to examples or it clearly contains examples of a political category but not present in the seed set. We achieved a 0.48 Cohen's kappa score for exact matches of annotations (even a~one-word mismatch was treated as an error) and a 0.65 kappa coefficient counting partial matches such as \emph{reduce coil usage} and \emph{reduce coil} as correct agreement. We disambiguated and improved the annotation via an additional pass by the third annotator. He resolved the mismatches between the first two annotators and made the dataset more consistent and comprehensive. According to \newcite{McHugh2012}, the 0.65 kappa coefficient lies between a moderate and strong level of agreement. We must remember that we are annotating social media content. Hence there will exist a lot of ambiguity, slang language, and very short or chunked sentences without context that could influence the outcome. Then, we trained a~Convolutional Neural Network model using a spaCy Named Entity classifier~\cite{Mather}, achieving a 70\% F1 score for 5-fold cross-validation. We used fastText vectors for Polish~\cite{Grave2019a} and default spaCy model hyperparameters. The dataset and trained model are publicly available in the GitHub repository \footnote{\url{https://github.com/laugustyniak/misinformation}}. Table \ref{tab:scores} presents per category precision, recall, F1 score, as well as the number of examples for each category in the whole dataset. As we can see, there are 2507 spans annotated. Interestingly, 631 tweets have been annotated with two or more spans. Finally, 235 tweets do not contain any annotation span, and they represent 13.8\% of the whole dataset. \begin{table}[] \def0.65{0.65} \begin{tabular}{|m{1.1cm}|m{1.2cm}|m{1.4cm}|m{1.3cm}|m{1.5cm}|m{1.5cm}|m{1.5cm}|m{1.4cm}|m{1.2cm}|} \scriptsize \centering \textbf{Healthcare} & \scriptsize \centering \textbf{Welfare} & \scriptsize \centering \textbf{Education} & \scriptsize \centering \textbf{Immigration} & \scriptsize \centering \textbf{Infrastructure and Environment} & \scriptsize \centering \textbf{Defense and Security} & \scriptsize \centering \textbf{Foreign Policy} & \scriptsize \centering \textbf{Society} & \scriptsize \centering \textbf{Political and Legal System} \tabularnewline \hline \scriptsize \centering drug reform, national oncology strategy & \scriptsize \centering tax-free allowance, 500+ programme, minimum wage & \scriptsize \centering e-learning, remote learning, dentist in every school & \scriptsize \centering immigrant, refugees & \scriptsize \centering climate change, reduce coil usage, water crisis & \scriptsize \centering national security, alliance with the USA, NATO alliance & \scriptsize \centering lack of foreign policy, EU collaboration, Weimar Triangle & \scriptsize \centering death penalty, separation of church and state, LGBT & \scriptsize \centering presidential veto, independence of the courts \tabularnewline \hline \end{tabular} \caption{Political advertising -- categories with examples.\label{tab:examples}} \end{table} \section{Polish 2020 Presidential Election - Use Case} \label{sec:use_case} We present the analysis of 250,000 tweets related to the Polish 2020 Presidential Elections gathered between February 2, 2020 and April 23, 2020. The data acquisition and sentiment assignment procedures were similar to those described in Section \ref{sec:dataset}. The dataset and model we propose enabled us to analyze sentiment polarity across all election promise categories. Figure \ref{fig:sentiment} shows the overall average sentiment categories. The sentiment has been assigned on a -1 (negative) to 1 (positive) scale. None of the categories were positive on average; hence for readability we show only the zoomed part of the graph with a~scale from -0.5 (moderate negative) to 0 (neutral) sentiment. All categories contain a~much more negative attitude on the scale of an absolute sentiment analysis score. As we can imagine, most tweets gathered by us are from potential voters, and there are many more negative than positive messages. Most of the sentiment analysis tools available right now perform only general sentiment detection, saying only how many positive or negative tweets they have identified and analyzed. However, our dataset and model enable us to go deeper into the analysis of attitudes towards particular political advertising categories or even more granular towards specific election promises. \begin{figure}[t] \begin{floatrow} \capbtabbox{ \begin{tabular}{|c|c|c|c|c|} \label{tab:scores} \small Category & P & R & F1 & \# \\ \hline \small Healthcare & 0.75 & 0.72 & 0.74 & 586 \\ \small Welfare & 0.76 & 0.60 & 0.67 & 526\\ \small Defense & 0.92 & 0.71 & 0.80 & 57\\ \small Legal & 0.79 & 0.59 & 0.68 & 352\\ \small Education & 0.81 & 0.57 & 0.67 & 163\\ \small Infrastructure & 0.77 & 0.59 & 0.67 & 284\\ \small Society & 0.82 & 0.67 & 0.74 & 386 \\ \small Foreign Policy & 0.86 & 0.43 & 0.57 & 93\\ \small Immigration & 0.89 & 0.67 & 0.76 & 60\\ \hline \small & \textbf{0.82} & \textbf{0.62} & \textbf{0.70} & \textbf{2507} \\ \hline \end{tabular} }{ \caption{Precision, Recall, and F1 score for each of the promises categories. The last column presents the number of examples in the dataset.} } \hfill \begin{minipage}[t]{0.55\textwidth} \ffigbox { \label{fig:sentiment} \includegraphics[width=\linewidth]{sent.png} } { \caption{Sentiment orientation for each of political advertising category. The bars mean standard deviations. } } \end{minipage} \end{floatrow} \end{figure} \section{Conclusions and Future Work} \label{sec:conclusions} A new dataset and model enables us to analyze the Polish political scene, counter political misinformation in social media, and evaluate the political advertising of candidates. We plan to work on more datasets and models to fight fake news, classify political agitation content, and widen natural language solutions in regards to elections and political content in Polish social media. The dataset annotation will be very challenging due to many potential concept drifts between different election types such as presidential, parliamentary, European Union, and others. We use political advertising model to generate presidential candidates' vector representations. We can compare candidates with each other and say who is similar to whom. \section*{Acknowledgment} \small The work was partially supported by the National Science Centre, Poland grant No. 2016/21/N/ST6/02366 and by the Faculty of Computer Science and Management, Wrocław University of Science and Technology statutory funds. \nocite{Tumasjan2010, Burnap2016, Heredia2017, Prasetyo2015, Bayerl2011, Kearney2013, Gorwa2017, Bahuleyan2018a, Kochkina2018b, Ceron2016, Cohen2013, Gayo-Avello2012, Yaqub2017, Best2015, Isaak2018, Rossi2020, Golovchenko2020, Kearney2013, Bernaczyk2020ZnaczeniePolitycznego} \bibliographystyle{acl}
{'timestamp': '2020-06-19T02:06:15', 'yymm': '2006', 'arxiv_id': '2006.10207', 'language': 'en', 'url': 'https://arxiv.org/abs/2006.10207'}
arxiv
\section{Introduction} \label{introduction} Generative Adversarial Networks (GANs) \cite{goodfellow2014generative} can generate outstanding realistic examples, but suffer from two recognized problems (illustrated in Fig.1(a),(b) respectively): (1) Mode collapse, the generators of GANs could commonly miss modes in the training data while successfully cheating the discriminators; (2) Training instability, the training processes of GANs may fail at certain stages of the training. Many researchers have been devoted to solving them theoretically \cite{arjovsky2017wasserstein,zhao2016energy,salimans2018improving} or empirically ~\cite{salimans2016improved,metz2016unrolled,lin2018pacgan}, but these problems are still open. In this work, we tackle these problems by imposing explicit manifold prior onto GANs. GAN is recognized to model manifold from observed samples~\cite{zhu2016generative}. Since no latent representation are explicitly provided for the observed samples, GAN can be seen as implementing implicit manifold learning. It is worth noting that explicit manifold learning has advantages correspondingly addressing the above two problems: (1) By explicitly coding each observed sample on the generated manifold, all modes in the training data are guaranteed to be recovered and thus mode collapse problem can be solved naturally; (2) Explicit manifold learning has effect of pulling the generated manifold to the observed samples, which provides effective gradient to avoid the training instability at the beginning of training~\cite{salimans2016improved}. However, directly employing the conventional manifold learning methods fails to recover the intrinsic manifold to generate realistic samples. Manifold learning methods usually follow important assumptions like neighbors points lying close to a locally linear patch or preserving local structures, which are generally not satisfied in case of sparsely or unevenly distributed data. To construct an appropriate prior for GAN, we are motivated to further simplify the generated manifold to address the shortage in training data. Specifically, a new target for manifold learning, \emph{Minimum Manifold Coding}(MMC), is imposed to encouraging small Riemann volume of the generated manifold. The proposed MMC turns out a general form of the Shortest Hamiltonian Path(SHP) problem~\cite{polychronopoulos1996stochastic}, which aims to find a minimum manifold with fixed dimensions to cover all the samples and thus guarantees the simple and crease-free generated manifold. The standardized codes derived from MMC are then employed as prior to regularize the generator training in GAN, which constitutes the proposed framework of MMCGAN. The generated samples from MMCGAN in addressing mode collapse and training instability problems are illustrated in Fig.1(c),(d) correspondingly. We have conducted experiments on both toy datasets of 2D-SwissRoll, 25-Grid and realistic datasets of MNIST, Cifar10, ImageNet to show the effectiveness of MMC and MMCGAN. The main contributions can be summarized in three-fold: \begin{itemize} \item We propose to employ explicit manifold learning as prior to address the mode collapse and training instability problems of GAN. \item A new manifold learning target of Minimum Manifold Coding (MMC) is imposed to tackle the sparse and uneven data distribution and provide more suitable prior for GAN training. An approximate solution is also provided for the MMC problem. \item Extensive experiments shows that MMCGAN can alleviate mode collapse, stabilize training, and improve the quality of generated samples on different GAN architectures. \end{itemize} \begin{figure*}[t] \centering \subfigure[WGAN-gp] { \includegraphics[width=1.5in]{gaussian_wgan.jpg} } \subfigure[standard GAN] { \includegraphics[width=1.5in]{gaussian_standard.jpg} } \subfigure[MMC+WGAN-gp] { \includegraphics[width=1.5in]{gaussian_wganour.jpg} } \subfigure[MMC+standard GAN] { \includegraphics[width=1.5in]{gaussian_standardour.jpg} } \caption{Examples of (a) mode collapse and (b) training instability on the 25-Grid dataset. (c) and (d) shows the corresponding results from the proposed MMCGAN.} \end{figure*} \section{Related Work} \label{sec2} \subsection{Manifold Learning} \label{sec2.3} Manifold learning assumes that data are distributed around some low-dimensional manifolds rather than all over the data spaces. The goal of manifold learning is to discover this low-dimensional compact representation for the high-dimensional data. Classical manifold learning methods include LLE~\cite{roweis2000nonlinear}, Isomap~\cite{tenenbaum2000global}, Laplacian Eigenmaps~\cite{belkin2003laplacian} , ltsa~\cite{zhang2004principal}, t-SNE~\cite{maaten2008visualizing}, LargeVis~\cite{tang2016visualizing}, Umap~\cite{mcinnes2018umap}, etc. These methods basically consist of three steps: (1) finding k-nearest neighbors; (2) constructing a graph to preserve the structures of the raw data; and (3) embedding the raw data into low-dimensional representation satisfying the manifold structure. While manifold learning methods are widely used in data visualization and dimensionality reduction problems, they are not readily used as prior for generating realistic samples. One of the most important reasons is that manifold learning assume a topological space where every point has a neighborhood that is homeomorphic to the interior of a sphere in Euclidean space. Therefore, k-nearest neighbors represent the local structures only if the data are dense and evenly-distributed, which is hardly satisfied for realistic samples like image datasets. This critically limits the integration of conventional manifold learning methods into generative models like GAN. In this work, we introduce a further MMC target to simplify the generated manifold and fit to GAN in generating realistic samples. Comparison results with conventional manifold learning methods will be reported in the experiment section. \subsection{Generative Adversarial Networks} \label{sec2.1} Generative Adversarial Networks have two major parts: Generator (G) and Discriminator (D). The original form of GAN ~\cite{goodfellow2014generative} aims to find a Nash equilibrium to the following min-max problem: \begin{equation}\label{rawgan} \min_{G}{\max_{D}{\mathbb{E}_{x \sim q_{data}}[\log{D(x)}]+\mathbb{E}_{z \sim p_{z}}[\log{(1-D(G(z)))}]}} \end{equation} where $z \sim R^m$ is a latent representation drawn from distribution $p_z$ such as $\mathcal{N}(0,1)$ or $\mathcal{U}[1,-1]$. Theoretically, at the global optimum of Eqn.(\ref{rawgan}), generator will produce samples with the same distribution as data distribution. Unfortunately, standard GAN does not work well as it tends to be unstable during training, and its generator may treat the discriminator without diversities, which is called mode collapse. Many researchers make efforts to solve these problem \cite{nowozin2016f,fedus2017many,salimans2018improving,mescheder2018training}. An important line of work start from WGAN~\cite{arjovsky2017wasserstein}, which provides comprehensive theoretical analysis and gained good experimental performance. WGAN theoretically analyzes the reason why GAN is unstable and solve it by using Wasserstein distance to substitute Jensen-Shannon divergence in GAN. Then, the objective function changes to: \begin{equation}\label{wgan} \min_{G}{\max_{D}{\mathbb{E}_{x \sim q_{data}}[D(x)]+\mathbb{E}_{z \sim p_{z}}[-D(G(z))]}} \end{equation} Note that the discriminators here needs to be $1$-$Lipstchitz$. WGAN achieves this target by clipping the gradients. After that, WGAN-gp\cite{gulrajani2017improved} provides a more stable solution by imposing gradient penalty: the derived gradients will not be limited in only two values $\{-1,1\}$. SNGAN\cite{miyato2018spectral} is the state-of-art choice in this line of work, which is faster than WGAN-gp and achieves better performance. Recently, SNGAN was been implemented in BigGAN \cite{brock2018large}, which is the first photo-realistic GAN with the following hinge loss as objective function: \begin{equation}\label{sngan} \begin{split} &\min_{D}{\mathbb{E}_{x \sim q_{data}}[(1-D(x))_+]+\mathbb{E}_{z \sim p_{z}}[(1+D(G(z)))_+]}\\ &\min_{G}{\mathbb{E}_{z \sim p_{z}}[-D(G(z))]} \end{split} \end{equation} where $(\cdot)_+=\max(\cdot,0)$. We will compare the proposed MMCGAN with these typical GAN architectures to examine the effectiveness in addressing mode collapse and training stability. \subsection{GAN with Reconstruction Loss} \label{sec2.2} In this work, manifold learning serves as prior for GAN by adding a manifold preserving reconstruction loss during training the generator. In fact, reconstruction loss is one intuitive and efficient way to guarantee GAN not to lose information. This subsection reviews some GAN variants with reconstruction loss to penalizing losing different types of information. CycleGAN\cite{zhu2017unpaired} employs reconstruction loss to constrain that the image-to-image translation generates more diverse samples. EBGAN \cite{zhao2016energy} replaces traditional discriminator loss with reconstruction loss to show the performance of other energy functions. BAGAN \cite{yang2017dagan} uses the reconstruction loss to training a decoder as a better initialization for the generator, however, such initialization is a trick without theoretically analysis, and the coding of auto-encoder have a completely different distribution from $p_z$, which make its benefit unobvious. The most similar study is sinGAN ~\cite{shaham2019singan}, which uses reconstruction loss to guarantee that there exists an input noise to generate each of the raw image samples. The difference lies in that, sinGAN is proposed for a single input, which will not converge in case of multiple samples with random noise. Moreover, the reconstruction loss introduced in this work is motivated from manifold preserving perspective, which is compatible with the manifold discovery nature of generative models. \section{Minimum Manifold Coding} \label{sec4} As discussed in Introduction, in case of sparse and uneven data distribution, it is difficult for the generator to correctly recover manifold and generate realistic samples. We are motivated to introduce a new manifold learning target, Minimum Manifold Coding(MMC), to address these problems. Such target encourages a simple and unfolded manifold, so that the generators can fit easily. In this section, we will first derive the formal definition of the MMC, and then analyze its correlation with the Shorted Hamiltonian Path to explain why MMC leads to unfolded manifold. Finally, we will provide a practical algorithm to solve MMC. \subsection{Notations and Definitions} \label{sec4.1} \textbf{Notations}. Let the input data be $X=\{x_1,x_2,...,x_N\}$ where $\forall i,x_i \in R^n$, and we suppose all the samples are different from each other. The manifold learning methods embed $X$ to a low-dimensional space: we can obtain a set of codes corresponding to the input data: $C=\{c_1,c_2,...,c_N\}$, where $\forall i, c_i \in R^m$, $m<n$. Note that such codes represent the encoding mapping: $c_i=C(x_i), \forall i \in \{1,2,...,N\}$. The decoding function $f_C$ can recover the data $X$ from the coding $C$, and we denote $F_C$ as the set of all the decoding functions of $C$: $F_C=\{f_C:R^m\mapsto R^n| \forall c_i \in C, x_i=f_C(c_i)\}$. In addition, a decoding function $f_C$ can generate a corresponding manifold $M(f_C)=\{x|\forall c\in R^m, x=f_C(c)\}$. Obviously, all these manifolds of decoding functions in $F_C$ will intersect at the raw data points $X$. Recall that our target is to find a simple and unfolded manifold so that the generator of GAN can fit easily. Intuitively, the manifold with the minimum Riemann volume is simple, and we derive a new objective named Minimum Manifold Coding(MMC) from this motivation. Before deriving the formal definition of MMC, we will define \emph{Mapping Measure} first. \begin{Def}\label{MM} (Mapping Measure). Let the convex hull for a coding $C$ is $S=conv(C)$. A decoding function $f_C$ maps $S$ to the corresponding manifold: $f_C(S)\subset M(f_C)$. The mapping measure for $f_C$ defined as the Riemann volume of $f_C(S)$: \begin{equation} \Lambda(f_C)=\int_{S}{\sqrt{\left | det(J_{f_C}(s)^TJ_{f_C}(s)) \right|}ds} \end{equation} Where $det$ is the determinant of the matrix, and $J_{f_C}$ is the Jacobian matrix of $f_C$. \end{Def} \begin{Def}\label{MMC} (Coding Measure, Coding Manifold, and Minimum Manifold Coding). Let $F_C$ be a set of all the decoding functions with the coding $C$. The coding measure of the coding $C$ is the minimum mapping measure of the functions in $F_C$: \begin{equation} \rho(C)=\min_{f_C\in F_C} {\Lambda(f_C)} \end{equation} The coding manifold is the manifold generated by the decoding function $f_C$ with the minimum mapping measure: \begin{equation} M(C)=M(\arg\min_{f_C\in F_C} {\Lambda(f_C)}) \end{equation} Minimum manifold coding is to find a coding $C'$ with the minimum coding measure: \begin{equation} C'= \arg\min_{C}{\rho(C)} \end{equation} \end{Def} \begin{figure}[t] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=0.7\columnwidth, height=1.2in]{cross.png}} \caption{Illustration of the shortest Hamiltonian Path with no cross.} \end{center} \vskip -0.2in \end{figure} \subsection{General Form of the Shortest Hamiltonian Path} Such definition of MMC has a good property: the coding measure only depends on the arrangement of the data on the manifold, rather than the scale of codes. For example, if $m=1$, the manifolds will be curves, i.e., 1-D manifolds. As coding measure is the minimum mapping measure, it represents a set of line segments which connects all the points. Specifically, we can visualize the coding manifolds with painting line segments from the data point with the minimum code to the point with the maximum code in the data space. It is clear that such manifold only depends on the order of the codes, rather than the specific code values. As a matter of fact, the minimum manifold coding with 1-D manifold is equivalent to the Shortest Hamiltonian Path(SHP). Since the convex hull for a 1-D coding $C$ is a line segment ranging from the minimum code to the maximum code, the coding measure of the coding $C$ represents a path visiting each vertex exactly once, which is called Hamiltonian Path~\cite{tutte1946hamiltonian}. Therefore, minimizing the manifold coding can retrieve the shortest Hamiltonian path. In other words, MMC can be seen as a general form of the shortest Hamiltonian path. It is worth noting that the shortest Hamiltonian path represents a simple curve with less cross. Suppose there is a cross ($AC+BD$) in Hamiltonian path, see Fig.2. Without loss of generality, we suppose the cross aims to connect $AB$ and $CD$. It is clear that $AD+BC$ can also achieve the same connection target with no less, and $AD+BC<AC+BD$. As the general form of SHP, MMC is expected to discover manifold with less cross or even unfolded. \subsection{Approximate Solution of MMC} \label{sec4.3} As known to all, the SHP is an NP problem, so the MMC problem is also an NP problem and can only be approximately solved. In this subsection, we provide a practical approximate solution of the MMC problem. In brief, we split this problem into two parts: getting the decoding functions, and pursuing smaller mapping measures. For the first part, we use an auto-encoder with reconstruction loss. For the second part, we have the following theorem: \begin{thm}\label{thm} Let $f_C\in F_C$ be a decoding function which satisfies the L-Lipschitz condition on $S=conv(C)$, then the mapping measure of $f_C$ has an upper bound: \begin{equation} \Lambda(f_C)=\int_{S}{\sqrt{\left | det(J_{f_C}(s)^TJ_{f_C}(s)) \right|}ds}\leq L^m \int_{S}{ds} \end{equation} where $m$ is the dimension of the coding space. \end{thm} The proof is provided in Supplement-A. According to this theorem, as there always exist an $L$ to make decoder satisfy the $L$-$Lipschitz$ condition, we can use a minimum convex hull loss to get smaller convex hull $S$ and obtain a lower upper bound. In this work, we choose the constraint of L2-Norm for simplicity, so the objective function for auto-encoder becomes: \begin{equation}\label{gam} \min_{Dec,Enc}{\frac{1}{2}\mathbb{E}_{x \sim q_{data}}(\|x-Dec(Enc(x))\|^2+\gamma\|Enc(x)\|^2)} \end{equation} where $Dec$ is the decoder, and $Enc$ is the encoder of the auto-encoder. After training, we can obtain a coding with small coding measure. Recall that the coding measure will not change if we use the transformation which do not alter the arrangements of coding, so we can design a proper transformation to obtain an expected coding distribution. Note that the latent representations of GAN is drawn from the distribution $\mathcal{N}(0,1)$, and a code with zero-mean and one-variance will be more reasonable as the prior. In this work, we use z score standardization as the transformation function: $C'=\frac{C-\mathbb{E}C}{std(C)}$. \begin{figure}[t] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=0.65\columnwidth, height=1.4in]{reconstruct.jpg}} \caption{The manifold preserving reconstruction loss pulls the generator manifold to the data points according the corresponding codes.} \label{mc} \end{center} \vskip -0.2in \end{figure} \begin{figure*}[t] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=5.5in]{our_alg.png}} \caption{Illustration of MMCGAN framework.} \end{center} \vskip -0.2in \end{figure*} \section{MMCGAN} \label{sec3.1} In this section, we will use the manifold obtained by MMC as prior to improve the training of GAN, so called MMCGAN. There are many ways to implement the idea of using explicit manifold learning prior. We employ one intuitive way to constrain the generator to fit the prior manifold by $L2$ loss between the generator manifold and prior manifold: $R=\mathbb{E}_{x \sim q_{data}}\|x-G(C(x))\|^2$. We call the L2 loss as manifold preserving reconstruction loss. The overall framework of MMCGAN is shown in Fig.4, which consists of the auto-encoder component to derive the manifold prior, and the GAN component to using the prior to regularize the generator training. The training process has three steps: in the first step, we employ auto-encoder with loss of convex hull to get the latent code that minimizes the mapping measure. The derived code is then standardized by with z-score to be compatible with the input distribution of GAN. In the second step, we use the standardized code as prior to initialize the generator. Specifically, manifold preserving reconstruction loss is imposed at the beginning of the generator training, e.g., for hinge loss, we have: \begin{equation}\label{rlhinge} \begin{split} &\min_{D}{\mathbb{E}_{x \sim q_{data}}[(1-D(x))_+]+\mathbb{E}_{z \sim p_{z}}[(1+D(G(z)))_+]}\\ &\min_{G}{\mathbb{E}_{z \sim p_{z}}[-D(G(z))]}+\frac{\lambda}{2}\mathbb{E}_{x \sim q_{data}}\|x-G(C(x))\|^2 \end{split} \end{equation} Fig.3 illustrates the role of the manifold preserving reconstruction loss: it can be seen as some anchor pulling the generator manifold close to the data manifold, and ensure GANs are capable of producing all the input samples. Furthermore, GAN training is usually unstable at the beginning because of the adversarial mechanism. The manifold preserving reconstruction loss can provide consistent gradients to stabilize training. When the generator manifold is close enough to the AE recovered manifold, the role of manifold preserving reconstruction loss will be trivial. In contrast, further imposing the loss will prevent the generator from exploring its potential to cheat the discriminator. Moreover, the Nash equilibrium is difficult to achieve and guarantee the generator distribution is the same as the data distribution. Therefore, in the third step, we remove the manifold preserving reconstruction loss and turn to the training GAN in the standard way. Empirically, we use the moving average of the reconstruction loss to measure the closeness between the generator manifold and AE recovered manifold. A threshold value $T$ is set, and the third step switches on when the moving average is below $T$. \begin{figure*}[t] \centering \subfigure[MMC] { \includegraphics[width=1.2in]{MMC_swiss.jpg} } \subfigure[Laplace Eigenmap] { \includegraphics[width=1.2in]{LE_swiss.jpg} } \subfigure[LLE] { \includegraphics[width=1.2in]{LLE_swiss.jpg} } \subfigure[ltsa] { \includegraphics[width=1.2in]{ltsa_swiss.jpg} } \subfigure[UMAP] { \includegraphics[width=1.2in]{UMAP_swiss.jpg} } \subfigure[MMC] { \includegraphics[width=1.2in]{MMC_gaussian.jpg} } \subfigure[Laplace Eigenmap] { \includegraphics[width=1.2in]{LE_gaussian.jpg} } \subfigure[LLE] { \includegraphics[width=1.2in]{LLE_gaussian.jpg} } \subfigure[ltsa] { \includegraphics[width=1.2in]{ltsa_gaussian.jpg} } \subfigure[UMAP] { \includegraphics[width=1.2in]{UMAP_gaussian.jpg} } \caption{Recovered manifolds by MMC and traditional manifold learning methods on: (a)-(e) 2D-SwissRoll and (f)-(i) 25-Grid.} \label{fig2} \end{figure*} \section{Experiments} \label{sec5} In this section, after introducing the experiment settings of MMCGAN, we first compare MMC with the traditional manifold learning on sparse and uneven data, and then evaluate MMCGAN on different datasets with widely used GAN architectures to show its effectiveness in avoiding mode collapse and stabilizing training. \subsection{Implementation Settings} Note that delicate tuning of model hyperparameters and learning parameters is not necessary for MMCGAN, as most settings are universal for different datasets and model architectures. For the model hyperparameters, there are two hyper-parameters: we report the experimental results using $\gamma=\frac{1}{10m}$ for Eqn.(\ref{gam}) and $\lambda=1$ for Eqn.(\ref{rlhinge}), where $m$ is the dimension of latent representations in GAN. For the learning parameters, we enumerate them according to the training process illustrated in Section 4. For the first step, we use Adam optimizer~\cite{kingma2014adam} with $\beta_1 = 0.5$, and $\beta_2 = 0.9$. The learning rate scheme is described in SGDR\cite{loshchilov2016sgdr} which can accelerate convergence, with $T_0=10$, $\eta_{min}=0$ and $\eta_{max}=0.001$. For the second step, the moment of moving average is $0.999$ in this work, and the threshold $T$ is the moving average of the reconstruction loss of the first step. We have conducted experiments on 5 datasets and the following list the choice of threshold for these experiments: (1) \emph{2D-SwissRoll}, 0.1; (2)\emph{25-Grid}, 0.01; (3) \emph{MNIST}, 6; (4) \emph{Cifar10}: 30; (5) \emph{ImageNet20}: 1000. For the third step, the training settings are all the same as the normal GAN. The specific hyperparameters and architectures of benchmark GANs used in practice are detailed in Supplement-B. In addition, all the experiments use data-parallel distributed training in Pytorch with 6 Nvidia Titan X 12G. The source codes can be obtained in the supplementary materials. \subsection{MMC Evaluation} \label{sec5.1} The choice of explicit manifold learning prior determines the performance. To evaluate the performance of MMC prior, we conducted experiments on two synthetic datasets which are sparsely and unevenly distributed respectively: (1) \emph{2D-SwissRoll}, 200 samples which obtained by \verb|sklearn.datasets.make_swiss_roll| with noise of 0.25. To make the results more clear, we only use the first two dimensions and scale down to $\frac{2}{15}$. (2) \emph{25-Grid}\cite{lin2018pacgan}, 200 data samples from a mixture of 25 two-dimensional Gaussians with the same variances $\frac{1}{3200}$ and different means $(\frac{i}{2\sqrt{2}},\frac{j}{2\sqrt{2}})$, where $i, j \in \{-2, -1, 0, 1, 2\}$. We also examined the traditional manifold learning methods: PCA~\cite{wold1987principal}, Isomap~\cite{tenenbaum2000global}, Laplacian Eigenmaps~\cite{belkin2003laplacian}, LLE~\cite{roweis2000nonlinear}, HLLE~\cite{donoho2003hessian}, MLLE~\cite{zhang2007mlle}, ltsa~\cite{zhang2004principal}, t-SNE~\cite{maaten2008visualizing}, and Umap~\cite{mcinnes2018umap}. These methods are all implemented with official packages or sklearn, and the hyperparameters are \verb|n_neighbors=3, n_components=1|. To evaluate the performance intuitively, as analyzed in Section 3.2, we can use a set of line segments to connect all the data according to the order of coding to show the performance of the manifold learning. Fig.5 shows the results of MMC and 4 of the traditional manifold learning methods. Results for other manifold learning methods can be seen in Supplement-C. It can be seen that the manifold recovered by the examined traditional manifold learning methods tend to be folded and twisted, while MMC derives simple manifolds based on the proposed approximate solution. \subsection{MMCGAN Evaluation} \begin{figure}[t] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=0.7\columnwidth]{modecollapse.eps}} \caption{Mode collapse experiments: comparing between standard GAN architectures, PacGAN and the proposed MMCGAN.} \label{mc} \end{center} \vskip -0.2in \end{figure} \begin{figure*}[t] \centering \subfigure[WGAN-gp] { \includegraphics[width=1.6in]{gaussian_wgan.jpg} } \subfigure[WGAN-gp(PacGAN)] { \includegraphics[width=1.6in]{gaussian_wganpac.jpg} } \subfigure[MMC+WGAN-gp] { \includegraphics[width=1.6in]{gaussian_wganour.jpg} } \subfigure[SNGAN] { \includegraphics[width=1.6in]{gaussian_SN.jpg} } \subfigure[SNGAN(PacGAN)] { \includegraphics[width=1.6in]{gaussian_SNpac.jpg} } \subfigure[MMC+SNGAN] { \includegraphics[width=1.6in]{gaussian_SNour.jpg} } \caption{Intuitive results of mode collapse for the WGAN-gp and SNGAN architectures. } \label{fig} \end{figure*} \subsubsection{Mode Collapse Results} \label{sec5.2} Mode collapse indicates that the generator only produces data within a subset of modes. Recently, such phenomenon is not well-understood, and previous work provide many hypothesis, like improper objective functions~\cite{arora2017generalization,arjovsky2017wasserstein} and weak discriminators~\cite{li2017towards,salimans2016improved}. Based on these hypothesis, previous work have proposed many methods, e.g., ATI~\cite{dumoulin2016adversarially}, VEEGAN~\cite{srivastava2017veegan}, unrolled GAN~\cite{metz2016unrolled}. The state-of-art is PacGAN\cite{lin2018pacgan}, which strengthens the discriminators by packing the inputs. In this subsection, we compare MMCGAN with PacGAN on \emph{25-Grid} on three different architecture: standard GAN, WGAN-gp, SNGAN. Specifically, we set the latent representation with dimension $m=1$ to make the generator produce a low-dimensional manifold. As \emph{25-Grid} is constructed by 25 Gaussian distributions, it has 25 different modes, and we use the distance between the samples and the centers of 25 Gaussian distributions to examine whether the generator can produce such modes. Specifically, we sampled from the generator distributions 200 times, and recorded how many modes have samples near enough, i.e., the distance is less than $0.1$. All the experiments repeat 5 times. In each experiment, to obtain a stable results, we averaged the last 5 results before the end of training. The results are summarized in Fig.6. It can be seen that MMCGAN can obtain more modes in \emph{25-Grid} datasets for WGAN-gp and SNGAN, but work slightly poorer for the standard GAN. That is because MMCGAN can only improve the initialize states of training, while the standard GAN has recognized problem of its global minima~\cite{salimans2016improved}, which is well solved in WGAN-gp and SNGAN. PacGAN also contains special mechanism to address this problem by strengthening the discriminator. The intuitive results of WGAN-gp and SNGAN architectures can be seen in Fig.7, MMCGAN successfully cover almost all the modes while the raw GAN and PacGAN usually miss some modes especially in the sparsely and unevenly distributed area. \begin{figure}[t] \centering \subfigure[standard GAN] { \includegraphics[width=1.5in]{MNIST_standard.png} } \subfigure[MMC+standard GAN] { \includegraphics[width=1.5in]{MNIST_standardour.png} } \subfigure[SNGAN] { \includegraphics[width=1.5in]{MNIST_SN.png} } \subfigure[MMC+SNGAN] { \includegraphics[width=1.5in]{MNIST_SNour.png} } \caption{Visualization of samples produced by generators on MNIST: (a) standard GAN without BatchNorm; (c) SNGAN without BatchNorm; (b) and (d) illustrate the corresponding results with MMC prior.} \label{fig} \end{figure} \subsubsection{Training Stability Results} \label{sec5.1} We use two datasets to show the performance of MMCGAN in stabilizing training: (1) \emph{25-Grid}: We visualize the generator distributions in Fig.1(b)(d), where the green points are the fake data and the yellow points are the training data. We also paint the contour lines of the discriminators to show the training trend. It can be seen that GAN with standard objective (Eqn.(\ref{rawgan})) is very fragile: the generator manifold deviates too far to fit the data. The proposed MMC prior successfully avoid such deviation for stable training. (2) \emph{MNIST}~\cite{lecun1998mnist}: we use the training set which consists of 60K $28\times28$ images of handwritten digits. The benchmark architecture is 3-layer DCGAN \cite{radford2015unsupervised} without BatchNorm~\footnote{Batch normalization plays an important role in stabilize training of DCGAN, we remove it to obtain an unstable control group to show the effect of MMCGAN.}~\cite{ioffe2015batch}. The generated images are visualized in Fig.8: standard GAN(Eqn.(\ref{rawgan})) and SNGAN with hinge loss (Eqn.(\ref{sngan})) without BatchNorm both failed, and adding MMC prior successfully recovered the data manifold and generated the realistic handwritten digit images. \begin{figure}[t] \centering \subfigure[IS] { \includegraphics[width=1.5in]{IS_C10.eps} } \subfigure[FID] { \includegraphics[width=1.5in]{FID_C10.eps} } \caption{Inception score and FID of MMCGAN and baseline on Cifar10. } \end{figure} \begin{figure}[t] \centering \subfigure[IS] { \includegraphics[width=1.5in]{IS_I128.eps} } \subfigure[FID] { \includegraphics[width=1.5in]{FID_I128.eps} } \caption{Inception score and FID of MMCGAN and baseline on ImageNet20. } \end{figure} \subsubsection{Quantitative Results} \label{sec5.3} In this subsection, we will examine Inception Score~\cite{salimans2016improved} and FID \cite{heusel2017gans} to quantitatively evaluate the quality of generated samples of MMCGAN. Experiments are conducted on the CIFAR-10 and ImageNet20. \emph{Cifar-10}: The CIFAR-10 dataset consists of 60k 32$\times$32 color images in 10 classes. We use 50k training images for the training of GAN. In particular, we choose SNGAN with the implementation of BigGAN as the benchmark. We report IS and FID measures in Fig.9: As training proceeds, MMCGAN can improve FID measure while keeping the similar IS measure. This validates that MMCGAN avoid mode collapse and keeps the same global minima. \emph{ImageNet20}: We select a subset of ImageNet ILSVRC 2012~\cite{deng2009imagenet} for evaluation: 20 categories which start with 'n014' and 'n015', totally about 26k $128\times128$ images. SAGAN~\cite{zhang2018self} selected as the baseline due to its efficiency in large-scale high resolution datasets. The model was implemented based on the code of BigGAN. With each experiment repeating 3 times and calculating the means and standard deviations, Fig.10 plots the error bars for IS and FID measures. All the experiments of traditional SAGAN have broken down before $2\times 10^{4}$ iterations, and the MMCGAN can achieve better performance and keep stable until $4\times 10^{4}$ iterations. Note that the training of SAGAN is stable in the complete ImageNet. The observed instability might be due to the lack of data with such high resolution, where MMC prior successfully stabilize the training process to make up for the data shortage. \section{Conclusion and Future Work} \label{sec6} In this work, we introduce explicit manifold learning as prior for GAN to avoid mode collapse and stabilize training. A new target of Minimum Manifold Coding is further imposed for manifold learning. Such target is validated to discover simple and unfolded manifolds even when the data is sparsely or unevenly distributed. There remain many interesting directions to be explored in the future. The first direction is the theoretical proof of equilibrium, convergence and analysis on the improvement of mode collapse and training stability. The second direction can pursue more characteristics of generative models from the perspective of manifold learning, e.g., regularizing the completeness of manifold to obtain balanced distribution of GAN for data augmentation. Another interesting direction is to explore the potential of GAN beyond data generation. As the generator manifold can closely approach the data manifold with minimum Riemann volume, we can employ GAN to approximate the solution of MMC, SHP and other similar optimization problems. \bibliographystyle{IEEEtran}
{'timestamp': '2020-06-19T02:10:37', 'yymm': '2006', 'arxiv_id': '2006.10331', 'language': 'en', 'url': 'https://arxiv.org/abs/2006.10331'}
arxiv
\section{Introduction} \label{s:intro} Functional data analysis (FDA) is routinely encountered in modern applications due to the rapid advancement of new techniques to collect high-resolution data that can be viewed as curves; see~\cite{ramsay2005fda, morris2015functional, wang2016functional} for a comprehensive treatment. An overwhelming focus has been on nonparametric estimation of the underlying functions. However, shape constraints arise naturally in modern applications. {{One such example is \textit{local sparsity}, i.e., the function is exactly zero on subregions, in contrast to global sparsity that refers to a zero function.}} Local sparsity is a crucial characteristic for a nonparametric method to be interpretable in a variety of applications, and the estimation of the support as well as the function itself is of primary interest. This article aims to develop a flexible method with efficient implementation and theoretical guarantees for simultaneously estimating and recovering the support of locally sparse functions. Our motivation stems from neuroscientific studies using human intracranial electroencephalography (iEEG) data. {{iEEG is an emerging invasive method that offers anatomically precise measurements of human brain activity with electrodes placed on or implanted in the human brain, leading to excellent temporal resolution data and high signal-to-noise ratios \citep{lachaux2012high,kaiju2017high}}}. In most iEEG experiments, {{participants are presented with multiple experimental conditions. The brain response to each condition is recorded, and the experimenter wishes to know whether and how they differ}}. The contrast of brain activities is expected to be locally sparse (zero at certain period of time), and detecting non-sparse regions is of substantial interest to neuroscientists in addition to estimating the coefficient functions. For example, Figure \ref{fig:intro-demo} shows iEEG data from an audiovisual speech perception task \citep{ozker2018frontal} under two experimental conditions, namely, ``auditory-only'' and ``audiovisual''. In this study, the goal is to understand how the brain responds to auditory and visual stimuli through analyzing differential brain activities to these two conditions. Large trial-to-trial variation necessitates the use of statistical inference to automate the extraction of both population trajectories and supports of underlying brain activities. \begin{figure} \centering \includegraphics[width=5in]{application/intro-demo.pdf} \caption{Baseline corrected response of iEEG high-gamma power under auditory-only (left) and audiovisual (right) conditions. The data are obtained by decomposing the measured voltage signal into frequency space, converting to Decibel unit, calibrated to baseline (from $-1$ to $-0.3$ seconds), and then taking the average power in the 70-150Hz range. Each individual grey line is one trial. The bold solid line is the mean responses, and the shaded area around the mean is a pointwise 95\% confidence interval. \label{fig:intro-demo}} \end{figure} Over the past several decades, there has been an extensive literature on sparsity. This leads to a rich menu of methods in the context of regularization-based variable selection with the parameter space being \textit{sparse vectors}, including the Lasso~\citep{tibshirani1996regression}, minimax concave penalty (MCP)~\citep{zhang2010nearly}, and bridge regression~\citep{frank1993statistical}, to name just a few; see \cite{fan2010selective} for a review. Such concepts have been extended to grouped variable selection and nonparametric \textit{sparse functions}. {{Indeed, coupled with basis expansions, sparse coefficient vectors regularize the estimated function and lead to globally sparse coefficient functions via grouped sparsity. Along this line, \cite{barber2017} extended group Lasso to functional data, and \cite{chen2016variable} adopted group MCP, both achieving variable selection and parameter estimation.}} However, comparatively little work has been done for functions with local sparsity. {{There is a related literature on utilizing various penalties to improve interpretability, for example, \cite{james2009functional,zhou2013functional,wang2015functional,lin2017locally}}}. These methods, however, rely on scalar responses and are not suitable for the motivating iEEG studies, where the response is functional and covariates are scalar; hereafter we refer to such cases as \textit{function-on-scalar regression}. Function-on-scalar regression poses unique challenges to methodological and theoretical developments. In particular, the intrafunctional dependence of responses is vital, and the large sample properties may be more intricately determined by the sample size (number of subjects) as well as the sampling frequency of individual trajectories of each subject. {{In what follows we focus our attention on longitudinal data over time that out motivating example corresponds to.}} In this paper, we propose a method for simultaneous regression and support estimation for function-on-scalar regression, where the underlying functions are locally sparse. We adopt group bridge estimators coupled with B-splines to recover the sparse pattern of functional regression coefficients. {{Unlike the group Lasso and Lasso, group bridge penalty provably achieves variable selection in linear models at the group and individual level simultaneously \citep{huang2009group}. This is particularly well suited for locally sparse functions by inducing exactly zero regions through grouping basis coefficients that contribute to the function at each time point, while maintaining parsimony and regularization of basis coefficients via selection at the individual level. Following our use of B-splines and grouping structure of variables, other penalties can also be considered if they ensure both group-level and individual-level sparsity; however, these methods have not been extended to function-on-scalar regression.}} The proposed method does not require Gaussian assumptions and {{allows flexible heterogeneous correlation structures through random effects that possibly depend on various experimental phases.}} This leads to a novel \textit{weighted functional group bridge} approach for function-on-scalar mixed effect models. On the algorithmic front, we introduce a nested alternating direction method of multipliers (ADMM) algorithm with ``warm-start'' and ``early stopping'' to speed up the computation. On the theoretical front, we establish a range of large sample properties, including rate optimality in the minimax sense for regression and selection consistency for support estimation. Although under different models, our theory relies on substantially simplified assumptions than the existing literature to regularize regression functions, notably Assumption~\ref{assumption:integral}, facilitating interpretability. We allow flexible sampling designs including the case when the number of time points grows faster than the sample size, which is better suited for iEEG studies. In an application to the aforementioned iEEG experiment, our results complement previous studies by showing that multisensory interactions are a powerful modulator of activity throughout the speech perception network~\citep{ozker2018frontal, karas2019cross}. The rest of the article is organized as follows. Section \ref{s:methodology} introduces our model, the proposed estimator, and the optimization algorithm. Section \ref{s:asymptotic-properties} provides asymptotic properties. Section \ref{s:simulation} contains simulations, followed by an application to iEEG analysis in Section \ref{s:application}. The proposed method is implemented in the R package {\verb!spfda!}, available on CRAN. The Appendix include all proofs and additional simulations. \section{Methodology} \label{s:methodology} \subsection{Model} Suppose a sample of $n$ functional signals $\bracketlg[s]{{y}_{i}(\time)}_{i = 1}^n$ is observed on a compact time set $\mathcal{T}$. We assume without loss of generality $\mathcal{T}=\bracketmd{0,1}$. The linear function-on-scalar mixed effect model assumes \begin{equation} \label{eq:FDA.model} {y}_{i}(\time)=\sum_{j=1}^{p}x_{ij}{\beta}_{j}(\time)+ {\theta}_{i}(\time) + {\epsilon}_{i}(\time), \end{equation} where $x_{ij}$ is a scalar predictor, ${\beta}_j(\time)$ is a fixed effect function, ${\theta}_{i}(\time)$ is a zero mean random effect with {{covariance kernel $\Sigma_{\bm{\theta}}(\time,\time')$ that captures the within-curve dependence}}, and the ${\epsilon}_{i}(\time)$ is the measurement error process independent of ${\theta}_{i}(\time)$ with zero means and covariance kernel $\Sigma_{\bm{\epsilon}}(\time,\time')=\sigma^{2}\delta_{t, t'}$; here $\delta_{t, t'}$ is the Kronecker delta. We assume ${\beta}_j(\time)$ is smooth and locally sparse on the time domain. We propose to use phase-dependent random effects to account for heterogeneous dependence structures in various stages of an experiment, such as resting phase, trial onset, and stimuli offset. In particular, we partition $\mathcal{T}$ into a union of disjoint intervals $\bracketlg[s]{\mathcal{T}^{\text{pa}}}_{\text{pa}=1}^{P}$, where each $\mathcal{T}^{\text{pa}}$ corresponds to a stage of the experiments, and random effects ${\theta}_{i}(\time)$ are smooth within each phase. Note this generalizes traditional mixed effect models where $P$ is typically set to one. We use B-splines $\bracketlg{{\phi}_{k}(\time)}_{k=1}^{K}$ to approximate each fixed effect function, that is, ${\beta}_j(\time) = \sum_{k = 1}^K {\gamma}_{jk} {\phi}_k(\time) + {R}_{j}(\time)$, where ${R}_j(\time)$ is the approximation error. In addition to sharp approximation bounds to smooth functions, B-splines are particularly well suited for sparse functions as they are locally supported and thus transfer sparsity in ${\beta}(\time)$ to a sparse $p$ by $K$ matrix $\bm{\gamma} = \{{\gamma}_{jk}\}_{p\times K}$. Let a non-negative integer $d$ be the degree of B-splines and define the knots of length $K+d+1$ be $\time_{\tidx_{1}}=\dots=\time_{\tidx_{d}}=0=\time_{\tidx_{d+1}}<\time_{\tidx_{d+2}}<\dots<\time_{\tidx_{K}}=1=\time_{\tidx_{K+1}}=\dots=\time_{\tidx_{K+d+1}}$. Then B-splines are defined recursively \citep{de1978practical} as follows: \begin{gather} {\phi}_{k,1}(\time) = \mathbf{1}_{[\time_{ \tidx_{k} }, \time_{ \tidx_{k+1} })}(t) \label{eq:spl-def1} ,\quad {\phi}_{k,d+1}(\time) = \frac{\time-\time_{\tidx_{k}}}{ \time_{\tidx_{k+d}} - \time_{\tidx_{k}} }{\phi}_{k,d}(\time) + \frac{ \time_{\tidx_{k+1}} - t }{ \time_{\tidx_{k+q-1}} - \time_{\tidx_{k+1}} }{\phi}_{k+1,d}(\time), \label{eq:spl-def2} \end{gather} where $k = 1, \ldots, K$. B-splines of order $q = d + 1$ are ${\phi}_{k}(\time) = {\phi}_{k,q}(\time)$, and we typically choose $q\geq 4$. In practice, functional data are observed at discrete time points. Let $\mathcal{T}_{0}=\bracketlg{\time_{\tidx}}_{\tidx=1}^{T} \subseteq \mathcal{T}$ be the set of time points at which ${y}_{i}(\time)$ is observed. Each partition set $\mathcal{T}_{0}^{\text{pa}}$ is defined as $\mathcal{T}_{0}\cap \mathcal{T}^{\text{pa}}$. Let $\bm{Y}=\bracketlg{y_{i \tidx}}_{n\times T}, \bm{\theta}=\bracketlg{{\theta}_{i\tidx}}_{n\times T}, \bm{E}=\bracketlg[s]{e_{it}}_{n\times T}$ be the discretized responses, random effects, and random noise observed at $\mathcal{T}_{0}$, respectively, and {{$\bm{X}=\bracketlg{x_{ij}}_{n\times p}$ the design matrix}}, $\bm{B}=\bracketlg{{B}_{k}^{\tidx}}_{K\times T}$ the basis functions $\bracketlg{{\phi}_{k}(\time)}_{k=1}^{K}$ evaluated on $\mathcal{T}_{0}$, and $\bm{R}=\bracketlg{{R}_{j}(\time_{\tidx})}_{p\times T}$ the corresponding approximation error. Then Model~\eqref{eq:FDA.model} can be written as \begin{equation} \bm{Y}=\bm{X}\bm{\gamma} \bm{B} + \bm{X}\bm{R} + \bm{\theta} + \bm{E}, \label{eq:2-4} \end{equation} where $\bm{\theta}$ and $\bm{E}$ have covariance $\bm{\Sigma}_{\bm{\theta}}$ and $\bm{\Sigma}_{\bm{\epsilon}}=\sigma^{2}\bm{I}$ that are discretized $\Sigma_{\bm{\theta}}(\time,\time')$ and $\Sigma_{\bm{\epsilon}}(\time,\time')$ on $\mathcal{T}_{0}$. In what follows, we use subscript to index rows; for example, $\bm{y}_{i}, \bm{X}_i, \bm{\gamma}_j, \bm{B}_k$ are the corresponding rows of $\bm{Y}, \bm{X}, \bm{\gamma}, \bm{B}$, respectively. We use $\bm{B}^{(\tidx)}$ to denote the $\tidx^{th}$ column of $\bm{B}$, and $\bm{X}^{(j)}$ to denote the $j^{th}$ column of $\bm{X}$. All vectors are column vectors. \subsection{Estimation: Weighted functional group bridge}\label{sec:group.penalty} We propose a weighted functional group bridge approach to estimate $\bm{\gamma}$: \begin{equation}\label{eq:gamma.hat} \widehat{\bm{\gamma}} =\argmin{\bm{\gamma}} \; L(\bm{\gamma}; \lambda, \alpha, \bm{W}) = \argmin{\bm{\gamma}} \; \{f(\bm{\gamma}; \bm{W})+\lambda g(\bm{\gamma}; \alpha)\}, \end{equation} where $f(\bm{\gamma}; \bm{W})=\frac{1}{2}\sum_{i=1}^{n}\|(\bm{y}_{i}^{T}-\bm{X}_{i}^{T}\bm{\gamma} \bm{B})\bm{W}\|_{2}^{2}$ is the squared error loss with each observation weighted by a $T\times T$ matrix $\bm{W}$, and $\lambda g(\bm{\gamma}; \alpha)$ is a penalty term to encourage sparsity on $\bm{\gamma}$ and ${\beta}(t)$ with tuning parameters $\lambda \geq 0$ and $\alpha > 0$. Each coefficient function ${\beta}_j(\time)$ for $j = 1, \ldots, p$ is estimated by $\widehat{{\beta}}_j(\time)=\sum_{k = 1}^K \widehat{{\gamma}}_{jk} {\phi}_{k}(\time)$. {{We use a \textit{group bridge} penalty for $g(\bm{\gamma}; \alpha)$ to achieve sparsity in both $\bm{\gamma}$ and ${\beta}_j(t)$: \begin{equation} g(\bm{\gamma}; \alpha) =\sum_{j=1}^{p}\sum_{\tidx=1}^{T}g_{j,\tidx}(\bm{\gamma}; \alpha), \quad g_{j,\tidx}(\bm{\gamma}; \alpha) = \left\{\sum_{k: \bm{B}_k^{(m)} \neq 0} \abs{{\gamma}_{jk}}\right\}^{\alpha}, \end{equation} which decomposes $g(\bm{\gamma}; \alpha)$ into $pT$ groups. Within each group, the $L_1$ penalty on a subset of $\bm{\gamma}$ leads to sparse estimates $\widehat{\bm{\gamma}}_j$~\citep{tibshirani1996regression}. At the group level, if $g_{j,\tidx}(\bm{\gamma}; \alpha) = 0$, then $\abs{{\beta}_{j}(\time_{\tidx})}=\abs[s]{\bm{\gamma}_{j}^{T}\bm{B}^{(m)}}=0$. Hence, group-level sparsity on $g_{j,\tidx}(\bm{\gamma}; \alpha)$ leads to sparse ${\beta}_j(\time_{\tidx})$ at $\time_{\tidx}$. \cite{knight2000asymptotics} shows bridge estimators with $\alpha\in (0,1]$ combine variable selection and parameter estimation for sufficiently large $\lambda$. To achieve sparsity in both $\bm{\gamma}$ and ${\beta}_j(t)$, we propose to use $\alpha \in (0, 1)$ as it has the appealing property to select variables at the individual and group level simultaneously~\citep{huang2009group}. Note that $g(\bm{\gamma}; \alpha)$ becomes the $L_1$ penalty when $\alpha = 1$, which does not explicitly point to group-level sparsity that is critical to ensure that ${\beta}_j(t)$ is exactly zero at some $t$.}} Nevertheless, the developed algorithm in the following section is applicable for both $\alpha \in (0, 1)$ and $\alpha = 1$, and we further compare these two variants in simulations. To use a compact notation for $g_{jm}(\bm{\gamma}; \alpha)$, we indicate with $\mathbf{1}\{\bm{B}^{(\tidx)}\} = \big[\mathbf{1}\{{B}_{k}^{(\tidx)}\}\big]$ the indicator function evaluated on $\bm{B}^{(\tidx)}$, a column vector whose $k$th element $\mathbf{1}\{{B}_{k}^{(\tidx)}\}=1$ if ${B}_{k}^{(\tidx)}\neq 0$, and zero otherwise. Then \begin{equation} g_{j,\tidx}(\bm{\gamma}; \alpha) = \bracketmd[\bigg]{\sum_{k=1}^{K}\abs{{\gamma}_{jk}}\cdot \mathbf{1}\bracketlg[s]{{B}_{k}^{(\tidx)}}}^{\alpha} = \|\mathbf{1}\bracketlg[s]{\bm{B}^{(\tidx)}}\odot\bm{\gamma}_{j}\|_{1}^{\alpha}, \end{equation} where $\norm{\cdot}_{1}$ is the $L_{1}$ norm, and $\mathbf{1}\bracketlg[s]{\bm{B}^{(\tidx)}}\odot\bm{\gamma}_{j}$ is the element-wise multiplication between $\mathbf{1}\bracketlg[s]{\bm{B}^{(\tidx)}}$ and $\bm{\gamma}_{j}$. {{One needs to specify $(\lambda, \alpha, \bm{W})$ in the objective function $L(\bm{\gamma}; \lambda, \alpha, \bm{W})$. In the next sections, to ease exposition we assume these parameters are given.}} As such, in the sequel we omit $(\alpha, \lambda, \bm{W})$ in $L(\bm{\gamma};\lambda,\alpha,\bm{W}), f(\bm{\gamma};\bm{W})$ and $g(\bm{\gamma};\alpha)$ and instead use $L(\bm{\gamma}), f(\bm{\gamma})$, and $g(\bm{\gamma})$, respectively, when it does not cause confusion. {We will introduce fully data-driven methods to select $\bm{W}$ and $(\alpha, \lambda)$ in Section~\ref{s:parameter-tuning}.} \subsection{Optimization: Nested ADMM algorithm} We first recast the minimization of $L(\bm{\gamma})$ into an iterative Lasso problem as in \cite{huang2009group}. In particular, we embed $g(\bm{\gamma})$ in a carefully chosen higher dimensional space then link the solution back to $g(\bm{\gamma})$ through a particular path. Denote the expanded surface as \begin{gather} S\bracketsm{\bm{\gamma},\bm{\zeta}} =\sum_{j,\tidx}s_{j,\tidx}\bracketsm{\bm{\gamma},\bm{\zeta}}, \quad \bm{\zeta}=\{{\zeta}_{j,\tidx}\}, \\ s_{j,\tidx}(\bm{\gamma},\bm{\zeta}) =\frac{\alpha^{\alpha}}{(1-\alpha)^{\alpha-1}}{\zeta}_{j,\tidx}^{1-\frac{1}{\alpha}}\|\mathbf{1}\bracketlg[s]{\bm{B}^{(\tidx)}}\odot\bm{\gamma}_{j}\|_{1} +\alpha^{\alpha}(1-\alpha)^{1-\alpha}{\zeta}_{j,\tidx}. \end{gather} The original non-convex problem in Equation~\eqref{eq:gamma.hat} can be solved by finding the minimizer for \begin{gather} \argmin{\bm{\gamma},\bm{\zeta}}\ L_{S}(\bm{\gamma},\bm{\zeta}) \quad \text{subject to} \quad \bm{\zeta}=\bm{\zeta}(\bm{\gamma}) \text{ and } \bm{\zeta} > 0, \label{eq:modified-objective}\\ \text{where } L_{S}(\bm{\gamma},\bm{\zeta})=f(\bm{\gamma})+S(\bm{\gamma},\bm{\zeta})\label{eq:modobj} , \text{ and } {\zeta}_{j,\tidx}(\bm{\gamma}) =\bracketsm[\Big]{\frac{1-\alpha}{\alpha}}^{\alpha}\|\mathbf{1}\bracketlg[s]{\bm{B}^{(\tidx)}}\odot\bm{\gamma}_{j}\|_{1}^{\alpha}. \end{gather} We carry out the optimization by iteratively updating $\bm{\zeta}$ with fixed $\bm{\gamma}=\bm{\gamma}^{\mathrm{old}}$ through the definition $\bm{\zeta} = \bm{\zeta}(\bm{\gamma})$, and updating $\bm{\gamma}$ by solving a Lasso problem with fixed $\bm{\zeta}=\bm{\zeta}^{\mathrm{new}}$. We propose to solve the iterative Lasso problem using nested alternating direction method of multipliers, or ADMM~\citep{boyd2011distributed}. Algorithm \ref{alg:1} details the nested ADMM algorithm, in which we use common notations for matrices. For any matrix $\bm{A}$, $\bm{A}^{+}$ is the positive part, and $\bm{A}^{-}$ is the negative part. The operator $\diag(\cdot)$ extracts the diagonal elements of a square matrix into a vector, and expands a vector to a diagonal square. The operator $\oslash$ between two matrices defines element-wise division. {We use the ridge regression estimate $\widehat{\bm{\gamma}}_{\rm ridge}$ that minimizes \eqref{eq:gamma.hat} with $g(\bm{\gamma}; \alpha) = \sum_j \| \bm{\gamma}_j \|_2^2$ and tuning parameter $\lambda_{\rm ridge}$ as a closed-form ``warm-start".} Compared to LARS~\citep{efron2004least} adopted by \cite{huang2009group}, warm started ADMM can significantly improve the performance: If initialized near the solution, ADMM converges faster to modest accuracy within a few steps~\citep{boyd2011distributed, majzoobi2018analysis}. To fully take advantage of this property, we use few ADMM steps within each iteration without checking or waiting till full convergence, leading to ``early stopping''. The solutions at each iteration are used as warm-starts for the next iteration, further speeding up the convergence. {{Although the partial derivative $\partial g(\bm{\gamma})/\partial {\gamma}_{jk}$ near zero diverges, zero does not tend to be an absorbing state with an increased augmented Lagrangian parameter $\rho$ in Algorithm \ref{alg:1}. In addition, the adopted dense initialization via ridge regression and early stopping in ADMM help prevent the coefficients from entering zeros at early stage,}} leaving enough iterations for the coefficients to prioritize fitting before becoming sparse. {{In numerical experiments not reported here, we have found that the proposed algorithm outputs similar estimates with radically different initial values, indicating robustness. Nevertheless, we recommend to use the ridge regression estimate for faster convergence.}} {{We use the following default settings in our numerical experiments, unless otherwise stated. We use 5-fold cross validation to select $\lambda_{\rm ridge}$ in ridge regression. The number of iterations $S_{1}$ is 20, and the number of ADMM steps per iteration is $S_{2} = 50$. }}We increase $\rho$ exponentially by letting $\rho = e^{4s / S_{2} - 1}$ where $s$ is current ADMM step. \begin{algorithm}[ht] \caption{Nested ADMM solver for the case $\alpha\in(0,1)$}\label{alg:1} \begin{algorithmic}[1] \Procedure{}{$\bm{X},\bm{Y},\bm{B},\lambda, \alpha, \bm{W}, S_{1}, S_{2}$}\Comment{Inputs} \State Initialize $\bm{\gamma}\leftarrow \bm{\gamma}^{(0)}\leftarrow \hat{\bm{\gamma}}_{\rm ridge}$, $\bm{E}\leftarrow \bm{Y}-\bm{X}\bm{\gamma} \bm{B}$; \State SVD decomposition: $\bm{X} =\bm{U}_{\bm{X}}\bm{D}_{\bm{X}}\bm{V}_{\bm{X}}^{T}$, $\bm{B}\bm{W} =\bm{U}_{\bm{B}}\bm{D}_{\bm{B}}\bm{V}_{\bm{B}}^{T}$; \State Assign $\bm{V} = \bm{V}_{\bm{X}}^{T}$, $\bm{U} = \bm{U}_{\bm{B}}$, $\bm{Z} = \diag(\bm{D}_{\bm{X}}^{2})\diag(\bm{D}_{\bm{B}}^{2})^{T}+\rho\mathbf{1}_{p}\mathbf{1}_{K}^{T}$ ; \For{$v$ in $1,2,\dots,S_{1}$} \Comment{Macro-loop: iterative Lasso} \State Calculate $\bm{D}^{(v)} = \{{D}_{jk}^{(v)}\},$ where ${D}_{jk}^{(v)} = \alpha^{\alpha}(1-\alpha)^{1-\alpha}{\zeta}_{j,\tidx}^{1-\frac{1}{\alpha}}(\bm{\gamma}^{(v-1)})\cdot\mathbf{1}\bracketlg[s]{{B}_{k}^{(\tidx)}}$; \State Initialize $\bm{\eta}^{(0)}=\bm{\gamma}^{(v-1)}$, $\bm{\xi}^{(0)}=\bm{\gamma}^{(v-1)},$ $\bm{\psi}^{(0)} = \bm{\xi}^{(0)}-\bm{\eta}^{(0)} = \bm{0}$; \For{$s$ in $1,2,\dots,S_{2}$} \Comment{ADMM loop, fixed steps} \State $\bm{\phi}\leftarrow \bm{V}\bm{X}^{T}\bm{Y}\bm{W}(\bm{B}\bm{W})^{T}\bm{U}-\bm{\psi}^{(s-1)}+\rho \bm{V}\bm{\eta}^{(s-1)}\bm{U}$ \State $\bm{\xi}^{(s)}\leftarrow \bm{V}^{T}\left(\bm{\phi}\oslash \bm{Z}\right)\bm{U}^{T}$; \State $\bm{\eta}^{(s)}\leftarrow\bracketlg[\big]{\bm{\xi}^{(s)}+\frac{1}{\rho}\bm{V}^{T}\bm{\psi}^{(s-1)}\bm{U}^{T}-\frac{\lambda}{\rho}\bm{D}^{(v)}}^{+}-\bracketlg[\big]{\bm{\xi}^{(s)}+\frac{1}{\rho}\bm{V}^{T}\bm{\psi}^{(s-1)}\bm{U}^{T}+\frac{\lambda}{\rho}\bm{D}^{(v)}}^{-}$; \State $\bm{\psi}^{(s)} \leftarrow\bm{\psi}^{(s-1)}+\rho \bm{V}\bracketlg[s]{\bm{\xi}^{(s)}-\bm{\eta}^{(s)}}\bm{U}$; \EndFor \State Assign $\bm{\gamma}\leftarrow \bm{\gamma}^{(v)}\leftarrow \bm{\eta}^{(S_{2})}$; \State Recall $\widehat{\bm{Y}}=\bm{X}\bm{\gamma}^{(v)}\bm{B}$, calculate $\widehat{\bm{E}}=\bm{Y}-\widehat{\bm{Y}}$; \If{ $\|\widehat{\bm{E}} \bm{W}\|_{2}$ is stable }{ Break the loop} \Comment{Exit} \EndIf \EndFor \State \textbf{Return} $\bm{\gamma}$; \EndProcedure \end{algorithmic} \end{algorithm} Not that by setting $S_{2}=1$ and forcing ${D}^{(v)}_{jk}=1$ at each iteration, Algorithm~\ref{alg:1} also solves the case when $\alpha=1$. \subsection{Variance Estimation} \label{s:variance} Algorithm \ref{alg:1} solves an augmented Lagrangian problem $L^\text{aug}$: \begin{equation} L^\text{aug}(\bm{\xi}, \bm{\zeta}, \bm{\psi}, \bm{\eta}; \bm{W}, \lambda, \alpha, \rho) = L_S(\bm{\xi}, \bm{\zeta}) + \bracketlg{ \vec{(\bm{\psi})}^{T} \vec{\bracketsm{\bm{V}\bm{\xi} \bm{U} - \bm{V}\bm{\eta} \bm{U}}} } + \frac{\rho}{2}\norm{\bm{V}(\bm{\xi}-\bm{\eta})\bm{U}}_{2}^{2}, \end{equation} where $\vec(\bm{A})$ vectorizes $\bm{A}$ by stacking columns of $\bm{A}$. The dual feasibility in the ADMM optimality condition yields \begin{gather} \{\bm{V}\bm{\xi}^{(s)} \bm{U}\} \odot \bm{Z} = \bm{V}\bm{X}^{T}\bm{Y}\bm{W}\bm{W}^{T}\bm{B}^{T}\bm{U} - \bm{\psi}^{(s-1)} +\rho \bm{V}\bm{\eta}^{(s-1)}\bm{U} \label{eq:dual-1}\\ \mathbf{0} = \bracketmd[\Big]{-\frac{\lambda}{\rho} D(\bm{\zeta})\text{sign}\bracketlg[\big]{\bm{\xi}^{(s)}} + \frac{1}{\rho}\bm{V}^{T}\bm{\psi}^{(s-1)}\bm{U}^{T} - \bm{\eta}^{(s)}} \odot \text{sign}\bracketlg[\big]{\bm{\xi}^{(s)}}. \label{eq:dual-2} \end{gather} When Algorithm \ref{alg:1} converges, $\rho (\bm{\eta}^{(s)}-\bm{\eta}^{(s-1)})\rightarrow \mathbf{0}$ and $\bm{\xi}^{(s)} \rightarrow \widehat{\bm{\gamma}}$. Hence, for $(j,k)$ such that $\widehat{{\gamma}}_{jk}\neq 0$, the preceding optimality conditions in \eqref{eq:dual-1} and \eqref{eq:dual-2} yield \begin{equation} {\bm{X}^{(j)}}^T \bm{X}\widehat{\bm{\gamma}} \bm{B}\bm{W}\bm{W}^T\bm{B}_{k} + \lambda {D}_{jk}(\widehat{\bm{\zeta}})\widehat{{\gamma}}_{jk} = {\bm{X}^{(j)}}^T \bm{X}\bm{\gamma} \bm{B}\bm{W}\bm{W}^T\bm{B}_{k} + {\bm{X}^{(j)}}^T \bm{E}\bm{W}\bm{W}^T\bm{B}_{k}. \label{eq:optimality} \end{equation} Denote $\bm{P}(j,k)=\vec\{\bm{X}^T\bm{X}^{(j)}\bm{B}_{k}^T\bm{W}\bm{W}^T\bm{B}^T+\lambda {D}_{jk} \bm{J}(j,k)\}$, where $\bm{J}(j,k)$ is sparse matrix with only its $(j,k)$ element being $1$, and let $\bm{Q}(j,k)=\bm{X}^{(j)}\bm{B}_{k}^T\bm{W}\bm{W}^T$. Then $(\ref{eq:optimality})$ can be written as \begin{equation} \vec\bracketlg{\bm{P}(j,k)}^T\vec(\widehat{\bm{\gamma}}) = \vec\bracketlg{\bm{Q}(j,k)}^T \vec(\bm{X}\bm{\gamma} \bm{B}+\bm{Z}\bm{\theta}+\bm{E}), \label{eq:gamma-implicit} \end{equation} for $(j,k)$ such that $\widehat{{\gamma}}_{jk}\neq 0$. Letting $\vec_{\lambda}(\widehat{\bm{\gamma}})$ be the sub-vector of $\vec(\widehat{\bm{\gamma}})$ on its support, that is, all elements in $\vec_{\lambda}(\widehat{\bm{\gamma}})$ are non-zeros, and likewise $\bm{P}_{\lambda}(j,k)$ be $\bm{P}(j,k)$ on its support, then we have $\vec\bracketlg{\bm{P}(j,k)}^T\vec(\widehat{\bm{\gamma}}) = \vec_{\lambda}\bracketlg{\bm{P}(j,k)}^T\vec_{\lambda}(\widehat{\bm{\gamma}})$. Bind $\vec_{\lambda}\bracketlg{\bm{P}(j,k)}$ by column for all $(j,k)$ such that $\widehat{{\gamma}}_{jk}\neq 0$, and denote it as $\bm{P}_{\lambda}$. It is easy to show that $\bm{P}_{\lambda}$ is a square matrix and further $ \bm{P}_{\lambda}\vec_{\lambda}(\widehat{\bm{\gamma}}) = \bm{Q} \vec(\bm{X}\bm{\gamma} \bm{B}+\bm{Z}\bm{\theta}+\bm{E}),$ where $\bm{Q}$ is also a square matrix column-binded by $\vec\bracketlg{\bm{Q}(j,k)}$. Consequently, the covariance of $\widehat{\bm{\gamma}}$ is given by \begin{equation} \text{Cov}\bracketlg{\vec_{\lambda}(\widehat{\bm{\gamma}})}=\bm{P}_{\lambda}^{-1}\bm{Q}\text{Cov}\bracketlg{\vec(\bm{Z}\bm{\theta}+\bm{E})}\bm{Q}^T\bracketsm{\bm{P}_{\lambda}^T}^{-1}. \label{eq:covariance} \end{equation} \subsection{Choice of weights and parameter tuning} \label{s:parameter-tuning} We propose to use $\bm{W} \propto\bm{\Sigma}^{-1/2}$ to accounts for heterogeneity in the functional response, where $\bm{\Sigma}=\bm{\Sigma}_{\bm{\theta}} + \sigma^{2}\bm{I}$ is the covariance matrix of ${y}_{i}^{T}-\bm{X}_{i}^{T}{\beta}$. When $\bm{\Sigma}_{\bm{\theta}}$ and $\sigma^{2}$ are unknown, we substitute using their estimates $\widehat{\bm{\Sigma}}_{\bm{\theta}}$ and $\widehat{\sigma}^{2}$ to derive $\widehat{\bm{\Sigma}}$ and subsequently $\bm{W}$. We propose to employ local linear regression~\citep{fan1993local, zhu2014spatially} to estimate $\bm{\Sigma}$, assuming the existence of the second-order derivative of ${\theta}_{i}(\time)$ within each phase $\mathcal{T}^{\text{pa}}$. Denote $\Delta_{\tidx,b}(\time)=(\time_{\tidx} - \time) / b$ and ${\theta}'_{i,b}(\time)=b \cdot d{\theta}_{i}/d\time(\time)$, and choose a kernel function $K_{b}(\time)$ with the bandwidth parameter $b$ selected by minimizing the generalized cross-validation score~\citep{zhu2014spatially}. For each $\time\in\mathcal{T}^{\text{pa}}$, we estimate ${\theta}_{i}(\time)$ using a weighted least squares procedure \citep{fan1993local}: \begin{align} \bracketlg[\Big]{\widehat{{\theta}}_{i}(\time),\widehat{{\theta}'}_{i}(\time) }^T = \argmin{ {\theta}_{i}(\time), {\theta}'_{i}(\time) } \sum_{ \tidx: \time_{\tidx}\in \mathcal{T}_{0}^{\text{pa}} } & \Big[ {y}_{i}(t_{\tidx}) - \sum_{j=1}^{p} x_{ij} \widehat{{\beta}}_{j}^{ols}(\time_{\tidx}) \\ &\quad - \bracketlg[\big]{{\theta}_{i}(\time) + {\theta}'_{i}(\time)\Delta_{\tidx,b}(\time)} \Big]^{2} K_{b}(\time_{\tidx} - \time), \end{align} where $\widehat{{\beta}}_{j}^{ols}(\time_{\tidx})$ is ordinary lease square estimator of the $j^{th}$ coefficient at time $\time_{\tidx}$. We then calculate $\widehat{\bm{\Sigma}}_{\bm{\theta}}$ from the sample covariance of $\bracketlg[s]{\widehat{{\theta}}_{i}(\time_{\tidx})}_{i,\tidx}$, and $\widehat{\sigma}^2$ from the residuals ${y}_{i}(t_{\tidx}) - \sum_{j=1}^{p} x_{ij} \widehat{{\beta}}_{j}^{ols}(\time_{\tidx})- \widehat{{\theta}}_{i}(\time_{\tidx})$. {{As a passing comment, one may alternatively use $\bm{W} = \bm{I}$; this may lead to efficiency loss unless the functional dependence is homogeneous or approximately so, a special case of Model~\eqref{eq:FDA.model} without random effects. The developed methods and theory are applicable for this simplified model with such a choice of $\bm{W}$.}} We next move on to the tuning of $\alpha$ and $\lambda$ via an adjusted extended Bayesian information criterion (EBIC). We choose an equally spaced sequence of knots for B-splines. For given $K$, the EBIC proposed by \cite{chen2008extended} is \begin{equation} EBIC_{\nu} = \frac{\norm{(\bm{Y}-\bm{X}\widehat{\bm{\beta}})\bm{W}}_2^2}{n\sigma^{2}} + T\log{(\sigma^{2})} + df \frac{\log{n}}{n} + \nu df \frac{\log{pK}}{n}, \label{eq:ebic} \end{equation} where $\widehat{\bm{\beta}}$ is the fitted coefficients of a given model, $df$ the number of non-zero elements in $\bm{\gamma}$, $\nu \in [0, 1]$ a constant, and $\sigma^{2}$ an unknown parameter analogue to the error variance in a standard regression model. We use $\nu=\max\bracketlg[\big]{1-\frac{\log(n)}{2\log(pK)}, \frac{1}{2}}$ based on Theorem 1 and discussions in \cite{chen2008extended}. \cite{huang2010variable} and \cite{wang2015functional} substituted $n\sigma^{2}$ with residual sum of squares based on $\widehat{\bm{\beta}}$. Since a bridge estimator is not unbiased due to its shrinkage to zero, we instead propose to estimate $\sigma^{2}$ by the weighted residual sum of squares based on the generalized least-square estimator $\widehat{\bm{\beta}}_{GLS}$, which is unbiased although lacks sparsity. Letting $\widehat{\bm{\beta}}_{GLS} = (\bm{X}^{T}\bm{X})^{-1}\bm{X}^{T}\bm{Y}\bm{W}\bm{W}^{T}\bm{B}^{T}(\bm{B}\bm{W}\bm{W}^{T}\bm{B}^{T})^{-1}$ and $\widehat{{\sigma}}^{2}_{GLS} = \norm{(\bm{Y}-\bm{X}\widehat{\bm{\beta}}_{GLS})\bm{W}}_{2}^{2}/(nT),$ then the proposed adjusted EBIC is \begin{equation} EBIC_{\nu} = T \frac{\norm{(\bm{Y}-\bm{X}\widehat{\bm{\beta}})\bm{W}}_2^2}{\norm{(\bm{Y}-\bm{X}\widehat{\bm{\beta}}_{GLS})\bm{W}}_{2}^{2}} + df \frac{\log{n}}{n} + \nu df \frac{\log{pK}}{n}, \label{eq:adjust.ebic} \end{equation} up to an additive constant. In the simulation, we observe that our proposed adjusted EBIC select parameters that are close to the oracle values; see Section \ref{s:simulation} for more details. \section{Asymptotic Properties}\label{s:asymptotic-properties} In this section, we study asymptotic properties of the proposed estimators. For a function $f(t): [0, 1] \rightarrow \mathbb{R}$, let $\|f\|_r$ be the $L_r$ norm and $\|f\|_{\infty} = \sup_{t \in [0, 1]} |f(t)|$. Denote by $\mathcal{C}^{r}[0,1]$ the H\"older space on $[0,1]$ with order $r$, a set of functions $f(\time)$ such that for some $L_f > 0$, $|f^{(r_0)}(x) - f^{(r_0)}(y)| \leq L_f \|x - y\|^{r - r_0}$ for all $x, y \in [0, 1]$, where $r_0$ is the largest integer strictly smaller than $r$. Let $S(f)=\{\time\in\mathcal{T}: f(\time)=0\}$ map $f(t)$ to its zero set. Denote by $\delta_{\min}(\bm{A})$ and $\delta_{\max}(\bm{A})$ the minimum and maximum eigenvalues for any given matrix $\bm{A}$. For two sequences $a_{n, T}$ and $b_{n, T}$, $a_{n, T} \lesssim b_{n, T}$ means $a_{n, T} \leq C b_{n, T}$ for some universal constant $C > 0$. We write $a_{n, T} \asymp b_{n, T}$ if $a_{n, T} \lesssim b_{n, T}$ and $a_{n, T} \gtrsim b_{n, T}$. Asymptotics in this section are interpreted when $n$ and $T$ go to infinity. We assume the following regularity conditions. \begin{assumption} \label{assumption:holder-cont} The underlying ${\beta}_{j}(\time) \in \mathcal{C}^{r}[0,1]$, for $j=1,2,\dots,p$ and $r\geq 2$. \end{assumption} \begin{assumption} \label{assumption:integral} The integral $\underset{t\in S({\beta}_{j})^c}{\int} \abs[s]{ \frac{1}{{\beta}_j(t)} }^{2(1 - \alpha)} d\time$ exists and is finite, for all $j$. \end{assumption} \begin{assumption} $\bracketlg{{\epsilon}_{i}(\time)}_{i=1}^{n}$ and $\bracketlg{{\theta}_{i}(\time)}_{i=1}^{n}$ are independent across $i$ and sub-Gaussian.\label{assumption:iid-err} \end{assumption} \begin{assumption} The design matrix satisfies that for some constants $C_1, C_2 > 0$, $C_1\leq\delta_{\min}(\bm{X}^T \bm{X}/n)$ and $\delta_{\max}(\bm{X}^T \bm{X}/n) \leq C_2$, and the weight matrix is chosen such that $C_3 \leq \delta_{\min}(\bm{W} \bm{W}^T) \leq \delta_{\max}(\bm{W}\bm{W}^T) \leq C_4$ for some constants $C_3, C_4 > 0$, for all sufficiently large $n$ and $T$.\label{assumption:x-reg} \end{assumption} \begin{assumption} $\underset{\tidx}{\max}\bracketsm{\time_{\tidx+1}-\time_{\tidx}}=O(T^{-1})$. \label{assumption:equal-spaced} \end{assumption} \begin{assumption} $C_{5} K^{-1} \leq \time_{\tidx_{k+q}}-\time_{\tidx_{k}} \leq C_{6} K^{-1}$ for some constants $C_{5}, C_{6} > 0$, where $K<T$. \label{assumption:k} \end{assumption} {{Assumptions~\ref{assumption:holder-cont}, \ref{assumption:iid-err}, \ref{assumption:equal-spaced}, and \ref{assumption:k}, as well as the design matrix condition in Assumption \ref{assumption:x-reg}, are common in high-dimensional regression; see, for example, \cite{fan2000two, cai2011optimal, wang2015functional}. Assumptions \ref{assumption:equal-spaced} and \ref{assumption:k} are concerned with the spacing of time points and B-spline knots, respectively, and trivially hold when they are equally spaced.}} Assumption \ref{assumption:integral} is in the same vein of Conditions (B') and (C') in~\cite{Fan2004a} to ensure that the group bridge penalty does not dominate the least square error on its support, and implies that ${\beta}_{j}(\time)$ deviates from zero fast enough so that its support and zero set can be well distinguished. Unlike \cite{Fan2004a,huang2009group}, Assumption \ref{assumption:integral} disentangles the penalty and the regression function, leading to a simpler and more interpretable formulation to regularize regression coefficients. We achieve such simplicity by relying on a carefully modified B-spline approximation that will be detailed in Lemma~\ref{lem:appendix:approximation}. This assumption also suggests a lower bound of $\alpha$ for ${\beta}_{j}(\time)$ leaving zeros at polynomial speed. If ${\beta}_{j}(\time_{0})=0$ for some $\time_{0}$ and ${\beta}_{j}(\time)$ satisfies $\abs[s]{{\beta}_{j}(\time)} \gtrsim |\time-\time_{0}|^{b}$ as $t$ approaches $\time_{0}$ for some positive constant $b$, then choosing $\alpha> 1- 1/(2b)$ is required to comply with this assumption. {{Assumption~\ref{assumption:x-reg} holds for the proposed data-driven $\bm{W}$ that satisfies $\bm{W}\bm{W}^T = \widehat{\bm{\Sigma}}^{-1} $ if the eigenvalues of $\widehat{\bm{\Sigma}}$ are bounded from above and below, a condition that is often satisfied following the rich literature of covariance estimation in functional data. For example, letting $C_{\bm{\theta}}$ be a constant such that $\delta_{\max}(\bm{\Sigma}_{\bm{\theta}}) \leq C_{\bm{\theta}}$, Theorem 2 of \cite{zhu2014spatially} proves the consistency of $\widehat{\bm{\Sigma}}^{-1}$, and particularly indicates $\lvert \delta_{\max}(\widehat{\bm{\Sigma}}_{\bm{\theta}}) - \delta_{\max}({\bm{\Sigma}}_{\bm{\theta}})\rvert \lesssim C_{\bm{\theta}}/2$ and $\lvert \widehat{\sigma}^{2} - {\sigma}^{2}\rvert \lesssim {\sigma}^{2}/2$, yielding $\lvert \delta_{\max}(\widehat{\bm{\Sigma}}) - \delta_{\max}({\bm{\Sigma}}) \rvert \lesssim (C_{\bm{\theta}}+{\sigma}^{2})/2$ and thus $\delta_{\max}(\widehat{\bm{\Sigma}}) \lesssim 3(C_{\bm{\theta}}+{\sigma}^{2})/2$. Moreover, the semi-positiveness of $\widehat{\bm{\Sigma}}_{\bm{\theta}}$ ensures that $\delta_{\min}(\widehat{\bm{\Sigma}})\geq \widehat{\sigma}^{2} \gtrsim {\sigma}^{2}/2$.}} It is well known that if ${\beta}_{j}(\time) \in \mathcal{C}^{r}[0,1]$ and there are no overlapping spline knots for $t_{m_{k}}$ for $q\leq k\leq K$, then there exists a B-spline approximation such that $L_{\infty}$ approximation error is upper bounded by $K^{-r}$ up to a constant; for example, see~\cite{schumaker2007spline}. However, these accurate B-spline approximations do not necessarily capture the sparsity of the true function. In Lemma~\ref{lem:appendix:approximation}, we propose a sparse modification of such B-splines so that the new approximation preserves the sparsity structure with the same approximation accuracy. \begin{lemma} \label{lem:appendix:approximation}Under Assumptions~\ref{assumption:holder-cont} and \ref{assumption:k}, let $\widetilde{{\beta}}^{*}_{j}(\time)=\sum_{k=1}^{K}\widetilde{\bm{\gamma}}^{*}_{jk}{\phi}_{k}(\time)$ be the B-spline approximation in \cite{schumaker2007spline} such that $\big\|\widetilde{{\beta}}^{*}_{j}(\time) - {\beta}_{j}(\time)\big\|_{\infty} \leq C^{*}_{{\beta}_{j}}K^{-r}$ for a constant $C_{{\beta}_{j}}^{*}$. Then there exists a sparse modification $\widetilde{{\beta}}_{j}(\time):=\sum_{k=1}^{K}\widetilde{{\gamma}}_{jk}{\phi}_{k}(\time)$ and a constant $C_{{\beta}_{j}}$ such that $S({\beta}_{j}) \subseteq S(\widetilde{{\beta}}_{j})$, and $\big\|{\beta}_{j}(\time)-\widetilde{{\beta}}_{j}(\time)\big\|_{\infty} \leq C_{{\beta}_{j}} K^{-r}$. Also for any $\time\notin S(\widetilde{{\beta}}_{j})$, $\sum_{k:{\phi}_{k}(\time) > 0} \abs[s]{\widetilde{{\gamma}}_{jk}}\geq \frac{C_{{\beta}_{j}}^{*}}{qC_{{\beta}_{j}} + C_{{\beta}_{j}}^{*}}\abs[s]{{\beta}_{j}(\time)}$. \end{lemma} We call the modified B-spline coefficients $\widetilde{\bm{\gamma}} = \{\widetilde{{\gamma}}_{jk}\}_{p \times K}$ pseudo true values of $\bm{\gamma}$. The triangle inequality gives \begin{align} \big\|{\beta}_{j}(\time)-\widehat{{\beta}}_{j}(\time)\big\|_{\infty} & \leq \big\|{\beta}_{j}(\time)-\widetilde{{\beta}}_{j}(\time)\big\|_{\infty} + \big\|\widetilde{{\beta}}_{j}(\time)-\widehat{{\beta}}_{j}(\time)\big\|_{\infty} \\ & \leq C_{{\beta}_{j}} K^{-r} + \big\|\widehat{\bm{\gamma}}_{j}-\widetilde{\bm{\gamma}}_{j}\big\|_{\infty}\sum_{k=1}^{K}\big\|{\phi}_{k}(\time)\big\|_{1}, \end{align} where $\sum_{k=1}^{K}\norm{{\phi}_{k}(\time)}_{1}=1.$ Therefore, convergence rates of $\widehat{{\beta}}(\time)$ boils down to convergence rates of $\widehat{\bm{\gamma}}$ relative to the pseudo true $\widetilde{\bm{\gamma}}$ and the approximation error $C_{{\beta}_{j}} K^{-r}$ of using B-splines. The following Theorem~\ref{thm:5} and Theorem~\ref{thm:6} establish convergence rates of $\widehat{\bm{\gamma}}$ and $\widehat{{\beta}}_j$, respectively. To ease exposition, we relate $K$ and $T$ to $n$ by writing $K=n^{\frac{\kappa}{2r}}$ and $T=n^{\frac{\tau}{2r}}$ where $0<\kappa \leq\tau$. Here $n^{\frac{\kappa}{2r}}$ and $n^{\frac{\tau}{2r}}$ represent the asymptotic rates of $K$ and $T$, and any multiplicative constants do not change our results. To state the two theorems in their most general forms, we do not yet assume a specific order of either $\kappa$ or $\tau$. \begin{theorem}[Convergence rate of $\widehat{\bm{\gamma}}$] \label{thm:5} Let $c_{\kappa}=\min(1, \kappa)$ and suppose Assumptions~\ref{assumption:holder-cont}--\ref{assumption:k} hold. If $\frac{\log(\lambda)}{\log(n)} \leq 1 - \frac{c_{\kappa}}{2} + \frac{\tau}{4r} - \frac{\kappa}{4r}$, then we have as $n\rightarrow\infty$ \begin{equation} \norm{\widehat{\bm{\gamma}}-\widetilde{\bm{\gamma}}}_{\infty}\leq \norm{\widehat{\bm{\gamma}}-\widetilde{\bm{\gamma}}}_{2}=O_{p}\bracketsm[\big]{ n^{\frac{\kappa}{4r} - \frac{c_{\kappa}}{2}} }. \label{eq:3-7} \end{equation} \end{theorem} \begin{theorem}[Convergence rate of $\widehat{{\beta}}(\time)$]\label{thm:6} Under the same assumptions of Theorem~\ref{thm:5}, as $n\rightarrow\infty$, \begin{gather} \big\|\widehat{{\beta}}_{j}(\time)-{\beta}_{j}(\time)\big\|_{\infty} =O_{p} \bracketsm[\big]{n^{\frac{\kappa}{4r} - \frac{c_{\kappa}}{2}}}, \label{eq:6-2}\\ \big\|\widehat{{\beta}}_{j}(\time)-{\beta}_{j}(\time)\big\|_{2} =O_{p} \bracketsm[\big]{n^{ - \frac{c_{\kappa}}{2}}}. \label{eq:6-1} \end{gather} \end{theorem} Theorem~\ref{thm:6} establishes convergence rates of $\widehat{{\beta}}(\time)$ under both $L_{2}$ and $L_{\infty}$ norms. We remark that there is a phase transition at $\tau = 1$ in \eqref{eq:6-2}. When $\tau < 1$, because $\kappa < \tau$, we have $c_{\kappa}=\kappa$, and the optimal $L_{\infty}$ rate is attained at the largest $\kappa$, i.e., $\kappa = \tau$, which gives the rate $O_p(n^{(1-2r)\frac{\tau}{4r}})$. In this case, the rate improves as $\tau$ increases. When $\tau > 1$, the optimal $L_{\infty}$ rate is $O_{p}(n^{(1 - 2r)\frac{1}{4r}})$, which is achieved at $\kappa = 1$, and increasing $\tau$ does not improve the rate. The same phase transition also applies to the $L_2$ rate in \eqref{eq:6-1}, which coincides with the observation made in~\cite{cai2011optimal}. In addition, our rate calculation implies that with $\kappa = \min(\tau, 1)$, the $L_2$ rate in \eqref{eq:6-1} becomes $O_p(n^{- \min(\tau, 1) / 2})$, i.e., $O_p(n^{-1/2} + T^{-r})$, which is minimax optimal~\citep{cai2011optimal}. The rate under the $L_\infty$ norm in \eqref{eq:6-2} indicates that $\widehat{{\beta}}(\time)$ converges to ${\beta}(\time)$ at each $t$ for $\kappa < 2r$. This is particularly useful in detecting sparse regions as pointwise convergence suggests low false positive rates and low false negative rates in finding the support of ${\beta}_{j}(\time)$. In particular, we consider $\delta$-sparsity denoted by $S_{\delta}(h) = \{\time \in \mathcal{T}: |h(\time)| \leq \delta\}$ for $\delta > 0$. Then Equation~\eqref{eq:6-2} suggests that for arbitrary $\delta > 0$, as $n\rightarrow\infty$, \begin{equation} P\{S(\widehat{{\beta}}_j) \subseteq S_{\delta}({\beta}_j)\} \rightarrow 1,\quad P\{S({{\beta}}_j) \subseteq S_{\delta}(\widehat{{\beta}}_j)\} \rightarrow 1 .\label{eq:TPR} \end{equation} {{In addition, the following theorem establishes one side of strict sparsity for the proposed method, that is, the support of $\widehat{{\beta}}(\time)$ is a subset of ${\beta}_{j}(\time)$ with probability approaching to $1$. This leads to low {false positive rates} under strict sparsity. It is an interesting future direction to study under what conditions the other side of strict sparsity also holds.}} \begin{theorem} \label{thm:9} Under the same conditions in Theorem~\ref{thm:5} and $\frac{\log(\lambda)}{\log(n)} > 1 + \frac{c_{\kappa}(\alpha-2)}{2} + \frac{\tau}{2r} - \frac{\kappa\alpha}{4r}$, as $n\rightarrow\infty$, there holds $P\{S({\beta}_j) \subseteq S(\widehat{{\beta}}_j)\} \rightarrow 1.$ \end{theorem} While we have focused on $\alpha <1$, a close inspection into the proofs of Theorems~\ref{thm:5} and \ref{thm:6} suggests that they also hold for $\alpha = 1$ (note that Assumption~\ref{assumption:integral} is not needed in this case). {{As discussed in Section~\ref{sec:group.penalty}, choosing $\alpha < 1$ induces exactly zero estimates of functional coefficients. Theorem \ref{thm:9} reassuringly shows that the recovered exactly zero regions tend to contain the zero regions of the true regression functions at least asymptotically. The proof of Theorem \ref{thm:9} crucially relies on the choice of $\alpha < 1$; see the Appendix for details.}} \section{Simulations} \label{s:simulation} We conduct simulations to compare finite sample performances of the proposed approach with competing methods in terms of function estimation and sparse region detection. We also assess the the proposed adjusted EBIC method for parameter tuning. We generate data according to Model~\eqref{eq:FDA.model}. We consider three coefficients to represent different sparsity levels, displayed in Figure \ref{fig:truth}: ${\beta}_{1}(\time)=0$ for global sparsity, ${\beta}_{2}(\time)=\sin(\pi\time)$ for no sparsity (a dense coefficient), and ${\beta}_{3}(\time)$ for local sparsity that is defined as \begin{equation} {\beta}_{3}(t)=\sin\bracketsm{\frac{5\pi}{2}\time-\frac{\pi}{2}}\mathbf{1}_{[0.2, 0.4)}(t) + \mathbf{1}_{[0.4,0.6)}(t) + \sin\bracketsm{\frac{5\pi}{2}\time-\pi}\mathbf{1}_{[0.6,0.8)}(t). \end{equation} Among the three coefficient functions ${\beta}_3(t)$ is the most interesting one as it is locally sparse that pertains to the motivation of this paper; ${\beta}_1(t)$ and ${\beta}_2(t)$ are not of particular interest, but they allow us to study the performance of the proposed method when there are other coefficient functions with various sparsity levels. The design matrix $\bm{X}$ is generated from the standard normal distribution $N(0,1)$. To simulate different phases of experiments, the random effects ${\theta}_{i}(\time)$ are generated from a $AR(1)\times \sigma(\time)$ process, where $\sigma(\time)$ is a non-decreasing step function visualized in Figure~\ref{fig:truth} and $AR(1)$ is an order one autoregressive process with correlation $0.9$. The errors ${\epsilon}_i(\time_\tidx) \sim N(0,1)$ are independent across observations and time points. We use $T = 100$ as the time resolution to generate equally spaced $t_m$. We consider two sample sizes: $n = 100$ (small sample size) and $n = 1000$ (large sample size). We run 100 simulations for each sample size. \begin{figure} \centerline{ \includegraphics[width=0.95\linewidth]{simulation/generation.pdf}} \caption{Three coefficient functions (left) and step function $\sigma(\time)$ (right). ${\beta}_{1}(t)$ is globally sparse; ${\beta}_{2}(t)$ is dense; ${\beta}_{3}(t)$ is locally sparse. For ${\beta}_{3}(t)$, its phase I has the smallest errors and is half sparse and half dense. Phase II is dense with intermediate errors, and phase III is sparse with the largest errors.} \label{fig:truth} \end{figure} In addition to the proposed weighted function group bridge approach, we include its two variants: homogeneous weight ($\bm{W}=\bm{I}$) and $\alpha=1$. Other competing methods include Group Lasso (gLasso) proposed by \cite{barber2017} and Group MCP (gMCP) by \cite{chen2016variable}. {{We also implement two-step function-on-scalar (2-Step FoS) regression \citep{fan2000two}, which first obtains regression coefficients at each time point then smooths these estimates. Although 2-Step FoS is not designed for functions with sparsity, we include it to compare estimation accuracy.}} For the proposed methods, we set $K = 30$ and choose $\lambda$ and $\alpha$, when applicable, by minimizing the adjusted EBIC in Equation~\eqref{eq:adjust.ebic} through a grid search using 100 $\lambda$'s chosen log-linearly from $0.1$ to $100$ and 18 $\alpha$'s linearly from $0.05$ to $0.95$. We derive joint confident bands for ${\beta}(t)$'s based on the variance estimation in Section \ref{s:variance}. In particular, we perturb sparse estimates $\widehat{{\gamma}}_{jk}$ with small random numbers to expand Equation~\eqref{eq:covariance} into all $\widehat{{\gamma}}_{jk}$'s, which gives the covariance of $\widehat{\bm{\gamma}}$ and subsequently a joint confident band for each ${\beta}(t)$. Figure \ref{fig:all-coefs} visualizes the estimates and their 95\% joint confidence intervals using one randomly selected replication. The proposed method appears to have tighter and more adaptive confidence intervals than gMCP and gLasso, partly due to its accounting for heterogeneous errors. Two-step FoS also enjoys tight joint confidence bands, but it cannot recover sparsity. Although all other methods contain sparsity constraints in their design, gLasso fails to detect the support of ${\beta}_{3}(\time)$. Functional group bridge methods and gMCP succeed in recovering the globally sparse signal ${\beta}_{1}(\time)$. The proposed method is the only method to recover the locally sparse coefficient ${\beta}_{3}(\time)$ at $\time\in (0.8,1]$, when the error variance is large, indicating its adaptivity to various sparse and noise levels. \begin{figure} \centerline{ \centering \includegraphics[width=0.95\linewidth, trim = 0 0 0 45, clip=TRUE ]{simulation/coefs.pdf}} \caption{ \label{fig:all-coefs} Fitted coefficients with 95\% joint confidence intervals at $n = 100$ (top two rows) and $n = 1000$ (bottom two rows). } \end{figure} \begin{table} \centering \begin{minipage}{0.95\linewidth} \caption{ Performance comparison of various methods. For each sample size $n \in \{100, 1000\}$, RMSE calculates $\|{\beta}_{3}(\time) - \widehat{{\beta}}_{3}(\time) \|_{2}$, $L_{\infty}$ measures $\|{\beta}_{3}(\time) - \widehat{{\beta}}_{3}(\time) \|_{\infty}$, Coverage is the pointwise coverage of 95\% joint confidence intervals, and $F_1$ score assesses support recovery. All results are averaged over 100 simulations. Standard errors are reported in parentheses. } \label{tbl:rmse} \begin{tabular*}{0.9\linewidth}{@{}l@{\extracolsep{\fill}}r@{\extracolsep{\fill}}r@{\extracolsep{\fill}}r@{\extracolsep{\fill}}r@{\extracolsep{\fill}}r@{\extracolsep{\fill}}r@{\extracolsep{\fill}}r@{}} \hline \multirow{1}{*}{} $n$ & Metrics & Proposed & $\bm{W}=\bm{I}$ & $\alpha=1$ & gMCP & gLasso & 2-Step FoS \\ \hline \multirow{3}{*}{\rotatebox[origin=c]{90}{ $100$ }} & \small{RMSE} \tiny{$(\times 0.01)$} & 8.6 (0.3) & \textbf{8.1} (0.3) & 8.8 (0.3) & 9.5 (0.2) & 10.2 (0.3) & 8.8 (0.2) \\ & {$L_{\infty}$} \tiny{$(\times 0.01)$} & \textbf{21.2} (0.9) & 23.0 (0.9) & 22.4 (0.7) & 26.2 (0.9) & 25.6 (0.7) & 23.1 (0.8) \\ & {Coverage} & 94.8 (1.0) & 93.8 (0.9) & 87.3 (1.0) & 99.8 (0.1) & 99.5 (0.2) & 93.6 (0.6) \\ & $F_{1}$ score & 0.85 (0.0) & 0.82 (0.0) & 0.79 (0.0) & 0.75 (0.0) & 0.75 (0.0) & 0.75 (0.0) \\ \hline \multirow{3}{*}{\rotatebox[origin=c]{90}{ $1000$ }} & \small{RMSE} \tiny{$(\times 0.01)$} & \textbf{2.4} (0.1) & 2.5 (0.1) & 3.2 (0.1) & 3.3 (0.1) & 3.6 (0.1) & 3.0 (0.1) \\ & $L_{\infty}$ \tiny{$(\times 0.01)$} & \textbf{7.6} (0.3) & 8.1 (0.3) & 8.5 (0.2) & 9.8 (0.3) & 9.7 (0.3) & 8.5 (0.3) \\ & Coverage & 94.6 (0.4) & 96.4 (0.4) & 86.3 (0.8) & 99.6 (0.1) & 99.2 (0.2) & 94.6 (0.5) \\ & $F_{1}$ score & 0.94 (0.0) & 0.90 (0.0) & 0.85 (0.0) & 0.75 (0.0) & 0.75 (0.0) & 0.75 (0.0) \\ \hline \end{tabular*} \end{minipage} \vspace*{6pt} \end{table} We next focus on ${\beta}_3(t)$ and compare each method in terms of both accuracy and support detection. For each method, we calculate the root mean squared error (RMSE) $\|\widehat{{\beta}}_3(\time) - {\beta}_3(\time)\|_{2}$ to measure the overall accuracy, and $\|\widehat{{\beta}}_3(\time) - {\beta}_3(\time)\|_{\infty}$ to measure the maximum difference, reported in Table \ref{tbl:rmse}. We can see that our approach outperforms other methods in estimating the locally sparse coefficient ${\beta}_{3}(\time)$ for both sample sizes. Table \ref{tbl:rmse} also presents the coverage of the confident bands produced by each method. All methods except $\alpha=1$ attain the nominal coverage without significant deviation at $n = 1000$. Both gMCP and gLasso lead to the largest coverage at the expense of wider confidence bands; this can be clearly observed in Figure \ref{fig:all-coefs}. In contrast, the proposed method gives much tighter confidence bands while maintaining a coverage that is close to the nominal level. {{For support detection, we calculate the false positive rate (FPR) or recall by $|S({\beta}_3) \cap S_{\delta}(\widehat{{\beta}}_3)^c|/|S({\beta}_3)|$, true positive rate (TPR) $|S({\beta}_3)^c \cap S_{\delta}(\widehat{{\beta}}_3)^c|/|S({\beta}_3)^c|$, and precision $|S({\beta}_3)^c \cap S_{\delta}(\widehat{{\beta}}_3)^c|/|S_{\delta}(\widehat{{\beta}}_3)^c|$ for some $\delta \geq 0$, where $|\cdot|$ counts the number of time points in an interval. Table \ref{tbl:rmse} reports the $F_{1}$ score $2/(\text{recall}^{-1} + \text{precision}^{-1})$ under strict sparsity ($\delta=0$), and Figure \ref{fig:roc} shows the receiver operating characteristic (ROC) curve by varying $\delta$, both averaged over 100 simulations.}} The proposed method gives the highest $F_1$ score for both sample sizes, corroborating sparsity recovery of functional group bridge. Additional results (in the Appendix) show that the proposed method leads to the lowest FPR, while the other three competing methods do not produce strict sparsity, thus yielding the same $F_1$ score. In Figure \ref{fig:roc}, group bridge-based methods, particularly the weighted version, tend to dominate other methods under $\delta$-sparsity. Overall, the substantial performance gain of the proposed method over $\alpha = 1$ and other methods may be partly due to the functional group bridge penalty for local sparsity and data-dependent weighting for heterogeneous volatility. \begin{figure} \centering \includegraphics[width=\linewidth]{simulation/roc-main-rerun.png} \caption{ \label{fig:roc} ROC curve for each method with $n = 100$ (left) and $n = 1000$ (right), averaged over 100 simulations. } \end{figure} \begin{figure} \centerline{ \includegraphics[width=0.85\linewidth, trim = 75 25 45 25,]{simulation/EBIC.pdf}} \caption{ \textbf{Left}: Adjusted EBIC heatmap with respect to combinations of $(\lambda, \alpha)$. \textbf{Right}: Aggregated RMSE $\sum_{j = 1}^3 \norm{\widehat{{\beta}}_j(\time)-{\beta}_j(\time)}_{2}$. Solid orange lines correspond to $(\lambda_{\mathrm{EBIC}}, \alpha_{\mathrm{EBIC}})$, the selected $(\lambda, \alpha)$ by the adjusted EBIC, and dash lines are $(\lambda_{\mathrm{RMSE}}, \alpha_{\mathrm{RMSE}})$, the optimal combination that minimizes RMSE. The small ticks on the legends: ``Best RMSE'' marks the EBIC value with $(\lambda_{\mathrm{RMSE}}, \alpha_{\mathrm{RMSE}})$; ``Best EBIC'' corresponds to the RMSE after using $(\lambda_{\mathrm{EBIC}}, \alpha_{\mathrm{EBIC}})$ to fit the model. } \label{fig:param-tuning} \end{figure} Figure~\ref{fig:param-tuning} assesses the proposed adjusted EBIC through a comparison with the aggregated RMSE $\sum_{j = 1}^3 \|\widehat{{\beta}}_j(\time)-{\beta}_j(\time)\|_{2}$. At $n = 1000$ the adjusted EBIC heatmap is highly consistent with the actual RMSE. The dark blue areas that indicate lowest EBIC and RMSE largely overlap, and the selected parameters are close to the actual best. For $n = 100$, although differing from the optimal ones, the selected $(\lambda, \alpha)$ give low RMSEs. Indeed, the optimal $(\lambda, \alpha)$ might not be unique as the RMSE heatmap shows a dark blue trajectory that achieves the best or close to the best accuracy. \section{Application to iEEG Data} \label{s:application} In this section, we apply the proposed method to a human intracranial electroencephalography (iEEG) dataset that is collected in Beauchamp's Lab to investigate multisensory integration and has been extensively described in \cite{ozker2018frontal} and \cite{karas2019cross}. In this experiment, participants either listened to recordings of words (auditory-only condition, A) or viewed videos and listened to recordings of words (audiovisual condition, AV). We are interested in the contrasting effect of A and AV on brain responses in different brain areas. We focus on analyzing \textit{mouth-leading} words (e.g., ``last'' and ``drive''), meaning that mouth movements start before speech sounds. Such words were found to show a reduced brain response to audiovisual words compared to auditory-only words~\citep{karas2019cross}. {{The experiment contains 64 trials, each lasting for 3 seconds. There are 7 participating patients with a total of 58 Superior Temporal Gyrus (STG) electrodes. We fit the proposed model on each subject and electrode separately as the highly precise iEEG measurements localize activities of a small population of neurons nearest each electrode and lead to drastically different signals across electrodes. This separate analysis also allows us to study transferability of our findings. Information borrowing through jointly modelling all electrodes may yield further efficiency gain. This can be achieved by accounting for the spatial feature in a hierarchical model that links trials of various electrodes. The main challenges include the need to formulate the spatial dependence of signals and stochastic random effects across electrodes, and develop scalable algorithms for the increased parameter space.}} The original analog traces are measured at 2000 Hz. We apply notch filters to remove line noise and its harmonics (60, 120 and 180 Hz, etc.). Then a common average reference is used to remove common shifts introduced by patient activities. High-gamma oscillations usually stay above 70 Hz; hence, we apply wavelet transform to extract 70 - 150 Hz activities from the raw analogue traces. The transformed data is further down-sampled to 100 Hz for storage purposes. Each session is sliced into trials according to epoch information. All the trials are aligned to auditory onset, i.e., the time when audio stimuli started to emerge. Because there might be visual information before audio onset for mouth leading words, we collect three seconds of data for each trial, with one second prior and two seconds posterior to audio onset. Since brain activity levels often shift for each trial and frequency, we calibrate the signals of high-gamma activities against their own baselines (the average signals during the baseline period from $-1$ to $-0.3$ seconds). After the baseline period, we collapse the data by frequencies, resulting in a $301$ time-point functional data for each trial and electrode. The functional response $\bm{Y}$ is an $64\times 301$ matrix for each electrode. The design matrix $\bm{X}$ is $64\times 2$, with the first column being constant one for the intercept and the second column indicating whether visual stimuli are present. The second regression coefficient ${\beta}_2(t)$ reflects the effect of audiovisual (AV) stimuli versus auditory only (A) stimuli, and is of primary interest in this study. The time domain $\mathcal{T}$ is partitioned into four parts: $\mathcal{T}^{1}=[-1,-0.3)$ as the baseline period, $\mathcal{T}^{2}=[-0.3,0)$ containing video onset but without audio in, $\mathcal{T}^{3}=[0,1.5)$ when both auditory and visual stimuli are present, and $\mathcal{T}^{4}=[1.5,2]$ as clip offset. {{Since each trial is calibrated to the baseline, differential brain activities to experiment stimuli are expected to be zero during the baseline period, and non-zero when experiment stimuli present and exhibit effects.}} Consequently, the estimation of the locally sparse function ${\beta}_2(t)$ as well as detection of its support is of particular interest. \begin{figure} \centerline{ \includegraphics[width=0.95\linewidth]{application/fitted-gb2.pdf} } \caption{Effect of AV versus A estimated by various methods. In each plot, the solid line (blue) is the estimated effect $\bm{\widehat{\beta}}_2(t)$, shaded area (light-blue) is the joint $95\%$ confidence band, and dashed line (grey) is the estimated effect from ordinary least squares at each time point. } \label{fig:e14-YAB} \end{figure} \begin{figure} \centering \includegraphics[width=0.85\linewidth]{application/brain.pdf} \caption{\textbf{First row}: visualization of all 58 electrodes mapped onto N27 template brain. \textbf{Second row}: mean response of AV-A from auditory onset to 500 ms after onset. Color coding: blue for suppression introduced by visual stimuli, gray for little to no differences, and red for that AV is greater than A. \textbf{Third row}: p-values for each electrodes with alternative hypothesis of AV less than A response. \label{fig:pstg}} \end{figure} We use $K=50$ when implementing the proposed method and select $\lambda$ and $\alpha$ by the adjusted EBIC. Figure \ref{fig:e14-YAB} plots the fitted coefficients for ${\beta}_2(t)$, AV versus A effect. In the proposed weighted functional group bridge approach, no significant signals are seen in the baseline window, while the other methods deviate from this expectation. According to \cite{karas2019cross}, we should expect a negative AV-A response after auditory onset as visual stimuli may suppress activities for words ``drive'' and ``last''. Because the proposed functional group bridge method is sparse on non-significant responses, it becomes easy not only to observe the suppression ($\text{AV}<\text{A}$), but to locate the starting time of that suppression as well as to automate the detection of duration of significant AV versus A effect. Figure \ref{fig:pstg} visualize all the 58 STG electrodes using the N27 template brain \citep{holmes1998enhancement}. The average response within 500 ms after auditory onset indicates that the posterior part of STG area is suppressed by additional visual stimuli when audio is present. To test the significance, we calculate the p-value to test the null hypothesis that there is no suppression ($\text{AV}\geq\text{A}$) for each electrode. The z-score is derived from $\min_{\time \in (0, 0.5)}\bracketlg[\big]{\widehat{{\beta}}(\time)/\widehat{s}(\time)}$, where $\widehat{s}(t)$ is the estimated standard derivation of $\widehat{{\beta}}(\time)$ as described in Section~\ref{s:simulation} based on \eqref{eq:covariance}. The corresponding p-values are displayed in the third row of Figure \ref{fig:pstg}. There are 15 electrodes in the posterior part of STG with p-values less than $0.05$. A closer inspection into the results show that each participant is associated with at least one significant electrode, indicating consistent visual surpressions in the posterior STG area for audiovisual stimuli. Our analysis for cross-modal suppression of auditory cortex complements the work by \cite{ozker2018frontal} and \cite{karas2019cross}, showing that multisensory interactions are a powerful modulator of activity throughout the speech perception network. Compared with the traditional methods used by \cite{ozker2018frontal, karas2019cross}, the proposed nonparametric method is more flexible with theroetical support. In addition, the proposed method provides a data-driven approach to find the time window where the brain response to each experimental condition differs, rather than relying on manually defined window as was done in the initial publications. \section*{Acknowledgements} This research was partly supported by the Grant DMS-2015569 from the National Science Foundation, and 1R24MH117529 from the BRAIN Initiative of the United States National Institutes of Health. \bibliographystyle{apalike} \section{Introduction} \label{s:intro} Functional data analysis (FDA) is routinely encountered in modern applications due to the rapid advancement of new techniques to collect high-resolution data that can be viewed as curves; see~\cite{ramsay2005fda, morris2015functional, wang2016functional} for a comprehensive treatment. An overwhelming focus has been on nonparametric estimation of the underlying functions. However, shape constraints arise naturally in modern applications. {{One such example is \textit{local sparsity}, i.e., the function is exactly zero on subregions, in contrast to global sparsity that refers to a zero function.}} Local sparsity is a crucial characteristic for a nonparametric method to be interpretable in a variety of applications, and the estimation of the support as well as the function itself is of primary interest. This article aims to develop a flexible method with efficient implementation and theoretical guarantees for simultaneously estimating and recovering the support of locally sparse functions. Our motivation stems from neuroscientific studies using human intracranial electroencephalography (iEEG) data. {{iEEG is an emerging invasive method that offers anatomically precise measurements of human brain activity with electrodes placed on or implanted in the human brain, leading to excellent temporal resolution data and high signal-to-noise ratios \citep{lachaux2012high,kaiju2017high}}}. In most iEEG experiments, {{participants are presented with multiple experimental conditions. The brain response to each condition is recorded, and the experimenter wishes to know whether and how they differ}}. The contrast of brain activities is expected to be locally sparse (zero at certain period of time), and detecting non-sparse regions is of substantial interest to neuroscientists in addition to estimating the coefficient functions. For example, Figure \ref{fig:intro-demo} shows iEEG data from an audiovisual speech perception task \citep{ozker2018frontal} under two experimental conditions, namely, ``auditory-only'' and ``audiovisual''. In this study, the goal is to understand how the brain responds to auditory and visual stimuli through analyzing differential brain activities to these two conditions. Large trial-to-trial variation necessitates the use of statistical inference to automate the extraction of both population trajectories and supports of underlying brain activities. \begin{figure} \centering \includegraphics[width=5in]{application/intro-demo.pdf} \caption{Baseline corrected response of iEEG high-gamma power under auditory-only (left) and audiovisual (right) conditions. The data are obtained by decomposing the measured voltage signal into frequency space, converting to Decibel unit, calibrated to baseline (from $-1$ to $-0.3$ seconds), and then taking the average power in the 70-150Hz range. Each individual grey line is one trial. The bold solid line is the mean responses, and the shaded area around the mean is a pointwise 95\% confidence interval. \label{fig:intro-demo}} \end{figure} Over the past several decades, there has been an extensive literature on sparsity. This leads to a rich menu of methods in the context of regularization-based variable selection with the parameter space being \textit{sparse vectors}, including the Lasso~\citep{tibshirani1996regression}, minimax concave penalty (MCP)~\citep{zhang2010nearly}, and bridge regression~\citep{frank1993statistical}, to name just a few; see \cite{fan2010selective} for a review. Such concepts have been extended to grouped variable selection and nonparametric \textit{sparse functions}. {{Indeed, coupled with basis expansions, sparse coefficient vectors regularize the estimated function and lead to globally sparse coefficient functions via grouped sparsity. Along this line, \cite{barber2017} extended group Lasso to functional data, and \cite{chen2016variable} adopted group MCP, both achieving variable selection and parameter estimation.}} However, comparatively little work has been done for functions with local sparsity. {{There is a related literature on utilizing various penalties to improve interpretability, for example, \cite{james2009functional,zhou2013functional,wang2015functional,lin2017locally}}}. These methods, however, rely on scalar responses and are not suitable for the motivating iEEG studies, where the response is functional and covariates are scalar; hereafter we refer to such cases as \textit{function-on-scalar regression}. Function-on-scalar regression poses unique challenges to methodological and theoretical developments. In particular, the intrafunctional dependence of responses is vital, and the large sample properties may be more intricately determined by the sample size (number of subjects) as well as the sampling frequency of individual trajectories of each subject. {{In what follows we focus our attention on longitudinal data over time that out motivating example corresponds to.}} In this paper, we propose a method for simultaneous regression and support estimation for function-on-scalar regression, where the underlying functions are locally sparse. We adopt group bridge estimators coupled with B-splines to recover the sparse pattern of functional regression coefficients. {{Unlike the group Lasso and Lasso, group bridge penalty provably achieves variable selection in linear models at the group and individual level simultaneously \citep{huang2009group}. This is particularly well suited for locally sparse functions by inducing exactly zero regions through grouping basis coefficients that contribute to the function at each time point, while maintaining parsimony and regularization of basis coefficients via selection at the individual level. Following our use of B-splines and grouping structure of variables, other penalties can also be considered if they ensure both group-level and individual-level sparsity; however, these methods have not been extended to function-on-scalar regression.}} The proposed method does not require Gaussian assumptions and {{allows flexible heterogeneous correlation structures through random effects that possibly depend on various experimental phases.}} This leads to a novel \textit{weighted functional group bridge} approach for function-on-scalar mixed effect models. On the algorithmic front, we introduce a nested alternating direction method of multipliers (ADMM) algorithm with ``warm-start'' and ``early stopping'' to speed up the computation. On the theoretical front, we establish a range of large sample properties, including rate optimality in the minimax sense for regression and selection consistency for support estimation. Although under different models, our theory relies on substantially simplified assumptions than the existing literature to regularize regression functions, notably Assumption~\ref{assumption:integral}, facilitating interpretability. We allow flexible sampling designs including the case when the number of time points grows faster than the sample size, which is better suited for iEEG studies. In an application to the aforementioned iEEG experiment, our results complement previous studies by showing that multisensory interactions are a powerful modulator of activity throughout the speech perception network~\citep{ozker2018frontal, karas2019cross}. The rest of the article is organized as follows. Section \ref{s:methodology} introduces our model, the proposed estimator, and the optimization algorithm. Section \ref{s:asymptotic-properties} provides asymptotic properties. Section \ref{s:simulation} contains simulations, followed by an application to iEEG analysis in Section \ref{s:application}. The proposed method is implemented in the R package {\verb!spfda!}, available on CRAN. The Appendix include all proofs and additional simulations. \section{Methodology} \label{s:methodology} \subsection{Model} Suppose a sample of $n$ functional signals $\bracketlg[s]{{y}_{i}(\time)}_{i = 1}^n$ is observed on a compact time set $\mathcal{T}$. We assume without loss of generality $\mathcal{T}=\bracketmd{0,1}$. The linear function-on-scalar mixed effect model assumes \begin{equation} \label{eq:FDA.model} {y}_{i}(\time)=\sum_{j=1}^{p}x_{ij}{\beta}_{j}(\time)+ {\theta}_{i}(\time) + {\epsilon}_{i}(\time), \end{equation} where $x_{ij}$ is a scalar predictor, ${\beta}_j(\time)$ is a fixed effect function, ${\theta}_{i}(\time)$ is a zero mean random effect with {{covariance kernel $\Sigma_{\bm{\theta}}(\time,\time')$ that captures the within-curve dependence}}, and the ${\epsilon}_{i}(\time)$ is the measurement error process independent of ${\theta}_{i}(\time)$ with zero means and covariance kernel $\Sigma_{\bm{\epsilon}}(\time,\time')=\sigma^{2}\delta_{t, t'}$; here $\delta_{t, t'}$ is the Kronecker delta. We assume ${\beta}_j(\time)$ is smooth and locally sparse on the time domain. We propose to use phase-dependent random effects to account for heterogeneous dependence structures in various stages of an experiment, such as resting phase, trial onset, and stimuli offset. In particular, we partition $\mathcal{T}$ into a union of disjoint intervals $\bracketlg[s]{\mathcal{T}^{\text{pa}}}_{\text{pa}=1}^{P}$, where each $\mathcal{T}^{\text{pa}}$ corresponds to a stage of the experiments, and random effects ${\theta}_{i}(\time)$ are smooth within each phase. Note this generalizes traditional mixed effect models where $P$ is typically set to one. We use B-splines $\bracketlg{{\phi}_{k}(\time)}_{k=1}^{K}$ to approximate each fixed effect function, that is, ${\beta}_j(\time) = \sum_{k = 1}^K {\gamma}_{jk} {\phi}_k(\time) + {R}_{j}(\time)$, where ${R}_j(\time)$ is the approximation error. In addition to sharp approximation bounds to smooth functions, B-splines are particularly well suited for sparse functions as they are locally supported and thus transfer sparsity in ${\beta}(\time)$ to a sparse $p$ by $K$ matrix $\bm{\gamma} = \{{\gamma}_{jk}\}_{p\times K}$. Let a non-negative integer $d$ be the degree of B-splines and define the knots of length $K+d+1$ be $\time_{\tidx_{1}}=\dots=\time_{\tidx_{d}}=0=\time_{\tidx_{d+1}}<\time_{\tidx_{d+2}}<\dots<\time_{\tidx_{K}}=1=\time_{\tidx_{K+1}}=\dots=\time_{\tidx_{K+d+1}}$. Then B-splines are defined recursively \citep{de1978practical} as follows: \begin{gather} {\phi}_{k,1}(\time) = \mathbf{1}_{[\time_{ \tidx_{k} }, \time_{ \tidx_{k+1} })}(t) \label{eq:spl-def1} ,\quad {\phi}_{k,d+1}(\time) = \frac{\time-\time_{\tidx_{k}}}{ \time_{\tidx_{k+d}} - \time_{\tidx_{k}} }{\phi}_{k,d}(\time) + \frac{ \time_{\tidx_{k+1}} - t }{ \time_{\tidx_{k+q-1}} - \time_{\tidx_{k+1}} }{\phi}_{k+1,d}(\time), \label{eq:spl-def2} \end{gather} where $k = 1, \ldots, K$. B-splines of order $q = d + 1$ are ${\phi}_{k}(\time) = {\phi}_{k,q}(\time)$, and we typically choose $q\geq 4$. In practice, functional data are observed at discrete time points. Let $\mathcal{T}_{0}=\bracketlg{\time_{\tidx}}_{\tidx=1}^{T} \subseteq \mathcal{T}$ be the set of time points at which ${y}_{i}(\time)$ is observed. Each partition set $\mathcal{T}_{0}^{\text{pa}}$ is defined as $\mathcal{T}_{0}\cap \mathcal{T}^{\text{pa}}$. Let $\bm{Y}=\bracketlg{y_{i \tidx}}_{n\times T}, \bm{\theta}=\bracketlg{{\theta}_{i\tidx}}_{n\times T}, \bm{E}=\bracketlg[s]{e_{it}}_{n\times T}$ be the discretized responses, random effects, and random noise observed at $\mathcal{T}_{0}$, respectively, and {{$\bm{X}=\bracketlg{x_{ij}}_{n\times p}$ the design matrix}}, $\bm{B}=\bracketlg{{B}_{k}^{\tidx}}_{K\times T}$ the basis functions $\bracketlg{{\phi}_{k}(\time)}_{k=1}^{K}$ evaluated on $\mathcal{T}_{0}$, and $\bm{R}=\bracketlg{{R}_{j}(\time_{\tidx})}_{p\times T}$ the corresponding approximation error. Then Model~\eqref{eq:FDA.model} can be written as \begin{equation} \bm{Y}=\bm{X}\bm{\gamma} \bm{B} + \bm{X}\bm{R} + \bm{\theta} + \bm{E}, \label{eq:2-4} \end{equation} where $\bm{\theta}$ and $\bm{E}$ have covariance $\bm{\Sigma}_{\bm{\theta}}$ and $\bm{\Sigma}_{\bm{\epsilon}}=\sigma^{2}\bm{I}$ that are discretized $\Sigma_{\bm{\theta}}(\time,\time')$ and $\Sigma_{\bm{\epsilon}}(\time,\time')$ on $\mathcal{T}_{0}$. In what follows, we use subscript to index rows; for example, $\bm{y}_{i}, \bm{X}_i, \bm{\gamma}_j, \bm{B}_k$ are the corresponding rows of $\bm{Y}, \bm{X}, \bm{\gamma}, \bm{B}$, respectively. We use $\bm{B}^{(\tidx)}$ to denote the $\tidx^{th}$ column of $\bm{B}$, and $\bm{X}^{(j)}$ to denote the $j^{th}$ column of $\bm{X}$. All vectors are column vectors. \subsection{Estimation: Weighted functional group bridge}\label{sec:group.penalty} We propose a weighted functional group bridge approach to estimate $\bm{\gamma}$: \begin{equation}\label{eq:gamma.hat} \widehat{\bm{\gamma}} =\argmin{\bm{\gamma}} \; L(\bm{\gamma}; \lambda, \alpha, \bm{W}) = \argmin{\bm{\gamma}} \; \{f(\bm{\gamma}; \bm{W})+\lambda g(\bm{\gamma}; \alpha)\}, \end{equation} where $f(\bm{\gamma}; \bm{W})=\frac{1}{2}\sum_{i=1}^{n}\|(\bm{y}_{i}^{T}-\bm{X}_{i}^{T}\bm{\gamma} \bm{B})\bm{W}\|_{2}^{2}$ is the squared error loss with each observation weighted by a $T\times T$ matrix $\bm{W}$, and $\lambda g(\bm{\gamma}; \alpha)$ is a penalty term to encourage sparsity on $\bm{\gamma}$ and ${\beta}(t)$ with tuning parameters $\lambda \geq 0$ and $\alpha > 0$. Each coefficient function ${\beta}_j(\time)$ for $j = 1, \ldots, p$ is estimated by $\widehat{{\beta}}_j(\time)=\sum_{k = 1}^K \widehat{{\gamma}}_{jk} {\phi}_{k}(\time)$. {{We use a \textit{group bridge} penalty for $g(\bm{\gamma}; \alpha)$ to achieve sparsity in both $\bm{\gamma}$ and ${\beta}_j(t)$: \begin{equation} g(\bm{\gamma}; \alpha) =\sum_{j=1}^{p}\sum_{\tidx=1}^{T}g_{j,\tidx}(\bm{\gamma}; \alpha), \quad g_{j,\tidx}(\bm{\gamma}; \alpha) = \left\{\sum_{k: \bm{B}_k^{(m)} \neq 0} \abs{{\gamma}_{jk}}\right\}^{\alpha}, \end{equation} which decomposes $g(\bm{\gamma}; \alpha)$ into $pT$ groups. Within each group, the $L_1$ penalty on a subset of $\bm{\gamma}$ leads to sparse estimates $\widehat{\bm{\gamma}}_j$~\citep{tibshirani1996regression}. At the group level, if $g_{j,\tidx}(\bm{\gamma}; \alpha) = 0$, then $\abs{{\beta}_{j}(\time_{\tidx})}=\abs[s]{\bm{\gamma}_{j}^{T}\bm{B}^{(m)}}=0$. Hence, group-level sparsity on $g_{j,\tidx}(\bm{\gamma}; \alpha)$ leads to sparse ${\beta}_j(\time_{\tidx})$ at $\time_{\tidx}$. \cite{knight2000asymptotics} shows bridge estimators with $\alpha\in (0,1]$ combine variable selection and parameter estimation for sufficiently large $\lambda$. To achieve sparsity in both $\bm{\gamma}$ and ${\beta}_j(t)$, we propose to use $\alpha \in (0, 1)$ as it has the appealing property to select variables at the individual and group level simultaneously~\citep{huang2009group}. Note that $g(\bm{\gamma}; \alpha)$ becomes the $L_1$ penalty when $\alpha = 1$, which does not explicitly point to group-level sparsity that is critical to ensure that ${\beta}_j(t)$ is exactly zero at some $t$.}} Nevertheless, the developed algorithm in the following section is applicable for both $\alpha \in (0, 1)$ and $\alpha = 1$, and we further compare these two variants in simulations. To use a compact notation for $g_{jm}(\bm{\gamma}; \alpha)$, we indicate with $\mathbf{1}\{\bm{B}^{(\tidx)}\} = \big[\mathbf{1}\{{B}_{k}^{(\tidx)}\}\big]$ the indicator function evaluated on $\bm{B}^{(\tidx)}$, a column vector whose $k$th element $\mathbf{1}\{{B}_{k}^{(\tidx)}\}=1$ if ${B}_{k}^{(\tidx)}\neq 0$, and zero otherwise. Then \begin{equation} g_{j,\tidx}(\bm{\gamma}; \alpha) = \bracketmd[\bigg]{\sum_{k=1}^{K}\abs{{\gamma}_{jk}}\cdot \mathbf{1}\bracketlg[s]{{B}_{k}^{(\tidx)}}}^{\alpha} = \|\mathbf{1}\bracketlg[s]{\bm{B}^{(\tidx)}}\odot\bm{\gamma}_{j}\|_{1}^{\alpha}, \end{equation} where $\norm{\cdot}_{1}$ is the $L_{1}$ norm, and $\mathbf{1}\bracketlg[s]{\bm{B}^{(\tidx)}}\odot\bm{\gamma}_{j}$ is the element-wise multiplication between $\mathbf{1}\bracketlg[s]{\bm{B}^{(\tidx)}}$ and $\bm{\gamma}_{j}$. {{One needs to specify $(\lambda, \alpha, \bm{W})$ in the objective function $L(\bm{\gamma}; \lambda, \alpha, \bm{W})$. In the next sections, to ease exposition we assume these parameters are given.}} As such, in the sequel we omit $(\alpha, \lambda, \bm{W})$ in $L(\bm{\gamma};\lambda,\alpha,\bm{W}), f(\bm{\gamma};\bm{W})$ and $g(\bm{\gamma};\alpha)$ and instead use $L(\bm{\gamma}), f(\bm{\gamma})$, and $g(\bm{\gamma})$, respectively, when it does not cause confusion. {We will introduce fully data-driven methods to select $\bm{W}$ and $(\alpha, \lambda)$ in Section~\ref{s:parameter-tuning}.} \subsection{Optimization: Nested ADMM algorithm} We first recast the minimization of $L(\bm{\gamma})$ into an iterative Lasso problem as in \cite{huang2009group}. In particular, we embed $g(\bm{\gamma})$ in a carefully chosen higher dimensional space then link the solution back to $g(\bm{\gamma})$ through a particular path. Denote the expanded surface as \begin{gather} S\bracketsm{\bm{\gamma},\bm{\zeta}} =\sum_{j,\tidx}s_{j,\tidx}\bracketsm{\bm{\gamma},\bm{\zeta}}, \quad \bm{\zeta}=\{{\zeta}_{j,\tidx}\}, \\ s_{j,\tidx}(\bm{\gamma},\bm{\zeta}) =\frac{\alpha^{\alpha}}{(1-\alpha)^{\alpha-1}}{\zeta}_{j,\tidx}^{1-\frac{1}{\alpha}}\|\mathbf{1}\bracketlg[s]{\bm{B}^{(\tidx)}}\odot\bm{\gamma}_{j}\|_{1} +\alpha^{\alpha}(1-\alpha)^{1-\alpha}{\zeta}_{j,\tidx}. \end{gather} The original non-convex problem in Equation~\eqref{eq:gamma.hat} can be solved by finding the minimizer for \begin{gather} \argmin{\bm{\gamma},\bm{\zeta}}\ L_{S}(\bm{\gamma},\bm{\zeta}) \quad \text{subject to} \quad \bm{\zeta}=\bm{\zeta}(\bm{\gamma}) \text{ and } \bm{\zeta} > 0, \label{eq:modified-objective}\\ \text{where } L_{S}(\bm{\gamma},\bm{\zeta})=f(\bm{\gamma})+S(\bm{\gamma},\bm{\zeta})\label{eq:modobj} , \text{ and } {\zeta}_{j,\tidx}(\bm{\gamma}) =\bracketsm[\Big]{\frac{1-\alpha}{\alpha}}^{\alpha}\|\mathbf{1}\bracketlg[s]{\bm{B}^{(\tidx)}}\odot\bm{\gamma}_{j}\|_{1}^{\alpha}. \end{gather} We carry out the optimization by iteratively updating $\bm{\zeta}$ with fixed $\bm{\gamma}=\bm{\gamma}^{\mathrm{old}}$ through the definition $\bm{\zeta} = \bm{\zeta}(\bm{\gamma})$, and updating $\bm{\gamma}$ by solving a Lasso problem with fixed $\bm{\zeta}=\bm{\zeta}^{\mathrm{new}}$. We propose to solve the iterative Lasso problem using nested alternating direction method of multipliers, or ADMM~\citep{boyd2011distributed}. Algorithm \ref{alg:1} details the nested ADMM algorithm, in which we use common notations for matrices. For any matrix $\bm{A}$, $\bm{A}^{+}$ is the positive part, and $\bm{A}^{-}$ is the negative part. The operator $\diag(\cdot)$ extracts the diagonal elements of a square matrix into a vector, and expands a vector to a diagonal square. The operator $\oslash$ between two matrices defines element-wise division. {We use the ridge regression estimate $\widehat{\bm{\gamma}}_{\rm ridge}$ that minimizes \eqref{eq:gamma.hat} with $g(\bm{\gamma}; \alpha) = \sum_j \| \bm{\gamma}_j \|_2^2$ and tuning parameter $\lambda_{\rm ridge}$ as a closed-form ``warm-start".} Compared to LARS~\citep{efron2004least} adopted by \cite{huang2009group}, warm started ADMM can significantly improve the performance: If initialized near the solution, ADMM converges faster to modest accuracy within a few steps~\citep{boyd2011distributed, majzoobi2018analysis}. To fully take advantage of this property, we use few ADMM steps within each iteration without checking or waiting till full convergence, leading to ``early stopping''. The solutions at each iteration are used as warm-starts for the next iteration, further speeding up the convergence. {{Although the partial derivative $\partial g(\bm{\gamma})/\partial {\gamma}_{jk}$ near zero diverges, zero does not tend to be an absorbing state with an increased augmented Lagrangian parameter $\rho$ in Algorithm \ref{alg:1}. In addition, the adopted dense initialization via ridge regression and early stopping in ADMM help prevent the coefficients from entering zeros at early stage,}} leaving enough iterations for the coefficients to prioritize fitting before becoming sparse. {{In numerical experiments not reported here, we have found that the proposed algorithm outputs similar estimates with radically different initial values, indicating robustness. Nevertheless, we recommend to use the ridge regression estimate for faster convergence.}} {{We use the following default settings in our numerical experiments, unless otherwise stated. We use 5-fold cross validation to select $\lambda_{\rm ridge}$ in ridge regression. The number of iterations $S_{1}$ is 20, and the number of ADMM steps per iteration is $S_{2} = 50$. }}We increase $\rho$ exponentially by letting $\rho = e^{4s / S_{2} - 1}$ where $s$ is current ADMM step. \begin{algorithm}[ht] \caption{Nested ADMM solver for the case $\alpha\in(0,1)$}\label{alg:1} \begin{algorithmic}[1] \Procedure{}{$\bm{X},\bm{Y},\bm{B},\lambda, \alpha, \bm{W}, S_{1}, S_{2}$}\Comment{Inputs} \State Initialize $\bm{\gamma}\leftarrow \bm{\gamma}^{(0)}\leftarrow \hat{\bm{\gamma}}_{\rm ridge}$, $\bm{E}\leftarrow \bm{Y}-\bm{X}\bm{\gamma} \bm{B}$; \State SVD decomposition: $\bm{X} =\bm{U}_{\bm{X}}\bm{D}_{\bm{X}}\bm{V}_{\bm{X}}^{T}$, $\bm{B}\bm{W} =\bm{U}_{\bm{B}}\bm{D}_{\bm{B}}\bm{V}_{\bm{B}}^{T}$; \State Assign $\bm{V} = \bm{V}_{\bm{X}}^{T}$, $\bm{U} = \bm{U}_{\bm{B}}$, $\bm{Z} = \diag(\bm{D}_{\bm{X}}^{2})\diag(\bm{D}_{\bm{B}}^{2})^{T}+\rho\mathbf{1}_{p}\mathbf{1}_{K}^{T}$ ; \For{$v$ in $1,2,\dots,S_{1}$} \Comment{Macro-loop: iterative Lasso} \State Calculate $\bm{D}^{(v)} = \{{D}_{jk}^{(v)}\},$ where ${D}_{jk}^{(v)} = \alpha^{\alpha}(1-\alpha)^{1-\alpha}{\zeta}_{j,\tidx}^{1-\frac{1}{\alpha}}(\bm{\gamma}^{(v-1)})\cdot\mathbf{1}\bracketlg[s]{{B}_{k}^{(\tidx)}}$; \State Initialize $\bm{\eta}^{(0)}=\bm{\gamma}^{(v-1)}$, $\bm{\xi}^{(0)}=\bm{\gamma}^{(v-1)},$ $\bm{\psi}^{(0)} = \bm{\xi}^{(0)}-\bm{\eta}^{(0)} = \bm{0}$; \For{$s$ in $1,2,\dots,S_{2}$} \Comment{ADMM loop, fixed steps} \State $\bm{\phi}\leftarrow \bm{V}\bm{X}^{T}\bm{Y}\bm{W}(\bm{B}\bm{W})^{T}\bm{U}-\bm{\psi}^{(s-1)}+\rho \bm{V}\bm{\eta}^{(s-1)}\bm{U}$ \State $\bm{\xi}^{(s)}\leftarrow \bm{V}^{T}\left(\bm{\phi}\oslash \bm{Z}\right)\bm{U}^{T}$; \State $\bm{\eta}^{(s)}\leftarrow\bracketlg[\big]{\bm{\xi}^{(s)}+\frac{1}{\rho}\bm{V}^{T}\bm{\psi}^{(s-1)}\bm{U}^{T}-\frac{\lambda}{\rho}\bm{D}^{(v)}}^{+}-\bracketlg[\big]{\bm{\xi}^{(s)}+\frac{1}{\rho}\bm{V}^{T}\bm{\psi}^{(s-1)}\bm{U}^{T}+\frac{\lambda}{\rho}\bm{D}^{(v)}}^{-}$; \State $\bm{\psi}^{(s)} \leftarrow\bm{\psi}^{(s-1)}+\rho \bm{V}\bracketlg[s]{\bm{\xi}^{(s)}-\bm{\eta}^{(s)}}\bm{U}$; \EndFor \State Assign $\bm{\gamma}\leftarrow \bm{\gamma}^{(v)}\leftarrow \bm{\eta}^{(S_{2})}$; \State Recall $\widehat{\bm{Y}}=\bm{X}\bm{\gamma}^{(v)}\bm{B}$, calculate $\widehat{\bm{E}}=\bm{Y}-\widehat{\bm{Y}}$; \If{ $\|\widehat{\bm{E}} \bm{W}\|_{2}$ is stable }{ Break the loop} \Comment{Exit} \EndIf \EndFor \State \textbf{Return} $\bm{\gamma}$; \EndProcedure \end{algorithmic} \end{algorithm} Not that by setting $S_{2}=1$ and forcing ${D}^{(v)}_{jk}=1$ at each iteration, Algorithm~\ref{alg:1} also solves the case when $\alpha=1$. \subsection{Variance Estimation} \label{s:variance} Algorithm \ref{alg:1} solves an augmented Lagrangian problem $L^\text{aug}$: \begin{equation} L^\text{aug}(\bm{\xi}, \bm{\zeta}, \bm{\psi}, \bm{\eta}; \bm{W}, \lambda, \alpha, \rho) = L_S(\bm{\xi}, \bm{\zeta}) + \bracketlg{ \vec{(\bm{\psi})}^{T} \vec{\bracketsm{\bm{V}\bm{\xi} \bm{U} - \bm{V}\bm{\eta} \bm{U}}} } + \frac{\rho}{2}\norm{\bm{V}(\bm{\xi}-\bm{\eta})\bm{U}}_{2}^{2}, \end{equation} where $\vec(\bm{A})$ vectorizes $\bm{A}$ by stacking columns of $\bm{A}$. The dual feasibility in the ADMM optimality condition yields \begin{gather} \{\bm{V}\bm{\xi}^{(s)} \bm{U}\} \odot \bm{Z} = \bm{V}\bm{X}^{T}\bm{Y}\bm{W}\bm{W}^{T}\bm{B}^{T}\bm{U} - \bm{\psi}^{(s-1)} +\rho \bm{V}\bm{\eta}^{(s-1)}\bm{U} \label{eq:dual-1}\\ \mathbf{0} = \bracketmd[\Big]{-\frac{\lambda}{\rho} D(\bm{\zeta})\text{sign}\bracketlg[\big]{\bm{\xi}^{(s)}} + \frac{1}{\rho}\bm{V}^{T}\bm{\psi}^{(s-1)}\bm{U}^{T} - \bm{\eta}^{(s)}} \odot \text{sign}\bracketlg[\big]{\bm{\xi}^{(s)}}. \label{eq:dual-2} \end{gather} When Algorithm \ref{alg:1} converges, $\rho (\bm{\eta}^{(s)}-\bm{\eta}^{(s-1)})\rightarrow \mathbf{0}$ and $\bm{\xi}^{(s)} \rightarrow \widehat{\bm{\gamma}}$. Hence, for $(j,k)$ such that $\widehat{{\gamma}}_{jk}\neq 0$, the preceding optimality conditions in \eqref{eq:dual-1} and \eqref{eq:dual-2} yield \begin{equation} {\bm{X}^{(j)}}^T \bm{X}\widehat{\bm{\gamma}} \bm{B}\bm{W}\bm{W}^T\bm{B}_{k} + \lambda {D}_{jk}(\widehat{\bm{\zeta}})\widehat{{\gamma}}_{jk} = {\bm{X}^{(j)}}^T \bm{X}\bm{\gamma} \bm{B}\bm{W}\bm{W}^T\bm{B}_{k} + {\bm{X}^{(j)}}^T \bm{E}\bm{W}\bm{W}^T\bm{B}_{k}. \label{eq:optimality} \end{equation} Denote $\bm{P}(j,k)=\vec\{\bm{X}^T\bm{X}^{(j)}\bm{B}_{k}^T\bm{W}\bm{W}^T\bm{B}^T+\lambda {D}_{jk} \bm{J}(j,k)\}$, where $\bm{J}(j,k)$ is sparse matrix with only its $(j,k)$ element being $1$, and let $\bm{Q}(j,k)=\bm{X}^{(j)}\bm{B}_{k}^T\bm{W}\bm{W}^T$. Then $(\ref{eq:optimality})$ can be written as \begin{equation} \vec\bracketlg{\bm{P}(j,k)}^T\vec(\widehat{\bm{\gamma}}) = \vec\bracketlg{\bm{Q}(j,k)}^T \vec(\bm{X}\bm{\gamma} \bm{B}+\bm{Z}\bm{\theta}+\bm{E}), \label{eq:gamma-implicit} \end{equation} for $(j,k)$ such that $\widehat{{\gamma}}_{jk}\neq 0$. Letting $\vec_{\lambda}(\widehat{\bm{\gamma}})$ be the sub-vector of $\vec(\widehat{\bm{\gamma}})$ on its support, that is, all elements in $\vec_{\lambda}(\widehat{\bm{\gamma}})$ are non-zeros, and likewise $\bm{P}_{\lambda}(j,k)$ be $\bm{P}(j,k)$ on its support, then we have $\vec\bracketlg{\bm{P}(j,k)}^T\vec(\widehat{\bm{\gamma}}) = \vec_{\lambda}\bracketlg{\bm{P}(j,k)}^T\vec_{\lambda}(\widehat{\bm{\gamma}})$. Bind $\vec_{\lambda}\bracketlg{\bm{P}(j,k)}$ by column for all $(j,k)$ such that $\widehat{{\gamma}}_{jk}\neq 0$, and denote it as $\bm{P}_{\lambda}$. It is easy to show that $\bm{P}_{\lambda}$ is a square matrix and further $ \bm{P}_{\lambda}\vec_{\lambda}(\widehat{\bm{\gamma}}) = \bm{Q} \vec(\bm{X}\bm{\gamma} \bm{B}+\bm{Z}\bm{\theta}+\bm{E}),$ where $\bm{Q}$ is also a square matrix column-binded by $\vec\bracketlg{\bm{Q}(j,k)}$. Consequently, the covariance of $\widehat{\bm{\gamma}}$ is given by \begin{equation} \text{Cov}\bracketlg{\vec_{\lambda}(\widehat{\bm{\gamma}})}=\bm{P}_{\lambda}^{-1}\bm{Q}\text{Cov}\bracketlg{\vec(\bm{Z}\bm{\theta}+\bm{E})}\bm{Q}^T\bracketsm{\bm{P}_{\lambda}^T}^{-1}. \label{eq:covariance} \end{equation} \subsection{Choice of weights and parameter tuning} \label{s:parameter-tuning} We propose to use $\bm{W} \propto\bm{\Sigma}^{-1/2}$ to accounts for heterogeneity in the functional response, where $\bm{\Sigma}=\bm{\Sigma}_{\bm{\theta}} + \sigma^{2}\bm{I}$ is the covariance matrix of ${y}_{i}^{T}-\bm{X}_{i}^{T}{\beta}$. When $\bm{\Sigma}_{\bm{\theta}}$ and $\sigma^{2}$ are unknown, we substitute using their estimates $\widehat{\bm{\Sigma}}_{\bm{\theta}}$ and $\widehat{\sigma}^{2}$ to derive $\widehat{\bm{\Sigma}}$ and subsequently $\bm{W}$. We propose to employ local linear regression~\citep{fan1993local, zhu2014spatially} to estimate $\bm{\Sigma}$, assuming the existence of the second-order derivative of ${\theta}_{i}(\time)$ within each phase $\mathcal{T}^{\text{pa}}$. Denote $\Delta_{\tidx,b}(\time)=(\time_{\tidx} - \time) / b$ and ${\theta}'_{i,b}(\time)=b \cdot d{\theta}_{i}/d\time(\time)$, and choose a kernel function $K_{b}(\time)$ with the bandwidth parameter $b$ selected by minimizing the generalized cross-validation score~\citep{zhu2014spatially}. For each $\time\in\mathcal{T}^{\text{pa}}$, we estimate ${\theta}_{i}(\time)$ using a weighted least squares procedure \citep{fan1993local}: \begin{align} \bracketlg[\Big]{\widehat{{\theta}}_{i}(\time),\widehat{{\theta}'}_{i}(\time) }^T = \argmin{ {\theta}_{i}(\time), {\theta}'_{i}(\time) } \sum_{ \tidx: \time_{\tidx}\in \mathcal{T}_{0}^{\text{pa}} } & \Big[ {y}_{i}(t_{\tidx}) - \sum_{j=1}^{p} x_{ij} \widehat{{\beta}}_{j}^{ols}(\time_{\tidx}) \\ &\quad - \bracketlg[\big]{{\theta}_{i}(\time) + {\theta}'_{i}(\time)\Delta_{\tidx,b}(\time)} \Big]^{2} K_{b}(\time_{\tidx} - \time), \end{align} where $\widehat{{\beta}}_{j}^{ols}(\time_{\tidx})$ is ordinary lease square estimator of the $j^{th}$ coefficient at time $\time_{\tidx}$. We then calculate $\widehat{\bm{\Sigma}}_{\bm{\theta}}$ from the sample covariance of $\bracketlg[s]{\widehat{{\theta}}_{i}(\time_{\tidx})}_{i,\tidx}$, and $\widehat{\sigma}^2$ from the residuals ${y}_{i}(t_{\tidx}) - \sum_{j=1}^{p} x_{ij} \widehat{{\beta}}_{j}^{ols}(\time_{\tidx})- \widehat{{\theta}}_{i}(\time_{\tidx})$. {{As a passing comment, one may alternatively use $\bm{W} = \bm{I}$; this may lead to efficiency loss unless the functional dependence is homogeneous or approximately so, a special case of Model~\eqref{eq:FDA.model} without random effects. The developed methods and theory are applicable for this simplified model with such a choice of $\bm{W}$.}} We next move on to the tuning of $\alpha$ and $\lambda$ via an adjusted extended Bayesian information criterion (EBIC). We choose an equally spaced sequence of knots for B-splines. For given $K$, the EBIC proposed by \cite{chen2008extended} is \begin{equation} EBIC_{\nu} = \frac{\norm{(\bm{Y}-\bm{X}\widehat{\bm{\beta}})\bm{W}}_2^2}{n\sigma^{2}} + T\log{(\sigma^{2})} + df \frac{\log{n}}{n} + \nu df \frac{\log{pK}}{n}, \label{eq:ebic} \end{equation} where $\widehat{\bm{\beta}}$ is the fitted coefficients of a given model, $df$ the number of non-zero elements in $\bm{\gamma}$, $\nu \in [0, 1]$ a constant, and $\sigma^{2}$ an unknown parameter analogue to the error variance in a standard regression model. We use $\nu=\max\bracketlg[\big]{1-\frac{\log(n)}{2\log(pK)}, \frac{1}{2}}$ based on Theorem 1 and discussions in \cite{chen2008extended}. \cite{huang2010variable} and \cite{wang2015functional} substituted $n\sigma^{2}$ with residual sum of squares based on $\widehat{\bm{\beta}}$. Since a bridge estimator is not unbiased due to its shrinkage to zero, we instead propose to estimate $\sigma^{2}$ by the weighted residual sum of squares based on the generalized least-square estimator $\widehat{\bm{\beta}}_{GLS}$, which is unbiased although lacks sparsity. Letting $\widehat{\bm{\beta}}_{GLS} = (\bm{X}^{T}\bm{X})^{-1}\bm{X}^{T}\bm{Y}\bm{W}\bm{W}^{T}\bm{B}^{T}(\bm{B}\bm{W}\bm{W}^{T}\bm{B}^{T})^{-1}$ and $\widehat{{\sigma}}^{2}_{GLS} = \norm{(\bm{Y}-\bm{X}\widehat{\bm{\beta}}_{GLS})\bm{W}}_{2}^{2}/(nT),$ then the proposed adjusted EBIC is \begin{equation} EBIC_{\nu} = T \frac{\norm{(\bm{Y}-\bm{X}\widehat{\bm{\beta}})\bm{W}}_2^2}{\norm{(\bm{Y}-\bm{X}\widehat{\bm{\beta}}_{GLS})\bm{W}}_{2}^{2}} + df \frac{\log{n}}{n} + \nu df \frac{\log{pK}}{n}, \label{eq:adjust.ebic} \end{equation} up to an additive constant. In the simulation, we observe that our proposed adjusted EBIC select parameters that are close to the oracle values; see Section \ref{s:simulation} for more details. \section{Asymptotic Properties}\label{s:asymptotic-properties} In this section, we study asymptotic properties of the proposed estimators. For a function $f(t): [0, 1] \rightarrow \mathbb{R}$, let $\|f\|_r$ be the $L_r$ norm and $\|f\|_{\infty} = \sup_{t \in [0, 1]} |f(t)|$. Denote by $\mathcal{C}^{r}[0,1]$ the H\"older space on $[0,1]$ with order $r$, a set of functions $f(\time)$ such that for some $L_f > 0$, $|f^{(r_0)}(x) - f^{(r_0)}(y)| \leq L_f \|x - y\|^{r - r_0}$ for all $x, y \in [0, 1]$, where $r_0$ is the largest integer strictly smaller than $r$. Let $S(f)=\{\time\in\mathcal{T}: f(\time)=0\}$ map $f(t)$ to its zero set. Denote by $\delta_{\min}(\bm{A})$ and $\delta_{\max}(\bm{A})$ the minimum and maximum eigenvalues for any given matrix $\bm{A}$. For two sequences $a_{n, T}$ and $b_{n, T}$, $a_{n, T} \lesssim b_{n, T}$ means $a_{n, T} \leq C b_{n, T}$ for some universal constant $C > 0$. We write $a_{n, T} \asymp b_{n, T}$ if $a_{n, T} \lesssim b_{n, T}$ and $a_{n, T} \gtrsim b_{n, T}$. Asymptotics in this section are interpreted when $n$ and $T$ go to infinity. We assume the following regularity conditions. \begin{assumption} \label{assumption:holder-cont} The underlying ${\beta}_{j}(\time) \in \mathcal{C}^{r}[0,1]$, for $j=1,2,\dots,p$ and $r\geq 2$. \end{assumption} \begin{assumption} \label{assumption:integral} The integral $\underset{t\in S({\beta}_{j})^c}{\int} \abs[s]{ \frac{1}{{\beta}_j(t)} }^{2(1 - \alpha)} d\time$ exists and is finite, for all $j$. \end{assumption} \begin{assumption} $\bracketlg{{\epsilon}_{i}(\time)}_{i=1}^{n}$ and $\bracketlg{{\theta}_{i}(\time)}_{i=1}^{n}$ are independent across $i$ and sub-Gaussian.\label{assumption:iid-err} \end{assumption} \begin{assumption} The design matrix satisfies that for some constants $C_1, C_2 > 0$, $C_1\leq\delta_{\min}(\bm{X}^T \bm{X}/n)$ and $\delta_{\max}(\bm{X}^T \bm{X}/n) \leq C_2$, and the weight matrix is chosen such that $C_3 \leq \delta_{\min}(\bm{W} \bm{W}^T) \leq \delta_{\max}(\bm{W}\bm{W}^T) \leq C_4$ for some constants $C_3, C_4 > 0$, for all sufficiently large $n$ and $T$.\label{assumption:x-reg} \end{assumption} \begin{assumption} $\underset{\tidx}{\max}\bracketsm{\time_{\tidx+1}-\time_{\tidx}}=O(T^{-1})$. \label{assumption:equal-spaced} \end{assumption} \begin{assumption} $C_{5} K^{-1} \leq \time_{\tidx_{k+q}}-\time_{\tidx_{k}} \leq C_{6} K^{-1}$ for some constants $C_{5}, C_{6} > 0$, where $K<T$. \label{assumption:k} \end{assumption} {{Assumptions~\ref{assumption:holder-cont}, \ref{assumption:iid-err}, \ref{assumption:equal-spaced}, and \ref{assumption:k}, as well as the design matrix condition in Assumption \ref{assumption:x-reg}, are common in high-dimensional regression; see, for example, \cite{fan2000two, cai2011optimal, wang2015functional}. Assumptions \ref{assumption:equal-spaced} and \ref{assumption:k} are concerned with the spacing of time points and B-spline knots, respectively, and trivially hold when they are equally spaced.}} Assumption \ref{assumption:integral} is in the same vein of Conditions (B') and (C') in~\cite{Fan2004a} to ensure that the group bridge penalty does not dominate the least square error on its support, and implies that ${\beta}_{j}(\time)$ deviates from zero fast enough so that its support and zero set can be well distinguished. Unlike \cite{Fan2004a,huang2009group}, Assumption \ref{assumption:integral} disentangles the penalty and the regression function, leading to a simpler and more interpretable formulation to regularize regression coefficients. We achieve such simplicity by relying on a carefully modified B-spline approximation that will be detailed in Lemma~\ref{lem:appendix:approximation}. This assumption also suggests a lower bound of $\alpha$ for ${\beta}_{j}(\time)$ leaving zeros at polynomial speed. If ${\beta}_{j}(\time_{0})=0$ for some $\time_{0}$ and ${\beta}_{j}(\time)$ satisfies $\abs[s]{{\beta}_{j}(\time)} \gtrsim |\time-\time_{0}|^{b}$ as $t$ approaches $\time_{0}$ for some positive constant $b$, then choosing $\alpha> 1- 1/(2b)$ is required to comply with this assumption. {{Assumption~\ref{assumption:x-reg} holds for the proposed data-driven $\bm{W}$ that satisfies $\bm{W}\bm{W}^T = \widehat{\bm{\Sigma}}^{-1} $ if the eigenvalues of $\widehat{\bm{\Sigma}}$ are bounded from above and below, a condition that is often satisfied following the rich literature of covariance estimation in functional data. For example, letting $C_{\bm{\theta}}$ be a constant such that $\delta_{\max}(\bm{\Sigma}_{\bm{\theta}}) \leq C_{\bm{\theta}}$, Theorem 2 of \cite{zhu2014spatially} proves the consistency of $\widehat{\bm{\Sigma}}^{-1}$, and particularly indicates $\lvert \delta_{\max}(\widehat{\bm{\Sigma}}_{\bm{\theta}}) - \delta_{\max}({\bm{\Sigma}}_{\bm{\theta}})\rvert \lesssim C_{\bm{\theta}}/2$ and $\lvert \widehat{\sigma}^{2} - {\sigma}^{2}\rvert \lesssim {\sigma}^{2}/2$, yielding $\lvert \delta_{\max}(\widehat{\bm{\Sigma}}) - \delta_{\max}({\bm{\Sigma}}) \rvert \lesssim (C_{\bm{\theta}}+{\sigma}^{2})/2$ and thus $\delta_{\max}(\widehat{\bm{\Sigma}}) \lesssim 3(C_{\bm{\theta}}+{\sigma}^{2})/2$. Moreover, the semi-positiveness of $\widehat{\bm{\Sigma}}_{\bm{\theta}}$ ensures that $\delta_{\min}(\widehat{\bm{\Sigma}})\geq \widehat{\sigma}^{2} \gtrsim {\sigma}^{2}/2$.}} It is well known that if ${\beta}_{j}(\time) \in \mathcal{C}^{r}[0,1]$ and there are no overlapping spline knots for $t_{m_{k}}$ for $q\leq k\leq K$, then there exists a B-spline approximation such that $L_{\infty}$ approximation error is upper bounded by $K^{-r}$ up to a constant; for example, see~\cite{schumaker2007spline}. However, these accurate B-spline approximations do not necessarily capture the sparsity of the true function. In Lemma~\ref{lem:appendix:approximation}, we propose a sparse modification of such B-splines so that the new approximation preserves the sparsity structure with the same approximation accuracy. \begin{lemma} \label{lem:appendix:approximation}Under Assumptions~\ref{assumption:holder-cont} and \ref{assumption:k}, let $\widetilde{{\beta}}^{*}_{j}(\time)=\sum_{k=1}^{K}\widetilde{\bm{\gamma}}^{*}_{jk}{\phi}_{k}(\time)$ be the B-spline approximation in \cite{schumaker2007spline} such that $\big\|\widetilde{{\beta}}^{*}_{j}(\time) - {\beta}_{j}(\time)\big\|_{\infty} \leq C^{*}_{{\beta}_{j}}K^{-r}$ for a constant $C_{{\beta}_{j}}^{*}$. Then there exists a sparse modification $\widetilde{{\beta}}_{j}(\time):=\sum_{k=1}^{K}\widetilde{{\gamma}}_{jk}{\phi}_{k}(\time)$ and a constant $C_{{\beta}_{j}}$ such that $S({\beta}_{j}) \subseteq S(\widetilde{{\beta}}_{j})$, and $\big\|{\beta}_{j}(\time)-\widetilde{{\beta}}_{j}(\time)\big\|_{\infty} \leq C_{{\beta}_{j}} K^{-r}$. Also for any $\time\notin S(\widetilde{{\beta}}_{j})$, $\sum_{k:{\phi}_{k}(\time) > 0} \abs[s]{\widetilde{{\gamma}}_{jk}}\geq \frac{C_{{\beta}_{j}}^{*}}{qC_{{\beta}_{j}} + C_{{\beta}_{j}}^{*}}\abs[s]{{\beta}_{j}(\time)}$. \end{lemma} We call the modified B-spline coefficients $\widetilde{\bm{\gamma}} = \{\widetilde{{\gamma}}_{jk}\}_{p \times K}$ pseudo true values of $\bm{\gamma}$. The triangle inequality gives \begin{align} \big\|{\beta}_{j}(\time)-\widehat{{\beta}}_{j}(\time)\big\|_{\infty} & \leq \big\|{\beta}_{j}(\time)-\widetilde{{\beta}}_{j}(\time)\big\|_{\infty} + \big\|\widetilde{{\beta}}_{j}(\time)-\widehat{{\beta}}_{j}(\time)\big\|_{\infty} \\ & \leq C_{{\beta}_{j}} K^{-r} + \big\|\widehat{\bm{\gamma}}_{j}-\widetilde{\bm{\gamma}}_{j}\big\|_{\infty}\sum_{k=1}^{K}\big\|{\phi}_{k}(\time)\big\|_{1}, \end{align} where $\sum_{k=1}^{K}\norm{{\phi}_{k}(\time)}_{1}=1.$ Therefore, convergence rates of $\widehat{{\beta}}(\time)$ boils down to convergence rates of $\widehat{\bm{\gamma}}$ relative to the pseudo true $\widetilde{\bm{\gamma}}$ and the approximation error $C_{{\beta}_{j}} K^{-r}$ of using B-splines. The following Theorem~\ref{thm:5} and Theorem~\ref{thm:6} establish convergence rates of $\widehat{\bm{\gamma}}$ and $\widehat{{\beta}}_j$, respectively. To ease exposition, we relate $K$ and $T$ to $n$ by writing $K=n^{\frac{\kappa}{2r}}$ and $T=n^{\frac{\tau}{2r}}$ where $0<\kappa \leq\tau$. Here $n^{\frac{\kappa}{2r}}$ and $n^{\frac{\tau}{2r}}$ represent the asymptotic rates of $K$ and $T$, and any multiplicative constants do not change our results. To state the two theorems in their most general forms, we do not yet assume a specific order of either $\kappa$ or $\tau$. \begin{theorem}[Convergence rate of $\widehat{\bm{\gamma}}$] \label{thm:5} Let $c_{\kappa}=\min(1, \kappa)$ and suppose Assumptions~\ref{assumption:holder-cont}--\ref{assumption:k} hold. If $\frac{\log(\lambda)}{\log(n)} \leq 1 - \frac{c_{\kappa}}{2} + \frac{\tau}{4r} - \frac{\kappa}{4r}$, then we have as $n\rightarrow\infty$ \begin{equation} \norm{\widehat{\bm{\gamma}}-\widetilde{\bm{\gamma}}}_{\infty}\leq \norm{\widehat{\bm{\gamma}}-\widetilde{\bm{\gamma}}}_{2}=O_{p}\bracketsm[\big]{ n^{\frac{\kappa}{4r} - \frac{c_{\kappa}}{2}} }. \label{eq:3-7} \end{equation} \end{theorem} \begin{theorem}[Convergence rate of $\widehat{{\beta}}(\time)$]\label{thm:6} Under the same assumptions of Theorem~\ref{thm:5}, as $n\rightarrow\infty$, \begin{gather} \big\|\widehat{{\beta}}_{j}(\time)-{\beta}_{j}(\time)\big\|_{\infty} =O_{p} \bracketsm[\big]{n^{\frac{\kappa}{4r} - \frac{c_{\kappa}}{2}}}, \label{eq:6-2}\\ \big\|\widehat{{\beta}}_{j}(\time)-{\beta}_{j}(\time)\big\|_{2} =O_{p} \bracketsm[\big]{n^{ - \frac{c_{\kappa}}{2}}}. \label{eq:6-1} \end{gather} \end{theorem} Theorem~\ref{thm:6} establishes convergence rates of $\widehat{{\beta}}(\time)$ under both $L_{2}$ and $L_{\infty}$ norms. We remark that there is a phase transition at $\tau = 1$ in \eqref{eq:6-2}. When $\tau < 1$, because $\kappa < \tau$, we have $c_{\kappa}=\kappa$, and the optimal $L_{\infty}$ rate is attained at the largest $\kappa$, i.e., $\kappa = \tau$, which gives the rate $O_p(n^{(1-2r)\frac{\tau}{4r}})$. In this case, the rate improves as $\tau$ increases. When $\tau > 1$, the optimal $L_{\infty}$ rate is $O_{p}(n^{(1 - 2r)\frac{1}{4r}})$, which is achieved at $\kappa = 1$, and increasing $\tau$ does not improve the rate. The same phase transition also applies to the $L_2$ rate in \eqref{eq:6-1}, which coincides with the observation made in~\cite{cai2011optimal}. In addition, our rate calculation implies that with $\kappa = \min(\tau, 1)$, the $L_2$ rate in \eqref{eq:6-1} becomes $O_p(n^{- \min(\tau, 1) / 2})$, i.e., $O_p(n^{-1/2} + T^{-r})$, which is minimax optimal~\citep{cai2011optimal}. The rate under the $L_\infty$ norm in \eqref{eq:6-2} indicates that $\widehat{{\beta}}(\time)$ converges to ${\beta}(\time)$ at each $t$ for $\kappa < 2r$. This is particularly useful in detecting sparse regions as pointwise convergence suggests low false positive rates and low false negative rates in finding the support of ${\beta}_{j}(\time)$. In particular, we consider $\delta$-sparsity denoted by $S_{\delta}(h) = \{\time \in \mathcal{T}: |h(\time)| \leq \delta\}$ for $\delta > 0$. Then Equation~\eqref{eq:6-2} suggests that for arbitrary $\delta > 0$, as $n\rightarrow\infty$, \begin{equation} P\{S(\widehat{{\beta}}_j) \subseteq S_{\delta}({\beta}_j)\} \rightarrow 1,\quad P\{S({{\beta}}_j) \subseteq S_{\delta}(\widehat{{\beta}}_j)\} \rightarrow 1 .\label{eq:TPR} \end{equation} {{In addition, the following theorem establishes one side of strict sparsity for the proposed method, that is, the support of $\widehat{{\beta}}(\time)$ is a subset of ${\beta}_{j}(\time)$ with probability approaching to $1$. This leads to low {false positive rates} under strict sparsity. It is an interesting future direction to study under what conditions the other side of strict sparsity also holds.}} \begin{theorem} \label{thm:9} Under the same conditions in Theorem~\ref{thm:5} and $\frac{\log(\lambda)}{\log(n)} > 1 + \frac{c_{\kappa}(\alpha-2)}{2} + \frac{\tau}{2r} - \frac{\kappa\alpha}{4r}$, as $n\rightarrow\infty$, there holds $P\{S({\beta}_j) \subseteq S(\widehat{{\beta}}_j)\} \rightarrow 1.$ \end{theorem} While we have focused on $\alpha <1$, a close inspection into the proofs of Theorems~\ref{thm:5} and \ref{thm:6} suggests that they also hold for $\alpha = 1$ (note that Assumption~\ref{assumption:integral} is not needed in this case). {{As discussed in Section~\ref{sec:group.penalty}, choosing $\alpha < 1$ induces exactly zero estimates of functional coefficients. Theorem \ref{thm:9} reassuringly shows that the recovered exactly zero regions tend to contain the zero regions of the true regression functions at least asymptotically. The proof of Theorem \ref{thm:9} crucially relies on the choice of $\alpha < 1$; see the Appendix for details.}} \section{Simulations} \label{s:simulation} We conduct simulations to compare finite sample performances of the proposed approach with competing methods in terms of function estimation and sparse region detection. We also assess the the proposed adjusted EBIC method for parameter tuning. We generate data according to Model~\eqref{eq:FDA.model}. We consider three coefficients to represent different sparsity levels, displayed in Figure \ref{fig:truth}: ${\beta}_{1}(\time)=0$ for global sparsity, ${\beta}_{2}(\time)=\sin(\pi\time)$ for no sparsity (a dense coefficient), and ${\beta}_{3}(\time)$ for local sparsity that is defined as \begin{equation} {\beta}_{3}(t)=\sin\bracketsm{\frac{5\pi}{2}\time-\frac{\pi}{2}}\mathbf{1}_{[0.2, 0.4)}(t) + \mathbf{1}_{[0.4,0.6)}(t) + \sin\bracketsm{\frac{5\pi}{2}\time-\pi}\mathbf{1}_{[0.6,0.8)}(t). \end{equation} Among the three coefficient functions ${\beta}_3(t)$ is the most interesting one as it is locally sparse that pertains to the motivation of this paper; ${\beta}_1(t)$ and ${\beta}_2(t)$ are not of particular interest, but they allow us to study the performance of the proposed method when there are other coefficient functions with various sparsity levels. The design matrix $\bm{X}$ is generated from the standard normal distribution $N(0,1)$. To simulate different phases of experiments, the random effects ${\theta}_{i}(\time)$ are generated from a $AR(1)\times \sigma(\time)$ process, where $\sigma(\time)$ is a non-decreasing step function visualized in Figure~\ref{fig:truth} and $AR(1)$ is an order one autoregressive process with correlation $0.9$. The errors ${\epsilon}_i(\time_\tidx) \sim N(0,1)$ are independent across observations and time points. We use $T = 100$ as the time resolution to generate equally spaced $t_m$. We consider two sample sizes: $n = 100$ (small sample size) and $n = 1000$ (large sample size). We run 100 simulations for each sample size. \begin{figure} \centerline{ \includegraphics[width=0.95\linewidth]{simulation/generation.pdf}} \caption{Three coefficient functions (left) and step function $\sigma(\time)$ (right). ${\beta}_{1}(t)$ is globally sparse; ${\beta}_{2}(t)$ is dense; ${\beta}_{3}(t)$ is locally sparse. For ${\beta}_{3}(t)$, its phase I has the smallest errors and is half sparse and half dense. Phase II is dense with intermediate errors, and phase III is sparse with the largest errors.} \label{fig:truth} \end{figure} In addition to the proposed weighted function group bridge approach, we include its two variants: homogeneous weight ($\bm{W}=\bm{I}$) and $\alpha=1$. Other competing methods include Group Lasso (gLasso) proposed by \cite{barber2017} and Group MCP (gMCP) by \cite{chen2016variable}. {{We also implement two-step function-on-scalar (2-Step FoS) regression \citep{fan2000two}, which first obtains regression coefficients at each time point then smooths these estimates. Although 2-Step FoS is not designed for functions with sparsity, we include it to compare estimation accuracy.}} For the proposed methods, we set $K = 30$ and choose $\lambda$ and $\alpha$, when applicable, by minimizing the adjusted EBIC in Equation~\eqref{eq:adjust.ebic} through a grid search using 100 $\lambda$'s chosen log-linearly from $0.1$ to $100$ and 18 $\alpha$'s linearly from $0.05$ to $0.95$. We derive joint confident bands for ${\beta}(t)$'s based on the variance estimation in Section \ref{s:variance}. In particular, we perturb sparse estimates $\widehat{{\gamma}}_{jk}$ with small random numbers to expand Equation~\eqref{eq:covariance} into all $\widehat{{\gamma}}_{jk}$'s, which gives the covariance of $\widehat{\bm{\gamma}}$ and subsequently a joint confident band for each ${\beta}(t)$. Figure \ref{fig:all-coefs} visualizes the estimates and their 95\% joint confidence intervals using one randomly selected replication. The proposed method appears to have tighter and more adaptive confidence intervals than gMCP and gLasso, partly due to its accounting for heterogeneous errors. Two-step FoS also enjoys tight joint confidence bands, but it cannot recover sparsity. Although all other methods contain sparsity constraints in their design, gLasso fails to detect the support of ${\beta}_{3}(\time)$. Functional group bridge methods and gMCP succeed in recovering the globally sparse signal ${\beta}_{1}(\time)$. The proposed method is the only method to recover the locally sparse coefficient ${\beta}_{3}(\time)$ at $\time\in (0.8,1]$, when the error variance is large, indicating its adaptivity to various sparse and noise levels. \begin{figure} \centerline{ \centering \includegraphics[width=0.95\linewidth, trim = 0 0 0 45, clip=TRUE ]{simulation/coefs.pdf}} \caption{ \label{fig:all-coefs} Fitted coefficients with 95\% joint confidence intervals at $n = 100$ (top two rows) and $n = 1000$ (bottom two rows). } \end{figure} \begin{table} \centering \begin{minipage}{0.95\linewidth} \caption{ Performance comparison of various methods. For each sample size $n \in \{100, 1000\}$, RMSE calculates $\|{\beta}_{3}(\time) - \widehat{{\beta}}_{3}(\time) \|_{2}$, $L_{\infty}$ measures $\|{\beta}_{3}(\time) - \widehat{{\beta}}_{3}(\time) \|_{\infty}$, Coverage is the pointwise coverage of 95\% joint confidence intervals, and $F_1$ score assesses support recovery. All results are averaged over 100 simulations. Standard errors are reported in parentheses. } \label{tbl:rmse} \begin{tabular*}{0.9\linewidth}{@{}l@{\extracolsep{\fill}}r@{\extracolsep{\fill}}r@{\extracolsep{\fill}}r@{\extracolsep{\fill}}r@{\extracolsep{\fill}}r@{\extracolsep{\fill}}r@{\extracolsep{\fill}}r@{}} \hline \multirow{1}{*}{} $n$ & Metrics & Proposed & $\bm{W}=\bm{I}$ & $\alpha=1$ & gMCP & gLasso & 2-Step FoS \\ \hline \multirow{3}{*}{\rotatebox[origin=c]{90}{ $100$ }} & \small{RMSE} \tiny{$(\times 0.01)$} & 8.6 (0.3) & \textbf{8.1} (0.3) & 8.8 (0.3) & 9.5 (0.2) & 10.2 (0.3) & 8.8 (0.2) \\ & {$L_{\infty}$} \tiny{$(\times 0.01)$} & \textbf{21.2} (0.9) & 23.0 (0.9) & 22.4 (0.7) & 26.2 (0.9) & 25.6 (0.7) & 23.1 (0.8) \\ & {Coverage} & 94.8 (1.0) & 93.8 (0.9) & 87.3 (1.0) & 99.8 (0.1) & 99.5 (0.2) & 93.6 (0.6) \\ & $F_{1}$ score & 0.85 (0.0) & 0.82 (0.0) & 0.79 (0.0) & 0.75 (0.0) & 0.75 (0.0) & 0.75 (0.0) \\ \hline \multirow{3}{*}{\rotatebox[origin=c]{90}{ $1000$ }} & \small{RMSE} \tiny{$(\times 0.01)$} & \textbf{2.4} (0.1) & 2.5 (0.1) & 3.2 (0.1) & 3.3 (0.1) & 3.6 (0.1) & 3.0 (0.1) \\ & $L_{\infty}$ \tiny{$(\times 0.01)$} & \textbf{7.6} (0.3) & 8.1 (0.3) & 8.5 (0.2) & 9.8 (0.3) & 9.7 (0.3) & 8.5 (0.3) \\ & Coverage & 94.6 (0.4) & 96.4 (0.4) & 86.3 (0.8) & 99.6 (0.1) & 99.2 (0.2) & 94.6 (0.5) \\ & $F_{1}$ score & 0.94 (0.0) & 0.90 (0.0) & 0.85 (0.0) & 0.75 (0.0) & 0.75 (0.0) & 0.75 (0.0) \\ \hline \end{tabular*} \end{minipage} \vspace*{6pt} \end{table} We next focus on ${\beta}_3(t)$ and compare each method in terms of both accuracy and support detection. For each method, we calculate the root mean squared error (RMSE) $\|\widehat{{\beta}}_3(\time) - {\beta}_3(\time)\|_{2}$ to measure the overall accuracy, and $\|\widehat{{\beta}}_3(\time) - {\beta}_3(\time)\|_{\infty}$ to measure the maximum difference, reported in Table \ref{tbl:rmse}. We can see that our approach outperforms other methods in estimating the locally sparse coefficient ${\beta}_{3}(\time)$ for both sample sizes. Table \ref{tbl:rmse} also presents the coverage of the confident bands produced by each method. All methods except $\alpha=1$ attain the nominal coverage without significant deviation at $n = 1000$. Both gMCP and gLasso lead to the largest coverage at the expense of wider confidence bands; this can be clearly observed in Figure \ref{fig:all-coefs}. In contrast, the proposed method gives much tighter confidence bands while maintaining a coverage that is close to the nominal level. {{For support detection, we calculate the false positive rate (FPR) or recall by $|S({\beta}_3) \cap S_{\delta}(\widehat{{\beta}}_3)^c|/|S({\beta}_3)|$, true positive rate (TPR) $|S({\beta}_3)^c \cap S_{\delta}(\widehat{{\beta}}_3)^c|/|S({\beta}_3)^c|$, and precision $|S({\beta}_3)^c \cap S_{\delta}(\widehat{{\beta}}_3)^c|/|S_{\delta}(\widehat{{\beta}}_3)^c|$ for some $\delta \geq 0$, where $|\cdot|$ counts the number of time points in an interval. Table \ref{tbl:rmse} reports the $F_{1}$ score $2/(\text{recall}^{-1} + \text{precision}^{-1})$ under strict sparsity ($\delta=0$), and Figure \ref{fig:roc} shows the receiver operating characteristic (ROC) curve by varying $\delta$, both averaged over 100 simulations.}} The proposed method gives the highest $F_1$ score for both sample sizes, corroborating sparsity recovery of functional group bridge. Additional results (in the Appendix) show that the proposed method leads to the lowest FPR, while the other three competing methods do not produce strict sparsity, thus yielding the same $F_1$ score. In Figure \ref{fig:roc}, group bridge-based methods, particularly the weighted version, tend to dominate other methods under $\delta$-sparsity. Overall, the substantial performance gain of the proposed method over $\alpha = 1$ and other methods may be partly due to the functional group bridge penalty for local sparsity and data-dependent weighting for heterogeneous volatility. \begin{figure} \centering \includegraphics[width=\linewidth]{simulation/roc-main-rerun.png} \caption{ \label{fig:roc} ROC curve for each method with $n = 100$ (left) and $n = 1000$ (right), averaged over 100 simulations. } \end{figure} \begin{figure} \centerline{ \includegraphics[width=0.85\linewidth, trim = 75 25 45 25,]{simulation/EBIC.pdf}} \caption{ \textbf{Left}: Adjusted EBIC heatmap with respect to combinations of $(\lambda, \alpha)$. \textbf{Right}: Aggregated RMSE $\sum_{j = 1}^3 \norm{\widehat{{\beta}}_j(\time)-{\beta}_j(\time)}_{2}$. Solid orange lines correspond to $(\lambda_{\mathrm{EBIC}}, \alpha_{\mathrm{EBIC}})$, the selected $(\lambda, \alpha)$ by the adjusted EBIC, and dash lines are $(\lambda_{\mathrm{RMSE}}, \alpha_{\mathrm{RMSE}})$, the optimal combination that minimizes RMSE. The small ticks on the legends: ``Best RMSE'' marks the EBIC value with $(\lambda_{\mathrm{RMSE}}, \alpha_{\mathrm{RMSE}})$; ``Best EBIC'' corresponds to the RMSE after using $(\lambda_{\mathrm{EBIC}}, \alpha_{\mathrm{EBIC}})$ to fit the model. } \label{fig:param-tuning} \end{figure} Figure~\ref{fig:param-tuning} assesses the proposed adjusted EBIC through a comparison with the aggregated RMSE $\sum_{j = 1}^3 \|\widehat{{\beta}}_j(\time)-{\beta}_j(\time)\|_{2}$. At $n = 1000$ the adjusted EBIC heatmap is highly consistent with the actual RMSE. The dark blue areas that indicate lowest EBIC and RMSE largely overlap, and the selected parameters are close to the actual best. For $n = 100$, although differing from the optimal ones, the selected $(\lambda, \alpha)$ give low RMSEs. Indeed, the optimal $(\lambda, \alpha)$ might not be unique as the RMSE heatmap shows a dark blue trajectory that achieves the best or close to the best accuracy. \section{Application to iEEG Data} \label{s:application} In this section, we apply the proposed method to a human intracranial electroencephalography (iEEG) dataset that is collected in Beauchamp's Lab to investigate multisensory integration and has been extensively described in \cite{ozker2018frontal} and \cite{karas2019cross}. In this experiment, participants either listened to recordings of words (auditory-only condition, A) or viewed videos and listened to recordings of words (audiovisual condition, AV). We are interested in the contrasting effect of A and AV on brain responses in different brain areas. We focus on analyzing \textit{mouth-leading} words (e.g., ``last'' and ``drive''), meaning that mouth movements start before speech sounds. Such words were found to show a reduced brain response to audiovisual words compared to auditory-only words~\citep{karas2019cross}. {{The experiment contains 64 trials, each lasting for 3 seconds. There are 7 participating patients with a total of 58 Superior Temporal Gyrus (STG) electrodes. We fit the proposed model on each subject and electrode separately as the highly precise iEEG measurements localize activities of a small population of neurons nearest each electrode and lead to drastically different signals across electrodes. This separate analysis also allows us to study transferability of our findings. Information borrowing through jointly modelling all electrodes may yield further efficiency gain. This can be achieved by accounting for the spatial feature in a hierarchical model that links trials of various electrodes. The main challenges include the need to formulate the spatial dependence of signals and stochastic random effects across electrodes, and develop scalable algorithms for the increased parameter space.}} The original analog traces are measured at 2000 Hz. We apply notch filters to remove line noise and its harmonics (60, 120 and 180 Hz, etc.). Then a common average reference is used to remove common shifts introduced by patient activities. High-gamma oscillations usually stay above 70 Hz; hence, we apply wavelet transform to extract 70 - 150 Hz activities from the raw analogue traces. The transformed data is further down-sampled to 100 Hz for storage purposes. Each session is sliced into trials according to epoch information. All the trials are aligned to auditory onset, i.e., the time when audio stimuli started to emerge. Because there might be visual information before audio onset for mouth leading words, we collect three seconds of data for each trial, with one second prior and two seconds posterior to audio onset. Since brain activity levels often shift for each trial and frequency, we calibrate the signals of high-gamma activities against their own baselines (the average signals during the baseline period from $-1$ to $-0.3$ seconds). After the baseline period, we collapse the data by frequencies, resulting in a $301$ time-point functional data for each trial and electrode. The functional response $\bm{Y}$ is an $64\times 301$ matrix for each electrode. The design matrix $\bm{X}$ is $64\times 2$, with the first column being constant one for the intercept and the second column indicating whether visual stimuli are present. The second regression coefficient ${\beta}_2(t)$ reflects the effect of audiovisual (AV) stimuli versus auditory only (A) stimuli, and is of primary interest in this study. The time domain $\mathcal{T}$ is partitioned into four parts: $\mathcal{T}^{1}=[-1,-0.3)$ as the baseline period, $\mathcal{T}^{2}=[-0.3,0)$ containing video onset but without audio in, $\mathcal{T}^{3}=[0,1.5)$ when both auditory and visual stimuli are present, and $\mathcal{T}^{4}=[1.5,2]$ as clip offset. {{Since each trial is calibrated to the baseline, differential brain activities to experiment stimuli are expected to be zero during the baseline period, and non-zero when experiment stimuli present and exhibit effects.}} Consequently, the estimation of the locally sparse function ${\beta}_2(t)$ as well as detection of its support is of particular interest. \begin{figure} \centerline{ \includegraphics[width=0.95\linewidth]{application/fitted-gb2.pdf} } \caption{Effect of AV versus A estimated by various methods. In each plot, the solid line (blue) is the estimated effect $\bm{\widehat{\beta}}_2(t)$, shaded area (light-blue) is the joint $95\%$ confidence band, and dashed line (grey) is the estimated effect from ordinary least squares at each time point. } \label{fig:e14-YAB} \end{figure} \begin{figure} \centering \includegraphics[width=0.85\linewidth]{application/brain.pdf} \caption{\textbf{First row}: visualization of all 58 electrodes mapped onto N27 template brain. \textbf{Second row}: mean response of AV-A from auditory onset to 500 ms after onset. Color coding: blue for suppression introduced by visual stimuli, gray for little to no differences, and red for that AV is greater than A. \textbf{Third row}: p-values for each electrodes with alternative hypothesis of AV less than A response. \label{fig:pstg}} \end{figure} We use $K=50$ when implementing the proposed method and select $\lambda$ and $\alpha$ by the adjusted EBIC. Figure \ref{fig:e14-YAB} plots the fitted coefficients for ${\beta}_2(t)$, AV versus A effect. In the proposed weighted functional group bridge approach, no significant signals are seen in the baseline window, while the other methods deviate from this expectation. According to \cite{karas2019cross}, we should expect a negative AV-A response after auditory onset as visual stimuli may suppress activities for words ``drive'' and ``last''. Because the proposed functional group bridge method is sparse on non-significant responses, it becomes easy not only to observe the suppression ($\text{AV}<\text{A}$), but to locate the starting time of that suppression as well as to automate the detection of duration of significant AV versus A effect. Figure \ref{fig:pstg} visualize all the 58 STG electrodes using the N27 template brain \citep{holmes1998enhancement}. The average response within 500 ms after auditory onset indicates that the posterior part of STG area is suppressed by additional visual stimuli when audio is present. To test the significance, we calculate the p-value to test the null hypothesis that there is no suppression ($\text{AV}\geq\text{A}$) for each electrode. The z-score is derived from $\min_{\time \in (0, 0.5)}\bracketlg[\big]{\widehat{{\beta}}(\time)/\widehat{s}(\time)}$, where $\widehat{s}(t)$ is the estimated standard derivation of $\widehat{{\beta}}(\time)$ as described in Section~\ref{s:simulation} based on \eqref{eq:covariance}. The corresponding p-values are displayed in the third row of Figure \ref{fig:pstg}. There are 15 electrodes in the posterior part of STG with p-values less than $0.05$. A closer inspection into the results show that each participant is associated with at least one significant electrode, indicating consistent visual surpressions in the posterior STG area for audiovisual stimuli. Our analysis for cross-modal suppression of auditory cortex complements the work by \cite{ozker2018frontal} and \cite{karas2019cross}, showing that multisensory interactions are a powerful modulator of activity throughout the speech perception network. Compared with the traditional methods used by \cite{ozker2018frontal, karas2019cross}, the proposed nonparametric method is more flexible with theroetical support. In addition, the proposed method provides a data-driven approach to find the time window where the brain response to each experimental condition differs, rather than relying on manually defined window as was done in the initial publications. \section*{Acknowledgements} This research was partly supported by the Grant DMS-2015569 from the National Science Foundation, and 1R24MH117529 from the BRAIN Initiative of the United States National Institutes of Health. \bibliographystyle{apalike}
{'timestamp': '2021-11-17T02:08:38', 'yymm': '2006', 'arxiv_id': '2006.10163', 'language': 'en', 'url': 'https://arxiv.org/abs/2006.10163'}
arxiv
\section{Introduction} \begin{figure}[t] \includegraphics[width=1.0\linewidth]{fig/k_cups.png} \vspace*{-.55cm} \caption{The most relevant taxonomy nodes are shown on the left when a user searches ``k cups'' on Amazon.com. } \label{fig:coffee_department} \vspace*{-.5cm} \end{figure} Taxonomies, the tree-structured hierarchies that represent the hypernymy (Is-A) relations, have been widely used in different domains, such as information extraction~\cite{Demeester2016LiftedRI}, question answering~\cite{Yang2017EfficientlyAT}, and recommender systems~\cite{huang2019taxonomy}, for the organization of concepts and instances as well as the injection of structured knowledge in downstream tasks. In particular, online catalog taxonomies\xspace serve as a building block of e-commerce websites (\eg, Amazon.com) and business directory services (\eg, Yelp.com) for both customer-facing and internal applications, such as query understanding, item categorization \cite{mao-etal-2019-hierarchical}, browsing, recommendation \cite{huang2019taxonomy}, and search \cite{wang2014hierarchical}. Fig.~\ref{fig:coffee_department} shows one real-world example of how the product taxonomy at Amazon.com is used to facilitate online shopping experience: when a user searches ``k cups'', the most relevant nodes (types) in the taxonomy \textit{Grocery \& Gourmet Food} are shown on the left sidebar. The taxonomy here serves multiple purposes. First, the user can browse relevant nodes to refine the search space if she is looking for a more general or specific type of items (\eg, ``Coffee Beverages''). Second, the taxonomy benefits query understanding by identifying that ``k cups'' belongs to the taxonomy \textit{Grocery \& Gourmet Food} and mapping the user query ``k cups'' to the corresponding taxonomy node ``Single-Serve Coffee Capsules \& Pods''. Third, the taxonomy allows query relaxation and makes more items searchable if the search results are sparse. For instance, not only ``Single-Serve Coffee Capsules \& Pods'' but also other coffee belonging to its parent type ``Coffee Beverages'' can be shown in the search results. Despite the prevalent use and benefits of online catalog taxonomies\xspace, most of them in practice are still built and maintained by human experts. Such manual practice embodies knowledge from the experts but is meanwhile labor-intensive and difficult to scale. On Amazon.com, the taxonomies usually have thousands of nodes, not necessarily enough to cover the types of billions of items: we sampled roughly 3 million items in Grocery domain on Amazon.com and found that over 70\% of items do not directly mention the types in the taxonomy, implying a mismatch between knowledge organization and item search. As a result, automatic taxonomy construction has drawn significant attention. Existing methods on taxonomy construction fail to work effectively on online catalog taxonomies\xspace for the following reasons. Most prior methods~\cite{kozareva2010semi,bansal2014structured,bordea2016semeval,shwartz2016improving,gupta2017taxonomy,mao2018end} are designed for taxonomy construction from general text corpora (\eg, Wikipedia), limiting their applicability to text-rich domains. The ``documents'' in e-commerce (\eg, item titles), however, are much shorter and pose particular challenges. First, it is implausible to extract terms with heuristic approaches~\cite{kozareva2010semi} from item titles and descriptions, since vendors can write them in arbitrary ways. Second, it is highly unlikely to find co-occurrences of hypernym pairs in the item titles due to their conciseness, making Hearst patterns~\cite{hearst1992automatic,panchenko2016taxi} and dependency parse-based features~\cite{mao2018end} infeasible. For instance, one may often see ``US'' and ``Seattle'' in the same document, but barely see ``Beverages'' and ``Coffee'' in the same item title. Third, blindly leveraging the co-occurrence patterns could be misleading: in an item titled ``\textit{Triple Scoop Ice Cream Mix, Premium Strawberry}'', ``Strawberry'' and ``Ice Cream'' co-occur but ``Strawberry'' is the flavor of the ``Ice Cream'' rather than its hypernym. The situation worsens as online catalog taxonomies\xspace are never static. There are new items (and thus new terms) emerging every day, making \textit{taxonomy construction from scratch} less favorable, since in practice we cannot afford to rebuild the whole taxonomy frequently and the downstream applications also require stable taxonomies to organize knowledge. To tackle the above issues of \textit{taxonomy construction from scratch}, we target the \textit{taxonomy enrichment} problem, which discovers emerging concepts\footnote{We use ``concept'', ``term'', ``type'', ``category'', and ``node'' interchangeably.} and attaches them to the existing taxonomy (named \textit{core taxonomy}) to precisely understand new customer interests. Different from taxonomy construction from scratch, the core taxonomies, which are usually built and maintained by experts for quality control and actively used in production, provide both valuable guidance and restrictive challenges for taxonomy enrichment. On the challenge side, the \textit{core taxonomy} requires term attachment to follow the existing taxonomy schema instead of arbitrarily building from scratch. On the bright side, we can base our work on the core taxonomy, which usually contains high-level and qualified concepts representing the fundamental categories in a domain (such as ``Beverages'' and ''Snacks`` for Grocery) and barely needs modification (or cannot be automatically organized due to business demands), but lacks fine-grained and emerging terms (such as ``Coconut Flour''). There are only a few prior works focused on taxonomy enrichment, which either employ simple rules~\cite{jurgens2015reserating} or represent taxonomy nodes by their associated items and totally neglect the lexical semantics of the concepts themselves~\cite{wang2014hierarchical}. In addition, prior studies~\cite{jurgens2016semeval,schlichtkrull2016msejrku} require manual training data and fail to exploit the structural information of the existing taxonomy. Despite the challenges, a unique opportunity for online catalog taxonomy\xspace enrichment is the availability of rich user behavior logs: vendors often carefully choose words to describe the type of their items and associate the items with appropriate taxonomy nodes to get more exposure; customers often include the item type in their queries and the majority of the clicked (purchased) items are instances of the type they are looking for. Such interactions among queries, items, and taxonomy nodes offer distinctive signals for hypernymy detection, which is unavailable in general-purpose text corpora. For instance, if a query mentioning ``hibiscus tea'' leads to the clicks of items associated with taxonomy node ``herbal tea'' or ``tea'', we can safely infer strong connections among ``hibiscus tea'', ``herbal tea'', and ``tea''. Existing works~\cite{wang2014hierarchical,liu2019user}, however, only utilize the user behavior heuristically to extract new terms or reduce the prediction space of hypernymy detection. \begin{figure*}[ht] \includegraphics[width=1.01\linewidth]{fig/octet} \vspace*{-.3cm} \caption{An overview of the proposed framework \textsc{Octet}\xspace. Item profiles and user queries in the target domain serve as framework input and the core taxonomy is used as self-supervision. New terms are automatically extracted via sequence labeling. Heterogeneous sources of signals, including the structure of the core taxonomy, the query-item-taxonomy interactions, and the lexical semantics of the term pairs are leveraged for hypernymy detection during term attachment.} \label{fig:framework} \vspace*{-.35cm} \end{figure*} In this paper, we present a self-supervised end-to-end framework, \textsc{Octet}\xspace, for online catalog taxonomy\xspace enrichment. \textsc{Octet}\xspace\ is novel in three aspects. First, \textsc{Octet}\xspace\ identifies new terms from item titles and user queries; it employs a sequence labeling model that is shown to significantly outperform typical term extraction methods. Second, to tackle the lack of text corpora, \textsc{Octet}\xspace leverages heterogeneous sources of signals; it captures the \textit{lexical semantics} of the terms and employs Graph Neural Networks (GNNs) to model the \textit{structure of the core taxonomy} as well as the \textit{query-item-taxonomy interactions} in user behavior. Third, \textsc{Octet}\xspace requires no human effort for generating training labels as it uses the core taxonomy for self-supervision during both term extraction and term attachment. We conduct extensive experiments on real-world online catalog taxonomies\xspace to verify the effectiveness of \textsc{Octet}\xspace via automatic, expert, and crowdsourcing evaluations. Experimental results show that \textsc{Octet}\xspace outperforms state-of-the-art methods by 46.2\% for term extraction and 11.5\% for term attachment on average. Notably, \textsc{Octet}\xspace doubles the size (2,163 to 4,355 terms) of an online catalog taxonomy\xspace in production with 0.881 precision. \start{Contributions.} (1) We introduce a self-supervised end-to-end framework, \textsc{Octet}\xspace, for online catalog taxonomy\xspace enrichment; \textsc{Octet}\xspace automatically extracts emerging terms and attaches them to the core taxonomy of a target domain with no human effort. (2) We propose a GNN-based model that leverages heterogeneous sources of information, especially the structure of the core taxonomy and query-item-taxonomy interactions, for term attachment. (3) Our extensive experiments show that \textsc{Octet}\xspace significantly improves over state-of-the-art methods under automatic and human evaluations. \section{Task Formulation} \start{Notations.} We define a taxonomy $T = (V, R)$ as a tree-structured hierarchy with term set $V$ and edge set $R$. A term $v \in V$ can be either single-word or multi-word (\eg, ``Yogurt'' and ``Herbal Tea''). The edge set $R$ indicates the Is-A relationship between $V$ (hypernym pairs such as ``Coffee'' -> ``Ground Coffee''). The online catalog taxonomies\xspace, which can be found in almost all online shopping websites such as Amazon.com and eBay, and business directory services like Yelp.com, maintain the hypernym relationship of their items (\eg, products or businesses). We define a \textit{core taxonomy} as a pre-given partial taxonomy that is usually manually curated and stores the high-level concepts in the target domain. We denote user behavior logs as $B = (Q, I)$, which record the user queries $Q$ in a search engine and corresponding clicked items $I$. The items $I$ are represented by item profiles such as titles and descriptions. $I$ is associated with (assigned to) nodes $V$ according to their types by item categorization (done by vendors or algorithms). \start{Problem Definition.} Let $T = (V, R)$ be a core taxonomy and $B = (Q, I)$ be user behavior logs, the {\em taxonomy enrichment} problem extends $T$ to $\bar{T} = (\bar{V}, \bar{R})$ with $\bar{V} = V \cup V'$, $\bar{R} = R \cup R'$, where $V'$ contains new terms extracted from $Q$ and $I$, and $R'$ contains pairs $(v, v'), v\in V, v' \in V'$, representing that $v$ is a hypernym of $v'$. \start{Non-Goals.} Although \textsc{Octet}\xspace works for terms regardless of their granularity, we keep $T$ unchanged as in~\cite{wang2014hierarchical,jurgens2016semeval} since we would like to keep the high-level expert-curated hypernym pairs intact and focus on discovering fine-grained terms. Following convention~\cite{jurgens2016semeval}, we do not identify the hypernym relationship between newly discovered types ($(v_1', v_2')$, $v_1', v_2' \in V'$). \textsc{Octet}\xspace already makes an important first step to solve the problem as our analysis shows that over 80\% terms are leaf nodes in the core taxonomy. \section{The \textsc{Octet}\xspace Framework} In this section, we first give a framework overview of the learning goal of term extraction and term attachment. We then elaborate on how to employ self-supervision of the core taxonomy to conduct term extraction via sequence labeling (Sec.~\ref{sec:term_extract}) and term attachment via GNN-based heterogeneous representation (Sec.~\ref{sec:term_attach}). \subsection{Framework Overview} \textsc{Octet}\xspace consists of two inter-dependent stages: \textbf{term extraction} and \textbf{term attachment}, which, in a nutshell, solves the problem of ``which terms to attach'' and ``where to attach'', respectively. Formally, the term extraction stage extracts the new terms $V'$ (with the guidance from $V$) that are to be used for enriching $T$ to $\bar{T}$. The term attachment stage takes $T$ and $V'$ as well as the sources of $V'$ (\ie, $Q$ and $I$) as input and attaches each new term $v' \in V'$ to a term $v \in V$ in $T$, forming the new edge set $R'$. \textsc{Octet}\xspace is readily deployable to different domains with no human effort, \ie, with no additional resources other than $T$, $Q$, $I$, and their interactions. Fig.~\ref{fig:framework} shows an overview of \textsc{Octet}\xspace. At a high level, we regard term extraction as a sequence labeling task and employ a sequence labeling model with distant supervision from $V$ to extract new terms $V'$. We show in Sec.~\ref{sec:term_extract_exp} that such a formulation is beneficial for the term extraction in online catalog taxonomy\xspace enrichment. For term attachment, existing hypernym pairs $R$ on $T$ are used as self-supervision. Structure of the core taxonomy as well as interactions among queries, items, and taxonomy nodes are captured via graph neural networks (GNNs) for structural\xspace representation learning. Meanwhile, the lexical semantics of the terms is employed and provides complementary signals for hypernymy detection (Sec.~\ref{sec:feat_ablation}). Each new term $v' \in V'$ is attached to one existing term $v \in V$ on $T$ based on the term pair representation. \subsection{Term Extraction Learning}\label{sec:term_extract} Term extraction extends $T=(V, R)$ with new terms $V'$. Extracting new terms from item profiles $I$ and user queries $Q$ has two benefits. First, they are closely related to the dynamics of customer needs, which is essential for the enrichment of user-oriented online catalog taxonomies\xspace and their deployment in production. Second, extraction from $I$ and $Q$ naturally connects type terms to user behavior, preparing rich signals required for generating structural\xspace term representations during term attachment. We propose to treat \textit{term extraction for online catalog taxonomy\xspace enrichment} as a sequence labeling task. Tokens in the text are labeled with the BIOE schema where each tag represents the beginning, inside, outside, and ending of a chunk, respectively. Instead of collecting expensive human annotations for training~\cite{zheng2018opentag}, we propose to adopt distant supervision by using the existing terms $V$ as self-supervised labels. Specifically, we find in $Q$ and $I$ the mentions of $V$ and label those mentions as the desired terms to be extracted. For example, item ``Golden State Fruit Pears to Compare Deluxe Gift'' with associated taxonomy node ``Pears'' will be labeled as "O O O B O O O O" for model learning. This approach has several advantages. First, unlike unsupervised term extraction methods~\cite{kozareva2010semi}, we train a sequence labeling model to ensure that only the terms in the same domain as the existing terms $V$ are extracted. Second, sequence labeling is more likely to extract terms of the desired type while filtering terms of undesired types (such as the brand or flavor of items) by inspecting the sentence context, which typical context-agnostic term extraction methods~\cite{liu2015mining,shang2018automated} fail to do. We train a BiLSTM-CRF model~\cite{panchendrarajan2018bidirectional} to fulfill term extraction in \textsc{Octet}\xspace. Briefly speaking, each token in the text is represented by its word embedding, fed into a bidirectional LSTM layer for contextualized representation. Then, tag prediction is conducted by a conditional random field (CRF) layer operating on the representation of the current token and the previous tag. A similar model architecture can be found in~\citet{zheng2018opentag}. Note that distant supervision may inevitably introduce noises in the labels. Nevertheless, we show in Sec.~\ref{sec:term_extract_exp} that \textsc{Octet}\xspace obtains superior performance in term extraction (precision@100=0.91). % In addition, \textsc{Octet}\xspace is likely to have low confidence in attaching incorrectly extracted terms, allowing further filtering with threshold setting during term attachment (Sec.~\ref{sec:tradeoff}). \subsection{Term Attachment Learning}\label{sec:term_attach} Term attachment extends taxonomy $(\bar{V} = V \cup V', R)$ with new edges $R'$ between terms in $V$ and $V'$. Following common practice~\cite{wang2014hierarchical,bansal2014structured}, we consider a taxonomy $\bar{T}$ as a Bayesian network where each node $v \in \bar{V}$ is a random variable. The joint probability distribution of nodes $\bar{V}$ can be then formulated as follows. \begin{equation*} P(\bar{V} \mid \bar{T}, \Theta) = P(v_0) \prod_{v \in \bar{V} \setminus v_0} P(v \mid p(v), \Theta), \end{equation*} where $v_0$ denotes the root node, $p(v)$ denotes the direct hypernym (parent) of node $v$, and $\Theta$ denotes model parameters. Maximizing the likelihood with respect to the taxonomy structure $\bar{T}$ gives the optimal taxonomy $\bar{T}^*$. As we do not modify the structure of core taxonomy $T$, the formulation can be simplified as follows. \begin{equation*} \vspace*{-.1cm} \begin{split} \bar{T}^* = \argmax_{\bar{T}} P(\bar{V} \mid \bar{T}, \Theta) &= \argmax_{\bar{T}} \prod_{v \in \bar{V} \setminus v_0} P(v \mid p(v), \Theta) \\ &= \argmax_{\bar{T}}\ \prod_{v' \in V'} P(v' \mid p(v'), \Theta). \end{split} \vspace*{-.1cm} \end{equation*} The problem definition further ensures that $p(v') \in V$ always holds true and thus no inter-dependencies exist between the new terms $v' \in V'$. Therefore, we can naturally regard term attachment as a \textit{multi-class classification problem} according to $P(v' \mid p(v'), \Theta)$ where each $p(v') = v \in V$ is a class. One unique challenge for online catalog taxonomy\xspace enrichment is the lack of conventional corpora. For example, it is rare to find co-occurrences of multiple item types in a single query (<1\% in Grocery domain on Amazon.com), let alone the ``such as''-style patterns in Hearst-based methods~\cite{kozareva2010semi}. Instead of using the limited text directly, we introduce signals from user behavior logs and the structure of the core taxonomy by modeling them in a graph (Sec.~\ref{sec:gnn}). The lexical semantics of the term pairs are further considered to better identify hypernymy relations (Sec.~\ref{sec:semantic_rep} \& \ref{sec:lexical_rep}). \subsubsection{Structural\xspace Representation}\hfill \label{sec:gnn} \noindent There is rich structural\xspace information for online catalog taxonomy\xspace enrichment which comes from two sources. First, the neighborhood (\eg, parent and siblings) of a node $v \in V$ on $T$ can serve as a meaningful supplement for the semantics of $v$. For example, one may not have enough knowledge of node $v=$ ``Makgeolli'' (Korean rice wine); but if she perceives that ``Sake'' (Japanese rice wine) is $v$'s sibling and ``Wine'' is $v$'s parent, she would have more confidence in considering ``Makgeolli'' as one type of ``Alcoholic Beverages''. Second, there exist abundant user behavior data, providing even richer structural information than that offered by the core taxonomy $T$. Specifically, items $I$ are associated with the existing taxonomy nodes $V$. New terms $V'$ are related to items $I$ and user queries $Q$ since $V'$ are extracted from the two sources. Furthermore, $I$ and $Q$ are also connected via clicks. Based on the observations above, we propose to learn a structural\xspace term pair representation to capture the structure in the core taxonomy and the query-item-taxonomy interactions as follows. \start{Graph Construction.} We construct a graph ${\mathcal{G}}$ where the nodes consist of the existing terms $v \in V$ and new terms $v' \in V'$. There are two sets of edges: one set is the same as $R$ in the core taxonomy $T$, which captures the ontological structure in $T$. The other set leverages the query-item-taxonomy interactions: for each new term $v' \in V'$, we find the user queries $Q_{v'}$ that mention $v'$ and collect the clicked items $I_{Q_{v'}}$ in the queries $Q_{v'}$. Then, we find the taxonomy nodes $\{v_i\}$ that $I_{Q_{v'}}$ is associated with. Finally, we add an edge between each $(v_i, v')$ pair. For instance, when determining the parent of a new term ``Figs'', we find that some queries mentioning ``Figs'' lead to clicked items associated with the taxonomy node ``Fruits'', evincing strong relations between the two terms. \start{Graph Embedding.} We leverage graph neural networks (GNNs) to aggregate the neighborhood information in ${\mathcal{G}}$ when measuring the relationship between a term pair. Specifically, we take the rationales in relational graph convolutional networks (RGCNs)~\cite{kipf2016semi,schlichtkrull2018modeling}. Let ${\mathcal{R}}$ denote the set of relations, including ($r_1$) The neighbors of $v$ on the core taxonomy $T$. The neighbors can be the (grand)parents or children of $v$ and we compare different design choices in Sec.~\ref{sec:graph_ablation}; ($r_2$) the interactions between $v \in V$ and $v' \in V'$ discovered in user behavior. We confine the interactions to be unidirectional (from $v$ to $v'$) since the terms $v \in V$ are already augmented with $r_1$ while there might be noise in the user behavior; and ($r_3$) the self-loop of node $v$. The self-loop of $v$ ensures that the information of $v$ itself is preserved and those isolated nodes without any connections can still be updated using its own representation. Let $N(v, r)$ denote the neighbors of node $v$ with relation $r$, and ${\bm{h}}^{\text{0}}_v$ the initial input representation of node $v$. The hidden representation of $v$ at layer (hop) $l$ is updated as follows: ${\bm{h}}^{l + 1}_v = \text{ReLU} (\sum_{r \in {\mathcal{R}}} \sum_{i \in \{N(v, r)\}} \frac{1}{c_{v, r}} {\bm{W}}^l_r {\bm{h}}^{l}_i)$, where ${\bm{W}}^l_r$ is the matrix at layer $l$ for linear projection of relation $r$ and $c_{v, r}$ is a normalization constant. We take the final hidden representation of each node ${\bm{h}}^{L}_v$ (\textit{denoted as ${\bm{g}}_v$}) as the graph embedding. \start{Relationship Measure.} \label{sec:sim_measure} One straightforward way of utilizing the structural\xspace representation is to use the graph embeddings ${\bm{g}}_v$ and ${\bm{g}}_{v'}$ as the representation of term $v$ and $v'$. Instead, we propose to measure the relationship between a term pair explicitly by cosine similarity and norm distance (more details in App.~\ref{app:repro}). We denote the relationship measure between two embeddings as $s({\bm{v}}, {\bm{v}}')$. One benefit of using $s({\bm{g}}_v, {\bm{g}}_{v'})$ is that empirically we observe $s({\bm{g}}_v, {\bm{g}}_{v'})$ alleviates overfitting compared with directly using ${\bm{g}}_v$ and ${\bm{g}}_v'$. Also, using $s({\bm{g}}_v, {\bm{g}}_{v'})$ makes the final output size much smaller and reduces the number of parameters in the following layer significantly. \subsubsection{Semantic Representation}\hfill \label{sec:semantic_rep} \noindent We use the word embedding ${\bm{w}}_{v}$ of each term $v$ to capture its semantics. For grouping nodes consisting of several item types (\eg, ``Fresh Flowers \& Live Indoor Plants'') and multi-word terms with qualifiers (\eg, ``Fresh Cut Bell Pepper''), we employ dependency parsing to find the noun chunks (``Fresh Flowers'', ``Live Indoor Plants'', and ``Fresh Cut Bell Pepper'') and respective head words (``Flowers'', ``Plants'', and ``Pepper''). Intuitively, $(v, v')$ tends to be related as long as one head word of $v$ is similar to that of $v'$. We thus use the relationship measure $s({\bm{v}}, {\bm{v}}')$ defined in Sec.~\ref{sec:sim_measure} to measure the semantic relationship of the head words: ${\bm{H}}(v, v') = \max_{i, j} s ({\bm{w}}_{\text{head}^i(v)}, {\bm{w}}_{\text{head}^{j}(v')})$, where ${\bm{w}}_{\text{head}^i(v)}$ denotes the word embedding of the i-th head word in the term $v$. Finally, the overall semantic representation ${\bm{S}}(v, v')$ is defined as ${\bm{S}}(v, v') = [{\bm{H}}(v, v'), {\bm{w}}_v, {\bm{w}}_{v'}]$, where ``,'' denotes the concatenation operation. \subsubsection{Lexical Representation}\hfill \label{sec:lexical_rep} \noindent String-level measures prove to be very effective in hypernymy detection~\cite{bansal2014structured,bordea2016semeval,gupta2017taxonomy,mao2018end}. For online catalog taxonomies\xspace, we also find many cases where lexical similarity provides strong signals for hypernymy identification. For example, ``Black Tea'' is a hyponym of ``Tea'' and ``Fresh Packaged Green Peppers'' is a sibling of ``Fresh Packaged Orange Peppers''. Therefore, we take the following lexical features~\cite{mao2018end} to measure the lexical relationship between term pairs: \emph{Ends with}, \emph{Contains}, \emph{Suffix match}, \emph{Longest common substring}, \emph{Length difference}, and \emph{Edit distance}. Values in each feature are binned by range and each bin is mapped to a randomly initialized embedding, which would be updated during model training. We denote the set of lexical features by ${\mathcal{M}}$ and compute lexical representation as the concatenation of the lexical features: ${\bm{L}}(v, v') = [{\bm{L}}_i(v, v')]_{ i \in {\mathcal{M}} }$. \subsubsection{Heterogeneous Representation}\hfill \noindent For each term pair $(v, v')$, we generate a heterogeneous term pair representation ${\bm{R}}(v, v')$ by combining the representations detailed above. ${\bm{R}}(v, v')$ captures several orthogonal aspects of the term pair relationship, which contribute to hypernymy detection in a complementary manner (Sec.~\ref{sec:feat_ablation}). To summarize, the structural\xspace representation models the core taxonomy structure as well as underlying query-item-taxonomy interactions, whilst the semantic and lexical representations capture the distributional and surface information of the term pairs, respectively. We further calculate $s({\bm{v}}, {\bm{v}}')$ between the graph embedding ${\bm{g}}_v$ (${\bm{g}}_v'$) of one term and the word embedding ${\bm{w}}_{v'}$ (${\bm{w}}_{v}$ ) of the other term in the term pair, which measures the relationship of the term pair in different forms and manifests improved performance. Formally, the heterogeneous term pair representation ${\bm{R}}(v, v')$ is defined as follows. \begin{equation*} {\bm{R}}(v, v')\! =\! [s({\bm{g}}_v, {\bm{g}}_{v'}), s({\bm{w}}_v, {\bm{g}}_{v'}), s({\bm{g}}_v, {\bm{w}}_{v'}), {\bm{S}}(v, v'), {\bm{L}}(v, v')]. \end{equation*} \subsubsection{Model Training and Inference}\hfill \noindent Similar to prior works~\cite{shwartz2016improving,mao2018end}, we feed ${\bm{R}}(v, v')$ into a two-layer feed-forward network and use the output after the sigmoid function as the probability of hypernym relationship between $v$ and $v'$. To train the term attachment module, we permute all the term pairs $(v_i, v_j)$ in $V$ as training samples and utilize the existing hypernym pairs $R$ on $T$ for self-supervision -- the pairs in $R$ are regarded as positive samples and other pairs are negative. The heterogeneous term pair representation, including the structural representation, is learned in an end-to-end fashion. We use binary cross-entropy loss as the objective function due to the classification formulation. An alternative formulation is to treat term attachment as a hierarchical classification problem where the positive labels are all the ancestors of the term (instead of only its parent). We found, however, that hierarchical classification does not outperform standard classification and thus opt for the simpler formulation following~\cite{wang2014hierarchical,bansal2014structured}. For inference, we choose $v_i \in V$ with the highest probability among all the permuted term pairs $(v_i, v')$ as the predicted hypernym of $v'$. \section{Experiments} In this section, we examine the effectiveness of \textsc{Octet}\xspace via both automatic and human evaluations. We first conduct experiments on term extraction (Sec.~\ref{sec:term_extract_exp}) and term attachment (Sec.~\ref{sec:term_attach_exp}) individually, and then perform an end-to-end open-world evaluation for \textsc{Octet}\xspace (Sec.~\ref{sec:e2e_exp}). Finally, we carefully analyze the performance of \textsc{Octet}\xspace via framework ablation and case studies (Sec.~\ref{sec:analysis}). \subsection{Evaluation on Term Extraction} \label{sec:term_extract_exp} \subsubsection{Evaluation Setup.}\hfill \label{sec:term_extract_setup} \noindent We take the \textit{Grocery \& Gourmet Food} taxonomy (2,163 terms) on Amazon.com as the major testbed for term extraction. We design three different evaluation setups with closed-world or open-world assumption as follows. \start{Closed-world Evaluation.} We first conduct a closed-world evaluation that holds out a number of terms on the core taxonomy $T$ as the virtual $V'$. In this way, we can ensure that the test set follows a similar distribution as the training set and the evaluation can be done automatically. Specifically, we match the terms on $T$ with the titles of active items belonging to \textit{Grocery \& Gourmet Food} (2,995,345 in total).\footnote{We also observed positive results on term extraction from user queries at Amazon.com but omit the results in the interest of space.} 948 of the 2,163 terms are mentioned in at least one item title and 948,897 (item title, term) pairs are collected. We split the pairs by the 948 matched terms into training set $V$ and test set $V'$ with a ratio of 80\% / 20\% and evaluate term recall on the unseen set $V'$. Splitting the pairs by terms (instead of items) ensures that $V$ and $V'$ have no overlap, which is much more challenging than typical named entity recognition (NER) tasks but resembles the real-world use cases for online catalog taxonomy\xspace enrichment. \start{Open-world Evaluation.} Open-world evaluation tests on new terms that do not currently exist in $T$, which is preferable since it evaluates term extraction methods in the same scenario as in production. The downside is that it requires manual annotations as there are no labels for the newly extracted terms. Therefore, we ask experts and workers on Amazon Mechanical Turk (MTurk) to verify the quality of the new terms. As we would like to take new terms with high confidence for term attachment, we ask our taxonomists to measure the precision of top-ranked terms that each method is most confident at. The terms that are already on the core taxonomy $T$ are excluded and the top 100 terms of each compared method are carefully verified. To evaluate from the average customers' perspective, we sample 1,000 items and ask MTurk workers to extract the item types in the item titles. Different from expert evaluation, items are used as the unit for evaluation rather than terms. Precision and recall, weighted by the votes of the workers, are measured. More details of crowdsourcing are provided in App.~\ref{app:crowdsourcing}. \start{Baseline Methods.} For the evaluation on term extraction, we compare with two approaches widely used for taxonomy construction, namely noun phrase (NP) chunking and AutoPhrase~\cite{shang2018automated}. Pattern-based methods~\cite{liu2019user} and classification-based methods with simple n-gram and click count features~\cite{wang2014hierarchical} perform poorly in our preliminary experiments and are thus excluded. More details and discussions of the baselines are provided in App.~\ref{app:baseline}. \subsubsection{Evaluation Results}\hfill \noindent For closed-world automatic evaluation, we calculate recall@K and show the comparison results in Fig.~\ref{fig:term_eval}~{\em (Left)}. We observe that \textsc{Octet}\xspace consistently achieves the highest recall@K on the held-out test set. The overall recall of all compared methods, however, is relatively low. Nevertheless, we argue that the low recall is mainly due to the wording difference between the terms in the core taxonomy $T$ and item titles. As we will demonstrate in the open-world evaluation below, many extracted terms are valid but not on $T$, which also confirms that $T$ is very sparse and incomplete. For open-world expert evaluation, we examine the terms each method is most confident at. In AutoPhrase~\cite{shang2018automated}, each extracted term is associated with a confidence score. In NP chunking and \textsc{Octet}\xspace, we use the frequency of extracted terms (instead of the raw frequency via string match) as their confidence score. As shown in Fig.~\ref{fig:term_eval}~{\em (Right)}, \textsc{Octet}\xspace achieves very high precision@K (0.91 when K=100), which indicates that the newly extracted terms not found on the core taxonomy are of high quality according to human experts and can be readily used for term attachment. The compared methods, however, perform much worse on the top-ranked terms. In particular, the performance of NP chunking degenerates very quickly and only 27 of its top 100 extracted terms are valid. We further show examples of the extracted terms in Table~\ref{table:term_example}. As one can see, NP chunking extracts many terms that are either not item types (\eg, ``Penzeys Spices'' is a company and ``No Sugar'' is an attribute) or less specific (\eg, ``Whole Bean'' Coffee). AutoPhrase extracts some terms that are not of the desired type. For example, ``Honey Roasted'' and ``American Flag'' are indeed high-quality phrases that appear in the item titles but not valid item types. In contrast, \textsc{Octet}\xspace achieves very high precision on the top-ranked terms while ensuring that the extracted terms are of the same type as existing terms on the core taxonomy, which empirically verifies the superiority of formulating term extraction for online catalog taxonomy\xspace enrichment as sequence labeling. \begin{figure}[t] \includegraphics[width=.96\linewidth]{fig/term_eval} \vspace{-.3cm} \caption{Closed-world automatic evaluation on term recall and open-world expert evaluation on term precision.} \label{fig:term_eval} \vspace{-.25cm} \end{figure} \begin{table}[t] \caption{Examples of top-ranked terms extracted by each approach. Valid terms for item types are marked in bold.} \label{table:term_example} \vspace*{-.3cm} \centering \scalebox{.82}{ \begin{tabular}{p{2.2cm}p{2.6cm}p{2.6cm}} \toprule \textbf{NP Chunking} & \textbf{AutoPhrase}~\cite{shang2018automated} & \textbf{\textsc{Octet}\xspace}\\ \midrule \textbf{dark chocolate}, whole bean, penzeys spices, \textbf{extra virgin olive oil}, net wt, a hint, no sugar & \textbf{almond butter}, honey roasted, \textbf{hot cocoa}, \textbf{tonic water}, \textbf{brown sugar}, \textbf{curry paste}, american flag & \textbf{coconut flour}, \textbf{ground cinnamon}, \textbf{red tea}, \textbf{ground ginger}, \textbf{green peas}, sweet leaf, \textbf{coconut syrup} \\ \bottomrule \end{tabular} } \vspace*{-.25cm} \end{table} Finally, we show the results of open-world crowdsourcing evaluation in Table~\ref{table:extract_mturk}. \textsc{Octet}\xspace again achieves much higher precision and F1 score than the baseline methods. AutoPhrase obtains higher recall as we found that it tends to extract multiple terms in each sample, whereas there is usually one item type. The recall of all the compared methods is still relatively low, which is possibly due to the conciseness and noise in the item titles (recall examples in Fig.~\ref{fig:framework}) and leaves much space for future work. \begin{table}[t] \caption{Performance comparison in the open-world crowdsourcing evaluation on 1,000 sampled items. \textsc{Octet}\xspace achieves significantly higher precision and best F1 score. } \label{table:extract_mturk} \vspace*{-.3cm} \centering \scalebox{.95}{ \begin{tabular}{l cc c} \toprule \textbf{Method} & \textbf{Precision} & \textbf{Recall} & \textbf{F1} \\ \midrule NP Chunking & 12.3 & 20.4 & 15.4 \\ AutoPhrase~\cite{shang2018automated} & 20.9 & \textbf{41.3} & 27.8 \\ \textsc{Octet}\xspace & \textbf{87.5} & 24.9 & \textbf{38.8} \\ \bottomrule \end{tabular} } \vspace*{-.3cm} \end{table} \subsection{Evaluation on Term Attachment} \label{sec:term_attach_exp} \subsubsection{Evaluation Setup.}\hfill \noindent For term attachment, we also conduct both closed-world and open-world evaluations, which involves ablating the core taxonomy $T$ and attaching newly extracted terms, respectively. In contrast, most of prior studies~\cite{bansal2014structured,jurgens2016semeval,mao2018end} only perform closed-world evaluation. \start{Closed-world Evaluation.} We take four taxonomies actively used in production as the datasets: \textit{Grocery \& Gourmet Food}, \textit{Home \& Kitchen}, and \textit{Beauty \& Personal Care} taxonomies at Amazon.com, and the \textit{Business Categories} at Yelp.com.\footnote{The taxonomies are available online. We use five-month user behavior logs on Amazon.com for structural\xspace representation and do not leverage user behavior on Yelp.com due to accessibility. See App.~\ref{app:repro} for more details on data availability.} \textit{Amazon Grocery \& Gourmet Food} is used for framework analysis unless otherwise stated. As the taxonomies are used in different domains and constructed according to their own business needs, they exhibit a wide spectrum of characteristics and almost have no overlap. Considering the real-world use cases where fine-grained terms are missing, we hold out the leaf nodes as the new terms $V'$ to be attached as in~\cite{jurgens2016semeval}. We split $V'$ into training, development, and test sets with a ratio of 64\% / 16\% / 20\%, respectively. Detailed statistics of the datasets can be found in Table~\ref{table:taxo_stats}. Note that if we regard term attachment as a classification problem, each class would have very few training samples (\eg, 1193 / 298 $\approx$ 4 in \textit{Amazon Grocery \& Gourmet Food}), which calls for a significant level of model generalizability. \begin{table}[ht] \caption{Taxonomy statistics for term attachment.} \centering \label{table:taxo_stats} \vspace*{-.3cm} \scalebox{.8}{ \begin{tabular}{l cccc c} \toprule \textbf{Taxonomy} & $|\textbf{V}|$ & $|\textbf{V}'|$ & $|\textbf{V}'_{\text{Train}}|$ & $|\textbf{V}'_{\text{Dev}}|$ & $|\textbf{V}'_{\text{Test}}|$ \\ \midrule Amazon Grocery \& Gourmet Food & 298 & 1,865 & 1,193 & 299 & 373 \\ Amazon Home \& Kitchen & 338 & 1,410 & 902 & 226 & 282 \\ Amazon Beauty \& Personal Care & 109 & 454 & 290 & 73 & 91 \\ Yelp Business Categories & 84 & 920 & 588 & 148 & 184 \\ \bottomrule \end{tabular} } \vspace*{-.2cm} \end{table} \start{Open-world Evaluation.} We conduct an open-world evaluation for term attachment on \textit{Amazon Grocery \& Gourmet Food}. Specifically, we ask the taxonomists to identify valid new terms among those discovered in the term extraction stage with frequency greater than 20. 106 terms are thus labeled as valid. We then ask the taxonomists to attach the 106 terms manually to the core taxonomy as ground truth and evaluate systems on these new terms with the same criteria as in the closed-world evaluation. \start{Evaluation Metrics.} We use Edge-F1 and Ancestor-F1~\cite{mao2018end} to measure the performance of term attachment. \textbf{Edge-F1} compares the predicted edge $(v, v')$ with the gold edge $(p(v'), v')$, \ie, whether $v = p(v')$. We use $P_{\text{Edge}}$, $R_{\text{Edge}}$, and $F1_{\text{Edge}}$ to denote the precision, recall, and F1-score, respectively. In particular, $P_{\text{Edge}} = R_{\text{Edge}} = F1_{\text{Edge}}$ if the number of predicted edges is the same as gold edges, \ie, when all the terms in $V'$ are attached. \textbf{Ancestor-F1} is more relaxed than Edge-F1 as it compares all the term pairs $(v_\text{sys}, v')$ with $(v_\text{gold}, v')$, where $v_\text{sys}$ represents the terms along the system predicted path (ancestors) to the root node, and $v_\text{gold}$ denotes those terms on the gold path. Similarly, we denote the ancesor-based metrics as $P_{\text{Ancestor}} = \frac{| v_{\text{sys}} \wedge v_{\text{gold}} |} {| v_{\text{sys}} |}$ and $R_{\text{Ancestor}} = \frac{| v_{\text{sys}} \wedge v_{\text{gold}} |} {| v_{\text{gold}} |}$. \start{Baseline Methods.} As discussed earlier, there are few existing methods for taxonomy enrichment. MSejrKu~\cite{schlichtkrull2016msejrku} is the winning method in the SemEval-2016 Task 14~\cite{jurgens2016semeval}. {HiDir}~\cite{wang2014hierarchical} is the state-of-the-art method for online catalog taxonomy\xspace enrichment. In addition, we compare with the substring method {Substr}~\cite{bordea2016semeval}, and {I2T} that finds one's hypernym by examining where its related items are assigned to. Two na\"ive baselines are also tested to better understand the difficulty of the task following convention~\cite{bansal2014structured,jurgens2016semeval}, where \textit{Random} attaches $v' \in V'$ randomly to $T$ and \textit{Root} attaches every term to the root node of $T$. More details of the baselines are in App.~\ref{app:baseline}. \subsubsection{Evaluation Results}\hfill \noindent We first evaluate different methods under the closed-world assumption (Tables~\ref{table:grocery_main} \& ~\ref{table:attachment_additional}). We observe that the Edge-F1 of two na\"ive baselines is very low since there are hundreds of $v \in V$ as candidates. The performance of I2T is similar to Substr but still far from satisfactory, implying that there might be noise in the matching between $V'$ and $I$, and the associations between $I$ and $V$. HiDir~\cite{wang2014hierarchical} and MSejrKu~\cite{schlichtkrull2016msejrku} achieve better performance than other baselines, especially in Edge-F1, while \textsc{Octet}\xspace outperforms all the compared methods by a large margin on both development and test sets across all of the four domains. \begin{table}[t] \caption{Comparison results of closed-world evaluation on \textit{Amazon Grocery \& Gourmet Food}.} \label{table:grocery_main} \vspace*{-.3cm} \centering \scalebox{.88}{ \begin{tabular}{l cccc} \toprule \multirow{2}{*}{\textbf{Method}} & \multicolumn{2}{c}{\textbf{Dev}} & \multicolumn{2}{c}{\textbf{Test}}\\ & Edge-F1 & Ancestor-F1 & Edge-F1 & Ancestor-F1\\ \midrule Random~\cite{bansal2014structured,jurgens2016semeval} & 0.3 & 30.3 & 0.5 & 31.2 \\ Root & 0.3 & 41.1 & 0 & 41.8 \\ I2T & 10.0 & 50.5 & 9.9 & 50.7 \\ Substr~\cite{bordea2016semeval} & 8.4 & 49.9 & 10.7 & 52.9 \\ HiDir~\cite{wang2014hierarchical} & 42.5 & 66.8 & 40.5 & 66.4 \\ MSejrKu~\cite{schlichtkrull2016msejrku} & 58.9 & 80.6 & 53.1 & 76.7 \\ \textsc{Octet}\xspace & \textbf{64.9} & \textbf{85.2} & \textbf{62.5} & \textbf{84.2} \\ \bottomrule \end{tabular} } \vspace*{-.3cm} \end{table} \begin{table}[t] \caption{Closed-world evaluation in different domains. Only competitive baseline methods that perform well on \textit{Amazon Grocery \& Gourmet Food} are listed.} \label{table:attachment_additional} \centering \vspace*{-.3cm} \scalebox{.8}{ \begin{tabular}{ll cc} \toprule \textbf{Dataset} & \textbf{Method} & \textbf{Edge-F1} & \textbf{Ancestor-F1}\\ \midrule \multirow{3}{*}{Amazon Home \& Kitchen} & HiDir~\cite{wang2014hierarchical} & 46.5 & 76.9 \\ & MSejrKu~\cite{schlichtkrull2016msejrku} & 46.0 & 74.1 \\ & \textsc{Octet}\xspace & \textbf{54.4} & \textbf{78.5} \\ \midrule \multirow{3}{*}{Amazon Beauty \& Personal Care} & HiDir~\cite{wang2014hierarchical} & 34.1 & 71.8 \\ & MSejrKu~\cite{schlichtkrull2016msejrku} & 49.5 & 75.0 \\ & \textsc{Octet}\xspace & \textbf{50.6} & \textbf{77.1} \\ \midrule \multirow{3}{*}{Yelp Business Categories} & HiDir~\cite{wang2014hierarchical} & 19.6 & 35.8 \\ & MSejrKu~\cite{schlichtkrull2016msejrku} & 29.9 & 35.7 \\ & \textsc{Octet}\xspace & \textbf{32.6} & \textbf{43.5} \\ \bottomrule \end{tabular} } \vspace*{-.2cm} \end{table} For the open-world evaluation, we compare \textsc{Octet}\xspace with the best performing baselines MSejrKu~\cite{schlichtkrull2016msejrku} and HiDir~\cite{wang2014hierarchical} on the expert-labeled data (Table~\ref{table:attachment_open}). Perhaps unsurprisingly, the performance of each method is lower than that under the closed-world evaluation, since the distributions of the existing terms on $T$ and the newly extracted terms are largely different (shown in Sec.~\ref{sec:term_extract_exp}). \textsc{Octet}\xspace again achieves the best performance thanks to its better generalizability. \begin{table}[t] \caption{Open-world expert evaluation. Note that the seemingly low \textit{absolute} performance is comparable to results on other datasets \cite{bansal2014structured,mao2018end} due to the difficulty of the task.} \label{table:attachment_open} \centering \vspace*{-.3cm} \scalebox{.95}{ \begin{tabular}{l cc} \toprule \textbf{Method} & \textbf{Edge-F1} & \textbf{Ancestor-F1}\\ \midrule HiDir~\cite{wang2014hierarchical} & 28.3 & 59.2 \\ MSejrKu~\cite{schlichtkrull2016msejrku} & 29.3 & 61.2 \\ \textsc{Octet}\xspace & \textbf{30.2} & \textbf{67.5} \\ \bottomrule \end{tabular} } \vspace*{-.3cm} \end{table} \subsection{End-to-End Evaluation} \label{sec:e2e_exp} Besides the individual evaluations on term extraction and term attachment, we perform a novel \textit{end-to-end open-world evaluation} that helps us better understand the quality of the enriched taxonomy by examining errors throughout the entire framework: whether (A) the extracted term is invalid or (B) the term is valid but the attachment is inaccurate. To our knowledge, such an end-to-end evaluation has not been conducted in prior studies. We evaluate \textsc{Octet}\xspace on \textit{Amazon Grocery \& Gourmet Food} using Amazon MTurk. The details of crowdsourcing can be found in App.~\ref{app:crowdsourcing}. In total, \textsc{Octet}\xspace extracts and attaches 2,192 new terms from the item titles described in Sec.~\ref{sec:term_extract_setup}, doubling the size of the existing taxonomy (2,163 terms). As listed in Table~\ref{table:end2end}, only 6.5\% of extracted terms are considered invalid by average customers (MTurk workers). The top-1 edge precision and ancestor precision are relatively low, but they are comparable to the state-of-the-art performance on similar datasets with \textit{clean} term vocabulary \cite{mao2018end}. The neighbor precision, which considers the siblings on the predicted path as correct, is very high (88.1). One can further improve the precision by filtering low-confidence terms or allowing top-k prediction (Sec.~\ref{sec:tradeoff}). \begin{table}[h] \vspace*{-.3cm} \caption{Open-world end-to-end evaluation for \textsc{Octet}\xspace.} \label{table:end2end} \centering \vspace*{-.3cm} \scalebox{.8}{ \begin{tabular}{cc ccc} \toprule \textbf{Error A\%} & \textbf{Error B\%} & \textbf{Edge Prec}& \textbf{Ancestor Prec}&\textbf{Neighbor Prec}\\ \midrule 6.5 & 11.9 & 22.1 & 40.9 & 88.1 \\ \bottomrule \end{tabular} } \vspace*{-.35cm} \end{table} \subsection{Framework Analysis} \label{sec:analysis} \subsubsection{Feature Ablation} \label{sec:feat_ablation} \noindent We analyze the contribution of each representation for the term pair (Table~\ref{table:ablation_feat}). As one can see, only using word embedding (W) does not suffice to identify hypernymy relations while adding the semantics of head words (H) explicitly boosts the performance significantly. Lexical (L) features are very effective and combining lexical representation with semantic representation (L + W + H) brings 17.2 absolute improvement in Edge-F1. The structural information is very useful in that even if we use word embedding (W) as the input of the structural\xspace representation (G), the Edge-F1 improves by 4.8x and the Ancestor-F1 improves by 59.3\% upon W. The full model that incorporates various representations performs the best, indicating that they capture different aspects of the term pair relationship and are complementary to each other. \begin{table}[t] \caption{Ablation study of word embedding (W), head word semantics (H), lexical representation (L), and structural\xspace graph-based representation (G).} \centering \label{table:ablation_feat} \vspace*{-.3cm} \scalebox{.85}{ \begin{tabular}{l cccc} \toprule \multirow{2}{*}{\textbf{Representation}} & \multicolumn{2}{c}{\textbf{Dev}} & \multicolumn{2}{c}{\textbf{Test}}\\ & Edge-F1 & Ancestor-F1 & Edge-F1 & Ancestor-F1\\ \midrule W & 12.0 & 50.4 & 11.0 & 49.7 \\ H & 30.8 & 62.9 & 29.2 & 64.4 \\ W + H & 41.8 & 68.8 & 39.7 & 67.8 \\ L & 48.2 & 74.7 & 42.6 & 70.3 \\ L + W & 57.9 & 79.7 & 52.6 & 76.9 \\ G & 57.5 & 80.3 & 50.9 & 78.6 \\ L + W + G & 63.6 & 82.6 & 56.0 & 79.9 \\ L + W + H & 62.5 & 83.6 & 59.8 & 81.6 \\ L + W + H + G & \textbf{64.9} & \textbf{85.2} & \textbf{62.5} & \textbf{84.2} \\ \bottomrule \end{tabular} } \vspace*{-.2cm} \end{table} \subsubsection{Graph Ablation} \label{sec:graph_ablation} \noindent We analyze different variants regarding the design choices in the structural\xspace representation. As shown in Table~\ref{table:graph_choice}, considering multi-hop relations (\eg, grandparents and siblings) is better than only considering immediate family (\ie, parent and children). The directionality of edges does not have a huge effect on the model performance, although the information of the ancestors tends to be more benefitial for Ancestor-F1 and descendants for Edge-F1. Adding the query-item-taxonomy interactions in the user behavior ($r_2$) in addition to the structure in the core taxonomy further improves model performance, showing the benefits of leveraging user behavior for term attachment. \begin{table}[t] \caption{Comparison of various design choices in the structural\xspace representation. C and P denote Child and Parent. $r_1$, $r_2$, $r_3$ denote structure in the core taxonomy, query-item-taxonomy interactions, and self-loop, respectively.} \label{table:graph_choice} \centering \vspace*{-.3cm} \scalebox{.88}{ \begin{tabular}{c l cc} \cmidrule[0.06em]{2-4} &\textbf{Design Choice} & \textbf{Edge-F1} & \textbf{Ancestor-F1}\\ \cmidrule{2-4} \multirow{2}{*}{\rotatebox[origin=c]{90}{$L$}} &One-hop neighborhood & 50.4 & 75.9\\ &Two-hop neighborhood & \textbf{60.1} & \textbf{83.0}\\ \cmidrule{2-4} \multirow{3}{*}{\rotatebox[origin=c]{90}{$N(v, r_1)$}} &C->P & \textbf{60.1} & 83.0 \\ &C<->P & 59.8 & 83.2 \\ &P->C & 59.3 & \textbf{83.6} \\ \cmidrule{2-4} \multirow{2}{*}{\rotatebox[origin=c]{90}{${\mathcal{R}}$}} &$\{r_1, r_3\}$ & 60.1 & 83.0\\ &$\{r_1, r_2, r_3\}$ & \textbf{62.5} & \textbf{84.2}\\ \cmidrule[0.06em]{2-4} \end{tabular} } \vspace*{-.35cm} \end{table} \subsubsection{Performance Trade-Off} \label{sec:tradeoff} \noindent Precision recall trade-off answers the practical question in production ``how many terms can be attached if a specific precision of term attachment is required'', by filtering predictions with $\max_{v \in V} P(v' \mid v, \Theta) < c$, where $c \in [0, 1]$ is a thresholding constant. As depicted in Fig~\ref{fig:hit_pr} {\em (Left)}, more than 15\% terms can be recalled and attached perfectly. Over 60\% terms can be recalled when an edge precision of 80\% is achieved. We also analyze the performance changes if we relax term attachment to top-k predictions rather than top-1 prediction (as measured in Edge-F1). We observe that more than 95\% gold hypernyms of the query terms are in the top-50 predictions (Fig~\ref{fig:hit_pr} {\em (Right)}), which indicates that \textsc{Octet}\xspace generally ranks the gold hypernyms higher than other candidates even if its top-1 prediction is incorrect. Note that the results in all the previous experiments are regarding term recall equal to 1 (all extracted terms are attached) and Hit@1 (whether the top-1 prediction is correct). \begin{figure}[t] \includegraphics[width=1.01\linewidth]{fig/hit_pr} \vspace*{-.65cm} \caption{The precision recall trade-off {\em (Left)}\xspace and performance of term attachment in Hit@K {\em (Right)}.} \label{fig:hit_pr} \vspace*{-.35cm} \end{figure} \subsubsection{Case Studies} \noindent We inspect correct and incorrect term attachments to better understand model behavior and the contribution of each type of representation. As shown in Table~\ref{table:expand_example}, \textsc{Octet}\xspace successfully predicts ``Fresh Cut Flowers'' as the hypernym of ``Fresh Cut Carnations'', where lexical representation possibly helps with the matching of ``Fresh Cut'' and semantic representation identifies ``Carnations'' is a type of ``Flowers''. When lexical clues are lacking, \textsc{Octet}\xspace can still use semantic representation to recognize that ``Tilapia'' is a type of ``Fresh Fish''. Without structural\xspace representation, \textsc{Octet}\xspace detects that ``Bock Beer'' is closely related to ``Beer'' and ``Ales''. By adding the structural\xspace representation \textsc{Octet}\xspace could narrow down its prediction to the more specific type ``Lager \& Pilsner Beers''. For the wrongly attached terms, \textsc{Octet}\xspace is unconfident in distinguishing ``Russet Potatoes'' from ``Fingerling \& Baby Potatoes'', which is undoubtfully a harder case and requires deeper semantic understanding. \textsc{Octet}\xspace also detects a potential error in the core taxonomy itself as we found the siblings of ``Pinto Beans'' all start with ``Dried'', which might have confused \textsc{Octet}\xspace during training. \begin{table}[ht] \footnotesize \caption{Case studies of term attachment. Correct and incorrect cases are marked in green and red, respectively.} \label{table:expand_example} \vspace*{-.3cm} \centering \scalebox{.87}{ \begin{tabular}{p{2.2cm}p{2.cm}p{4.5cm}} \toprule \textbf{Query Term} & \textbf{Gold Hypernym} & \textbf{Top-3 Predictions}\\ \midrule \colorG{fresh cut carnations} & fresh cut flowers & \colorB{fresh cut flowers}, fresh cut root vegetables, fresh cut \& packaged fruits\\ \midrule \colorG{tilapia} & fresh fish & \colorB{fresh fish}, liquor \& spirits, fresh shellfish \\ \midrule \colorG{bock beers} & lager \& pilsner beers & \textbf{W/O structural\xspace representation:} ales, beer, tea beverages \newline \textbf{Full Model:} \colorB{lager \& pilsner beers}, porter \& stout beers, tea beverages\\ \midrule \colorR{fresh russet potatoes} & fresh potatoes \& yams & fresh fingerlings \& baby potatoes, fresh root vegetables, fresh herbs \\ \midrule \colorR{pinto beans} & dried beans & canned beans, fresh peas \& beans, single herbs \& spices \\ \bottomrule \end{tabular} } \vspace*{-.25cm} \end{table} \section{Related Work} \start{Taxonomy Construction.} \cite{shen2012graph} proposed a graph-based approach to attach new concepts to Wikipedia categories. \cite{jurgens2015reserating} enriched WordNet by finding terms from Wiktionary and attaching them via rule-based patterns. A concurrent study \cite{shen2020taxoexpan} also leverages GNNs for taxonomy enrichment. However, the features used in prior methods~\cite{shen2012graph,jurgens2015reserating,shen2018hiexpan,liu2019user} are designed either for specific taxonomies or for text-rich domains whereas \textsc{Octet}\xspace is robust to short texts and generally applicable to various online domains. For online catalog taxonomies\xspace, \cite{wang2014hierarchical} extracted terms from search queries and formulated taxonomy enrichment as a hierarchical Dirichlet process, where each node is represented by a uni-gram language model of its associated items. \cite{liu2019user} used patterns to extract new concepts in the queries and online news, and built a topic-concept-instance taxonomy with human-labeled training set. In contrast, \textsc{Octet}\xspace is self-supervised and utilizes heterogeneous sources of information. \start{Term Extraction.} \cite{kozareva2010semi} used Hearst patterns~\cite{hearst1992automatic} to extract new terms from the web pages. \cite{shen2018hiexpan,zhang2018taxogen} used AutoPhrase~\cite{shang2018automated} to extract keyphrases in general-purpose corpora. These methods, however, are inapplicable or ineffective for short texts like item titles. On the other hand, many prior studies~\cite{bansal2014structured,panchenko2016taxi,jurgens2016semeval,bordea2016semeval,mao2018end} made a somewhat unrealistic assumption that one clean vocabulary is given as input and focused primarily on hypernymy detection. Another plausible alternative is to treat entire user queries as terms rather than perform term extraction~\cite{wang2014hierarchical}, which results in a low recall. In contrast, \textsc{Octet}\xspace employs a sequence labeling model designed for term extraction from online domains with self-supervision. \start{Hypernymy Detection.} Pattern-based hypernymy detection methods~\cite{hearst1992automatic,snow2005learning,kozareva2010semi,panchenko2016taxi,nakashole2012patty} consider the lexico-syntactic patterns between the co-occurrences of term pairs. They achieve high precision in text-rich domains but suffer from low recall and also generate false positives in domains like e-commerce. Distributional methods~\cite{fu2014learning,rimell2014distributional,yu2015learning,tuan2016learning,shwartz2016improving} utilize the contexts of each term for semantic representation learning. Unsupervised measures such as symmetric similarity~\cite{lin1998information} and distributional inclusion hypothesis~\cite{weeds2004characterising,chang2017unsupervised} are also proposed, but not directly applicable to online catalog taxonomy\xspace enrichment as there are \textit{grouping nodes} in the online catalog taxonomies\xspace like ``Dairy, Cheese \& Eggs'' and ``Flowers \& Gifts'' curated by taxonomists for business purposes, which might not exist in any form of text corpora. In \textsc{Octet}\xspace, heterogeneous sources of signals are leveraged to tackle the lack of text corpora and grouping nodes are captured by head word semantics. \section{Conclusion} In this paper, we present a self-supervised end-to-end framework for online catalog taxonomy\xspace enrichment that considers heterogeneous sources of representation and does not involve additional human effort other than the existing core taxonomies to be enriched. We conduct extensive experiments on real-world taxonomies used in production and show that the proposed framework consistently outperforms state-of-the-art methods by a large margin under both automatic and human evaluations. In the future, we will explore the feasibility of joint learning of online catalog taxonomy\xspace enrichment and downstream applications such as recommendation and search. \section*{Acknowledgment} We thank Jiaming Shen, Jun Ma, Haw-Shiuan Chang, Giannis Karamanolakis, Colin Lockard, Qi Zhu, and Johanna Umana for the valuable discussions and feedback. \section{Reproducibility} \label{app:repro} \subsection{Implementation Details} We use fastText~\cite{bojanowski2017enriching} as the word embedding ${\bm{w}}_v$ in order to capture sub-word information. ${\bm{w}}_v$ is fixed to avoid semantic shift for the inference of unseen terms $V'$. All the terms $v$ are lowercased and concatenated with underscores if there are multiple words. For structural\xspace representation, we use the Deep Graph Library\footnote{https://www.dgl.ai/} for the implementation of GNN-based models. The number of layers $L$ is set to 2 (two-hop neighbors are considered) and the normalization constant $c_{v, r}$ is 1. We sample $N=5$ neighbors instead of using all the neighbors $N(v)$ for information aggregation. Node embedding ${\bm{h}}^{l}_v$ is of size 300, also initialized by the fastText embedding. ${\bm{W}}^l$ is of size 300 $\times$ 300. All of the lexical string-level features ${\bm{L}}_i(v, v')$ are randomly initialized and have an embedding size of 10. ${\bm{W}}_1$ and ${\bm{W}}_2$ are of size 1 $\times$ 100 and 100 $\times\ |{\bm{R}}(v, v')|$, respectively. For \textit{relationship measure} involving the output of the GNNs, $s({\bm{v}}, {\bm{v}}')$ measures the $L^1$ Norm, $L^2$ Norm, and cosine similarity between the embeddings of a term pair. For that between head words, $s({\bm{v}}, {\bm{v}}')$ measures the cosine similarity of their corresponding word embeddings. We use Adam as the optimizer with initial learning rate 1e-4 and choose the best performing model according to the development set. \subsection{Data Availability} The taxonomies used in the experiments are available online. The taxonomies on Amazon.com can be obtained by scraping public webpages (refer to Fig.~\ref{fig:coffee_department}) or registering as a vendor. The Yelp taxonomy is accessible at \url{www.yelp.com/developers/documentation/v3/all_category_list}. The user behavior logs are mainly used for the GNN-based structural\xspace representation learning. We use five-month user behavior logs in the target domain on Amazon.com and do not leverage user behavior on Yelp.com due to accessibility. All of the experiments and framework analysis without the structural\xspace representation can be reproduced. While each taxonomy used in the experiments is seemingly ``small'', it is \textit{real} and quite big (2K+ nodes) for a single domain (Grocery). \textsc{Octet}\xspace is easily applicable to other domains (Home, Electronics, ...), which also contain thousands of categories; they collectively form a taxonomy of 30K+ nodes. There are also datasets with similar or smaller size (\eg, 187 to 1386 nodes in \cite{zhang2016learning}, and 50 to 100 nodes in \cite{mao2018end, bansal2014structured}). Our setup is more general than SemEval-2016 Task 14 \cite{jurgens2016semeval} and can be simplified to it if we ignore user behavior. \section{Baseline} \label{app:baseline} \subsection{Baseline in Term Extraction} NP chunking is one of the popular choices for general-purpose entity extraction~\cite{ren2015clustype}. We conduct NP chunking via spaCy\footnote{https://spacy.io/}, which performs dependency parsing on the sentences and finds noun phrases in them. No task-specific input (\eg, a list of positive terms) is required or supported for the training of NP chunking. Post-processing, including removing the terms containing punctuation or digits, is used to filter clearly invalid terms from the results. AutoPhrase~\cite{shang2018automated} is the state-of-the-art phrase mining method widely used in previous taxonomy construction approaches~\cite{shen2018hiexpan,zhang2018taxogen}. We replace the built-in Wikipedia phrase list that AutoPhrase uses for distant supervision with the terms $V$ on the core taxonomy $T$, as we find that it performs better than appending $V$ to the Wikipedia phrase list. Note that AutoPhrase uses exactly the same resources as \textsc{Octet}\xspace for distant supervision. In terms of methodology, AutoPhrase~\cite{shang2018automated} focuses more on the corpus-level statistics and performs phrasal segmentation instead of sequence labeling. Pattern-based methods~\cite{liu2019user} are ineffective in our scenario due to the lack of clear patterns in the item profiles and user queries. The classification-based method in~\cite{wang2014hierarchical} only works for term extraction from queries and also performs poorly, possibly because~\citet{wang2014hierarchical} treats the whole query as one term, which results in low recall. \subsection{Baseline in Term Attachment} HiDir~\cite{wang2014hierarchical} conducts hypernymy detection with the assumption that the representation of a taxonomy node is the same as its parent node, where one node is represented by its associated items. Since we do not have \textit{description sentences} as in SemEval-2016 Task 14~\cite{jurgens2016semeval}, most of MSejrKu's features are inapplicable and we thus replace its features with those used in \textsc{Octet}\xspace except for the structural\xspace representation. we found that such changes improve MSejrKu's performance. Substr~\cite{bordea2016semeval} is the sub-string baseline used in SemEval-2016 Task 13~\cite{bordea2016semeval}. It is shown that Substr, which regards A as B's hypernym if A is a substring of B (\eg, ``Coffee'' and ``Ground Coffee''), outperforms most of the systems in the SemEval-2016 competition on automatic taxonomy construction~\cite{bordea2016semeval}. I2T matches $v'$ with item titles and finds the taxonomy nodes these items $I_{v'}$ are associated with. The final prediction of I2T is made by majority voting of the associated nodes where the items $I_{v'}$ are assigned to. \section{Crowdsourcing} \label{app:crowdsourcing} Crowdsourcing is a reasonable choice in our scenario because our terms are common words (\eg, ``coffee'' and ``black coffee'') without complicated relations that require domain expertise (\eg, ``sennenhunde'' and ``entlebucher'' in WordNet). \subsection{Crowdsourcing for Open-world Term Extraction Evaluation} For crowdsourcing evaluation in term extraction, each item is assigned to 5 workers and only item types labeled by at least 2 workers are considered valid. Links to the corresponding pages on Amazon.com are also provided to the workers. \subsection{Crowdsourcing for End-to-End Evaluation} We use crowdsourcing on MTurk for the end-to-end evaluation since expert evaluation is difficult to scale. We assign each term to 4 MTurk workers for evaluation. One critical problem of using crowdsourcing for end-to-end evaluation is that we can not ask MTurk workers to find the hypernym of each new term directly, as there are thousands of terms $V$ on the core taxonomy $T$ while the workers are unfamiliar with the taxonomy structure. Alternatively, we ask the workers to verify the precision of \textsc{Octet}\xspace: we provide the predicted hypernym of \textsc{Octet}\xspace and the ancestors along the predicted path to the root as the candidates. We also include in the candidates one sibling term at each level along the predicted path. The workers are required to select the hypernym(s) of the query term $v'$ among the provided candidates. In this way, we can estimate how accurate the term attachment is from the average customers' perspective. Two other options, ``\textit{The query term is not a valid type}'' and ``\textit{None of above are hypernyms of the query term}'', are also provided, which corresponds to error types (A) and (B), respectively (refer to Sec.~\ref{sec:e2e_exp}). \section{Task Formulation} \start{Notations.} We define a taxonomy $T = (V, R)$ as a tree-structured hierarchy with term set $V$ and edge set $R$. A term $v \in V$ can be either single-word or multi-word (\eg, ``Yogurt'' and ``Herbal Tea''). The edge set $R$ indicates the Is-A relationship between $V$ (hypernym pairs such as ``Coffee'' -> ``Ground Coffee''). The online catalog taxonomies\xspace, which can be found in almost all online shopping websites such as Amazon.com and eBay, and business directory services like Yelp.com, maintain the hypernym relationship of their items (\eg, products or businesses). We define a \textit{core taxonomy} as a pre-given partial taxonomy that is usually manually curated and stores the high-level concepts in the target domain. We denote user behavior logs as $B = (Q, I)$, which record the user queries $Q$ in a search engine and corresponding clicked items $I$. The items $I$ are represented by item profiles such as titles and descriptions. $I$ is associated with (assigned to) nodes $V$ according to their types by item categorization (done by vendors or algorithms). \start{Problem Definition.} Let $T = (V, R)$ be a core taxonomy and $B = (Q, I)$ be user behavior logs, the {\em taxonomy enrichment} problem extends $T$ to $\bar{T} = (\bar{V}, \bar{R})$ with $\bar{V} = V \cup V'$, $\bar{R} = R \cup R'$, where $V'$ contains new terms extracted from $Q$ and $I$, and $R'$ contains pairs $(v, v'), v\in V, v' \in V'$, representing that $v$ is a hypernym of $v'$. \start{Non-Goals.} Although \textsc{Octet}\xspace works for terms regardless of their granularity, we keep $T$ unchanged as in~\cite{wang2014hierarchical,jurgens2016semeval} since we would like to keep the high-level expert-curated hypernym pairs intact and focus on discovering fine-grained terms. Following convention~\cite{jurgens2016semeval}, we do not identify the hypernym relationship between newly discovered types ($(v_1', v_2')$, $v_1', v_2' \in V'$). \textsc{Octet}\xspace already makes an important first step to solve the problem as our analysis shows that over 80\% terms are leaf nodes in the core taxonomy. \section{The \textsc{Octet}\xspace Framework} In this section, we first give a framework overview of the learning goal of term extraction and term attachment. We then elaborate on how to employ self-supervision of the core taxonomy to conduct term extraction via sequence labeling (Sec.~\ref{sec:term_extract}) and term attachment via GNN-based heterogeneous representation (Sec.~\ref{sec:term_attach}). \subsection{Framework Overview} \textsc{Octet}\xspace consists of two inter-dependent stages: \textbf{term extraction} and \textbf{term attachment}, which, in a nutshell, solves the problem of ``which terms to attach'' and ``where to attach'', respectively. Formally, the term extraction stage extracts the new terms $V'$ (with the guidance from $V$) that are to be used for enriching $T$ to $\bar{T}$. The term attachment stage takes $T$ and $V'$ as well as the sources of $V'$ (\ie, $Q$ and $I$) as input and attaches each new term $v' \in V'$ to a term $v \in V$ in $T$, forming the new edge set $R'$. \textsc{Octet}\xspace is readily deployable to different domains with no human effort, \ie, with no additional resources other than $T$, $Q$, $I$, and their interactions. Fig.~\ref{fig:framework} shows an overview of \textsc{Octet}\xspace. At a high level, we regard term extraction as a sequence labeling task and employ a sequence labeling model with distant supervision from $V$ to extract new terms $V'$. We show in Sec.~\ref{sec:term_extract_exp} that such a formulation is beneficial for the term extraction in online catalog taxonomy\xspace enrichment. For term attachment, existing hypernym pairs $R$ on $T$ are used as self-supervision. Structure of the core taxonomy as well as interactions among queries, items, and taxonomy nodes are captured via graph neural networks (GNNs) for structural\xspace representation learning. Meanwhile, the lexical semantics of the terms is employed and provides complementary signals for hypernymy detection (Sec.~\ref{sec:feat_ablation}). Each new term $v' \in V'$ is attached to one existing term $v \in V$ on $T$ based on the term pair representation. \subsection{Term Extraction Learning}\label{sec:term_extract} Term extraction extends $T=(V, R)$ with new terms $V'$. Extracting new terms from item profiles $I$ and user queries $Q$ has two benefits. First, they are closely related to the dynamics of customer needs, which is essential for the enrichment of user-oriented online catalog taxonomies\xspace and their deployment in production. Second, extraction from $I$ and $Q$ naturally connects type terms to user behavior, preparing rich signals required for generating structural\xspace term representations during term attachment. We propose to treat \textit{term extraction for online catalog taxonomy\xspace enrichment} as a sequence labeling task. Tokens in the text are labeled with the BIOE schema where each tag represents the beginning, inside, outside, and ending of a chunk, respectively. Instead of collecting expensive human annotations for training~\cite{zheng2018opentag}, we propose to adopt distant supervision by using the existing terms $V$ as self-supervised labels. Specifically, we find in $Q$ and $I$ the mentions of $V$ and label those mentions as the desired terms to be extracted. For example, item ``Golden State Fruit Pears to Compare Deluxe Gift'' with associated taxonomy node ``Pears'' will be labeled as "O O O B O O O O" for model learning. This approach has several advantages. First, unlike unsupervised term extraction methods~\cite{kozareva2010semi}, we train a sequence labeling model to ensure that only the terms in the same domain as the existing terms $V$ are extracted. Second, sequence labeling is more likely to extract terms of the desired type while filtering terms of undesired types (such as the brand or flavor of items) by inspecting the sentence context, which typical context-agnostic term extraction methods~\cite{liu2015mining,shang2018automated} fail to do. We train a BiLSTM-CRF model~\cite{panchendrarajan2018bidirectional} to fulfill term extraction in \textsc{Octet}\xspace. Briefly speaking, each token in the text is represented by its word embedding, fed into a bidirectional LSTM layer for contextualized representation. Then, tag prediction is conducted by a conditional random field (CRF) layer operating on the representation of the current token and the previous tag. A similar model architecture can be found in~\citet{zheng2018opentag}. Note that distant supervision may inevitably introduce noises in the labels. Nevertheless, we show in Sec.~\ref{sec:term_extract_exp} that \textsc{Octet}\xspace obtains superior performance in term extraction (precision@100=0.91). % In addition, \textsc{Octet}\xspace is likely to have low confidence in attaching incorrectly extracted terms, allowing further filtering with threshold setting during term attachment (Sec.~\ref{sec:tradeoff}). \section{Experiments} In this section, we examine the effectiveness of \textsc{Octet}\xspace via both automatic and human evaluations. We first conduct experiments on term extraction (Sec.~\ref{sec:term_extract_exp}) and term attachment (Sec.~\ref{sec:term_attach_exp}) individually, and then perform an end-to-end open-world evaluation for \textsc{Octet}\xspace (Sec.~\ref{sec:e2e_exp}). Finally, we carefully analyze the performance of \textsc{Octet}\xspace via framework ablation and case studies (Sec.~\ref{sec:analysis}). \subsection{Evaluation on Term Extraction} \label{sec:term_extract_exp} \subsubsection{Evaluation Setup.}\hfill \label{sec:term_extract_setup} \noindent We take the \textit{Grocery \& Gourmet Food} taxonomy (2,163 terms) on Amazon.com as the major testbed for term extraction. We design three different evaluation setups with closed-world or open-world assumption as follows. \start{Closed-world Evaluation.} We first conduct a closed-world evaluation that holds out a number of terms on the core taxonomy $T$ as the virtual $V'$. In this way, we can ensure that the test set follows a similar distribution as the training set and the evaluation can be done automatically. Specifically, we match the terms on $T$ with the titles of active items belonging to \textit{Grocery \& Gourmet Food} (2,995,345 in total).\footnote{We also observed positive results on term extraction from user queries at Amazon.com but omit the results in the interest of space.} 948 of the 2,163 terms are mentioned in at least one item title and 948,897 (item title, term) pairs are collected. We split the pairs by the 948 matched terms into training set $V$ and test set $V'$ with a ratio of 80\% / 20\% and evaluate term recall on the unseen set $V'$. Splitting the pairs by terms (instead of items) ensures that $V$ and $V'$ have no overlap, which is much more challenging than typical named entity recognition (NER) tasks but resembles the real-world use cases for online catalog taxonomy\xspace enrichment. \start{Open-world Evaluation.} Open-world evaluation tests on new terms that do not currently exist in $T$, which is preferable since it evaluates term extraction methods in the same scenario as in production. The downside is that it requires manual annotations as there are no labels for the newly extracted terms. Therefore, we ask experts and workers on Amazon Mechanical Turk (MTurk) to verify the quality of the new terms. As we would like to take new terms with high confidence for term attachment, we ask our taxonomists to measure the precision of top-ranked terms that each method is most confident at. The terms that are already on the core taxonomy $T$ are excluded and the top 100 terms of each compared method are carefully verified. To evaluate from the average customers' perspective, we sample 1,000 items and ask MTurk workers to extract the item types in the item titles. Different from expert evaluation, items are used as the unit for evaluation rather than terms. Precision and recall, weighted by the votes of the workers, are measured. More details of crowdsourcing are provided in App.~\ref{app:crowdsourcing}. \start{Baseline Methods.} For the evaluation on term extraction, we compare with two approaches widely used for taxonomy construction, namely noun phrase (NP) chunking and AutoPhrase~\cite{shang2018automated}. Pattern-based methods~\cite{liu2019user} and classification-based methods with simple n-gram and click count features~\cite{wang2014hierarchical} perform poorly in our preliminary experiments and are thus excluded. More details and discussions of the baselines are provided in App.~\ref{app:baseline}. \subsubsection{Evaluation Results}\hfill \noindent For closed-world automatic evaluation, we calculate recall@K and show the comparison results in Fig.~\ref{fig:term_eval}~{\em (Left)}. We observe that \textsc{Octet}\xspace consistently achieves the highest recall@K on the held-out test set. The overall recall of all compared methods, however, is relatively low. Nevertheless, we argue that the low recall is mainly due to the wording difference between the terms in the core taxonomy $T$ and item titles. As we will demonstrate in the open-world evaluation below, many extracted terms are valid but not on $T$, which also confirms that $T$ is very sparse and incomplete. For open-world expert evaluation, we examine the terms each method is most confident at. In AutoPhrase~\cite{shang2018automated}, each extracted term is associated with a confidence score. In NP chunking and \textsc{Octet}\xspace, we use the frequency of extracted terms (instead of the raw frequency via string match) as their confidence score. As shown in Fig.~\ref{fig:term_eval}~{\em (Right)}, \textsc{Octet}\xspace achieves very high precision@K (0.91 when K=100), which indicates that the newly extracted terms not found on the core taxonomy are of high quality according to human experts and can be readily used for term attachment. The compared methods, however, perform much worse on the top-ranked terms. In particular, the performance of NP chunking degenerates very quickly and only 27 of its top 100 extracted terms are valid. We further show examples of the extracted terms in Table~\ref{table:term_example}. As one can see, NP chunking extracts many terms that are either not item types (\eg, ``Penzeys Spices'' is a company and ``No Sugar'' is an attribute) or less specific (\eg, ``Whole Bean'' Coffee). AutoPhrase extracts some terms that are not of the desired type. For example, ``Honey Roasted'' and ``American Flag'' are indeed high-quality phrases that appear in the item titles but not valid item types. In contrast, \textsc{Octet}\xspace achieves very high precision on the top-ranked terms while ensuring that the extracted terms are of the same type as existing terms on the core taxonomy, which empirically verifies the superiority of formulating term extraction for online catalog taxonomy\xspace enrichment as sequence labeling. \begin{figure}[t] \includegraphics[width=.96\linewidth]{fig/term_eval} \vspace{-.3cm} \caption{Closed-world automatic evaluation on term recall and open-world expert evaluation on term precision.} \label{fig:term_eval} \vspace{-.25cm} \end{figure} \begin{table}[t] \caption{Examples of top-ranked terms extracted by each approach. Valid terms for item types are marked in bold.} \label{table:term_example} \vspace*{-.3cm} \centering \scalebox{.82}{ \begin{tabular}{p{2.2cm}p{2.6cm}p{2.6cm}} \toprule \textbf{NP Chunking} & \textbf{AutoPhrase}~\cite{shang2018automated} & \textbf{\textsc{Octet}\xspace}\\ \midrule \textbf{dark chocolate}, whole bean, penzeys spices, \textbf{extra virgin olive oil}, net wt, a hint, no sugar & \textbf{almond butter}, honey roasted, \textbf{hot cocoa}, \textbf{tonic water}, \textbf{brown sugar}, \textbf{curry paste}, american flag & \textbf{coconut flour}, \textbf{ground cinnamon}, \textbf{red tea}, \textbf{ground ginger}, \textbf{green peas}, sweet leaf, \textbf{coconut syrup} \\ \bottomrule \end{tabular} } \vspace*{-.25cm} \end{table} Finally, we show the results of open-world crowdsourcing evaluation in Table~\ref{table:extract_mturk}. \textsc{Octet}\xspace again achieves much higher precision and F1 score than the baseline methods. AutoPhrase obtains higher recall as we found that it tends to extract multiple terms in each sample, whereas there is usually one item type. The recall of all the compared methods is still relatively low, which is possibly due to the conciseness and noise in the item titles (recall examples in Fig.~\ref{fig:framework}) and leaves much space for future work. \begin{table}[t] \caption{Performance comparison in the open-world crowdsourcing evaluation on 1,000 sampled items. \textsc{Octet}\xspace achieves significantly higher precision and best F1 score. } \label{table:extract_mturk} \vspace*{-.3cm} \centering \scalebox{.95}{ \begin{tabular}{l cc c} \toprule \textbf{Method} & \textbf{Precision} & \textbf{Recall} & \textbf{F1} \\ \midrule NP Chunking & 12.3 & 20.4 & 15.4 \\ AutoPhrase~\cite{shang2018automated} & 20.9 & \textbf{41.3} & 27.8 \\ \textsc{Octet}\xspace & \textbf{87.5} & 24.9 & \textbf{38.8} \\ \bottomrule \end{tabular} } \vspace*{-.3cm} \end{table} \section{Related Work} \start{Taxonomy Construction.} \cite{shen2012graph} proposed a graph-based approach to attach new concepts to Wikipedia categories. \cite{jurgens2015reserating} enriched WordNet by finding terms from Wiktionary and attaching them via rule-based patterns. A concurrent study \cite{shen2020taxoexpan} also leverages GNNs for taxonomy enrichment. However, the features used in prior methods~\cite{shen2012graph,jurgens2015reserating,shen2018hiexpan,liu2019user} are designed either for specific taxonomies or for text-rich domains whereas \textsc{Octet}\xspace is robust to short texts and generally applicable to various online domains. For online catalog taxonomies\xspace, \cite{wang2014hierarchical} extracted terms from search queries and formulated taxonomy enrichment as a hierarchical Dirichlet process, where each node is represented by a uni-gram language model of its associated items. \cite{liu2019user} used patterns to extract new concepts in the queries and online news, and built a topic-concept-instance taxonomy with human-labeled training set. In contrast, \textsc{Octet}\xspace is self-supervised and utilizes heterogeneous sources of information. \start{Term Extraction.} \cite{kozareva2010semi} used Hearst patterns~\cite{hearst1992automatic} to extract new terms from the web pages. \cite{shen2018hiexpan,zhang2018taxogen} used AutoPhrase~\cite{shang2018automated} to extract keyphrases in general-purpose corpora. These methods, however, are inapplicable or ineffective for short texts like item titles. On the other hand, many prior studies~\cite{bansal2014structured,panchenko2016taxi,jurgens2016semeval,bordea2016semeval,mao2018end} made a somewhat unrealistic assumption that one clean vocabulary is given as input and focused primarily on hypernymy detection. Another plausible alternative is to treat entire user queries as terms rather than perform term extraction~\cite{wang2014hierarchical}, which results in a low recall. In contrast, \textsc{Octet}\xspace employs a sequence labeling model designed for term extraction from online domains with self-supervision. \start{Hypernymy Detection.} Pattern-based hypernymy detection methods~\cite{hearst1992automatic,snow2005learning,kozareva2010semi,panchenko2016taxi,nakashole2012patty} consider the lexico-syntactic patterns between the co-occurrences of term pairs. They achieve high precision in text-rich domains but suffer from low recall and also generate false positives in domains like e-commerce. Distributional methods~\cite{fu2014learning,rimell2014distributional,yu2015learning,tuan2016learning,shwartz2016improving} utilize the contexts of each term for semantic representation learning. Unsupervised measures such as symmetric similarity~\cite{lin1998information} and distributional inclusion hypothesis~\cite{weeds2004characterising,chang2017unsupervised} are also proposed, but not directly applicable to online catalog taxonomy\xspace enrichment as there are \textit{grouping nodes} in the online catalog taxonomies\xspace like ``Dairy, Cheese \& Eggs'' and ``Flowers \& Gifts'' curated by taxonomists for business purposes, which might not exist in any form of text corpora. In \textsc{Octet}\xspace, heterogeneous sources of signals are leveraged to tackle the lack of text corpora and grouping nodes are captured by head word semantics. \section{Conclusion} In this paper, we present a self-supervised end-to-end framework for online catalog taxonomy\xspace enrichment that considers heterogeneous sources of representation and does not involve additional human effort other than the existing core taxonomies to be enriched. We conduct extensive experiments on real-world taxonomies used in production and show that the proposed framework consistently outperforms state-of-the-art methods by a large margin under both automatic and human evaluations. In the future, we will explore the feasibility of joint learning of online catalog taxonomy\xspace enrichment and downstream applications such as recommendation and search. \section*{Acknowledgment} We thank Jiaming Shen, Jun Ma, Haw-Shiuan Chang, Giannis Karamanolakis, Colin Lockard, Qi Zhu, and Johanna Umana for the valuable discussions and feedback. \section{Reproducibility} \label{app:repro} \subsection{Implementation Details} We use fastText~\cite{bojanowski2017enriching} as the word embedding ${\bm{w}}_v$ in order to capture sub-word information. ${\bm{w}}_v$ is fixed to avoid semantic shift for the inference of unseen terms $V'$. All the terms $v$ are lowercased and concatenated with underscores if there are multiple words. For structural\xspace representation, we use the Deep Graph Library\footnote{https://www.dgl.ai/} for the implementation of GNN-based models. The number of layers $L$ is set to 2 (two-hop neighbors are considered) and the normalization constant $c_{v, r}$ is 1. We sample $N=5$ neighbors instead of using all the neighbors $N(v)$ for information aggregation. Node embedding ${\bm{h}}^{l}_v$ is of size 300, also initialized by the fastText embedding. ${\bm{W}}^l$ is of size 300 $\times$ 300. All of the lexical string-level features ${\bm{L}}_i(v, v')$ are randomly initialized and have an embedding size of 10. ${\bm{W}}_1$ and ${\bm{W}}_2$ are of size 1 $\times$ 100 and 100 $\times\ |{\bm{R}}(v, v')|$, respectively. For \textit{relationship measure} involving the output of the GNNs, $s({\bm{v}}, {\bm{v}}')$ measures the $L^1$ Norm, $L^2$ Norm, and cosine similarity between the embeddings of a term pair. For that between head words, $s({\bm{v}}, {\bm{v}}')$ measures the cosine similarity of their corresponding word embeddings. We use Adam as the optimizer with initial learning rate 1e-4 and choose the best performing model according to the development set. \subsection{Data Availability} The taxonomies used in the experiments are available online. The taxonomies on Amazon.com can be obtained by scraping public webpages (refer to Fig.~\ref{fig:coffee_department}) or registering as a vendor. The Yelp taxonomy is accessible at \url{www.yelp.com/developers/documentation/v3/all_category_list}. The user behavior logs are mainly used for the GNN-based structural\xspace representation learning. We use five-month user behavior logs in the target domain on Amazon.com and do not leverage user behavior on Yelp.com due to accessibility. All of the experiments and framework analysis without the structural\xspace representation can be reproduced. While each taxonomy used in the experiments is seemingly ``small'', it is \textit{real} and quite big (2K+ nodes) for a single domain (Grocery). \textsc{Octet}\xspace is easily applicable to other domains (Home, Electronics, ...), which also contain thousands of categories; they collectively form a taxonomy of 30K+ nodes. There are also datasets with similar or smaller size (\eg, 187 to 1386 nodes in \cite{zhang2016learning}, and 50 to 100 nodes in \cite{mao2018end, bansal2014structured}). Our setup is more general than SemEval-2016 Task 14 \cite{jurgens2016semeval} and can be simplified to it if we ignore user behavior. \section{Baseline} \label{app:baseline} \subsection{Baseline in Term Extraction} NP chunking is one of the popular choices for general-purpose entity extraction~\cite{ren2015clustype}. We conduct NP chunking via spaCy\footnote{https://spacy.io/}, which performs dependency parsing on the sentences and finds noun phrases in them. No task-specific input (\eg, a list of positive terms) is required or supported for the training of NP chunking. Post-processing, including removing the terms containing punctuation or digits, is used to filter clearly invalid terms from the results. AutoPhrase~\cite{shang2018automated} is the state-of-the-art phrase mining method widely used in previous taxonomy construction approaches~\cite{shen2018hiexpan,zhang2018taxogen}. We replace the built-in Wikipedia phrase list that AutoPhrase uses for distant supervision with the terms $V$ on the core taxonomy $T$, as we find that it performs better than appending $V$ to the Wikipedia phrase list. Note that AutoPhrase uses exactly the same resources as \textsc{Octet}\xspace for distant supervision. In terms of methodology, AutoPhrase~\cite{shang2018automated} focuses more on the corpus-level statistics and performs phrasal segmentation instead of sequence labeling. Pattern-based methods~\cite{liu2019user} are ineffective in our scenario due to the lack of clear patterns in the item profiles and user queries. The classification-based method in~\cite{wang2014hierarchical} only works for term extraction from queries and also performs poorly, possibly because~\citet{wang2014hierarchical} treats the whole query as one term, which results in low recall. \subsection{Baseline in Term Attachment} HiDir~\cite{wang2014hierarchical} conducts hypernymy detection with the assumption that the representation of a taxonomy node is the same as its parent node, where one node is represented by its associated items. Since we do not have \textit{description sentences} as in SemEval-2016 Task 14~\cite{jurgens2016semeval}, most of MSejrKu's features are inapplicable and we thus replace its features with those used in \textsc{Octet}\xspace except for the structural\xspace representation. we found that such changes improve MSejrKu's performance. Substr~\cite{bordea2016semeval} is the sub-string baseline used in SemEval-2016 Task 13~\cite{bordea2016semeval}. It is shown that Substr, which regards A as B's hypernym if A is a substring of B (\eg, ``Coffee'' and ``Ground Coffee''), outperforms most of the systems in the SemEval-2016 competition on automatic taxonomy construction~\cite{bordea2016semeval}. I2T matches $v'$ with item titles and finds the taxonomy nodes these items $I_{v'}$ are associated with. The final prediction of I2T is made by majority voting of the associated nodes where the items $I_{v'}$ are assigned to. \section{Crowdsourcing} \label{app:crowdsourcing} Crowdsourcing is a reasonable choice in our scenario because our terms are common words (\eg, ``coffee'' and ``black coffee'') without complicated relations that require domain expertise (\eg, ``sennenhunde'' and ``entlebucher'' in WordNet). \subsection{Crowdsourcing for Open-world Term Extraction Evaluation} For crowdsourcing evaluation in term extraction, each item is assigned to 5 workers and only item types labeled by at least 2 workers are considered valid. Links to the corresponding pages on Amazon.com are also provided to the workers. \subsection{Crowdsourcing for End-to-End Evaluation} We use crowdsourcing on MTurk for the end-to-end evaluation since expert evaluation is difficult to scale. We assign each term to 4 MTurk workers for evaluation. One critical problem of using crowdsourcing for end-to-end evaluation is that we can not ask MTurk workers to find the hypernym of each new term directly, as there are thousands of terms $V$ on the core taxonomy $T$ while the workers are unfamiliar with the taxonomy structure. Alternatively, we ask the workers to verify the precision of \textsc{Octet}\xspace: we provide the predicted hypernym of \textsc{Octet}\xspace and the ancestors along the predicted path to the root as the candidates. We also include in the candidates one sibling term at each level along the predicted path. The workers are required to select the hypernym(s) of the query term $v'$ among the provided candidates. In this way, we can estimate how accurate the term attachment is from the average customers' perspective. Two other options, ``\textit{The query term is not a valid type}'' and ``\textit{None of above are hypernyms of the query term}'', are also provided, which corresponds to error types (A) and (B), respectively (refer to Sec.~\ref{sec:e2e_exp}). \section{Introduction} \begin{figure}[t] \includegraphics[width=1.0\linewidth]{fig/k_cups.png} \vspace*{-.55cm} \caption{The most relevant taxonomy nodes are shown on the left when a user searches ``k cups'' on Amazon.com. } \label{fig:coffee_department} \vspace*{-.5cm} \end{figure} Taxonomies, the tree-structured hierarchies that represent the hypernymy (Is-A) relations, have been widely used in different domains, such as information extraction~\cite{Demeester2016LiftedRI}, question answering~\cite{Yang2017EfficientlyAT}, and recommender systems~\cite{huang2019taxonomy}, for the organization of concepts and instances as well as the injection of structured knowledge in downstream tasks. In particular, online catalog taxonomies\xspace serve as a building block of e-commerce websites (\eg, Amazon.com) and business directory services (\eg, Yelp.com) for both customer-facing and internal applications, such as query understanding, item categorization \cite{mao-etal-2019-hierarchical}, browsing, recommendation \cite{huang2019taxonomy}, and search \cite{wang2014hierarchical}. Fig.~\ref{fig:coffee_department} shows one real-world example of how the product taxonomy at Amazon.com is used to facilitate online shopping experience: when a user searches ``k cups'', the most relevant nodes (types) in the taxonomy \textit{Grocery \& Gourmet Food} are shown on the left sidebar. The taxonomy here serves multiple purposes. First, the user can browse relevant nodes to refine the search space if she is looking for a more general or specific type of items (\eg, ``Coffee Beverages''). Second, the taxonomy benefits query understanding by identifying that ``k cups'' belongs to the taxonomy \textit{Grocery \& Gourmet Food} and mapping the user query ``k cups'' to the corresponding taxonomy node ``Single-Serve Coffee Capsules \& Pods''. Third, the taxonomy allows query relaxation and makes more items searchable if the search results are sparse. For instance, not only ``Single-Serve Coffee Capsules \& Pods'' but also other coffee belonging to its parent type ``Coffee Beverages'' can be shown in the search results. Despite the prevalent use and benefits of online catalog taxonomies\xspace, most of them in practice are still built and maintained by human experts. Such manual practice embodies knowledge from the experts but is meanwhile labor-intensive and difficult to scale. On Amazon.com, the taxonomies usually have thousands of nodes, not necessarily enough to cover the types of billions of items: we sampled roughly 3 million items in Grocery domain on Amazon.com and found that over 70\% of items do not directly mention the types in the taxonomy, implying a mismatch between knowledge organization and item search. As a result, automatic taxonomy construction has drawn significant attention. Existing methods on taxonomy construction fail to work effectively on online catalog taxonomies\xspace for the following reasons. Most prior methods~\cite{kozareva2010semi,bansal2014structured,bordea2016semeval,shwartz2016improving,gupta2017taxonomy,mao2018end} are designed for taxonomy construction from general text corpora (\eg, Wikipedia), limiting their applicability to text-rich domains. The ``documents'' in e-commerce (\eg, item titles), however, are much shorter and pose particular challenges. First, it is implausible to extract terms with heuristic approaches~\cite{kozareva2010semi} from item titles and descriptions, since vendors can write them in arbitrary ways. Second, it is highly unlikely to find co-occurrences of hypernym pairs in the item titles due to their conciseness, making Hearst patterns~\cite{hearst1992automatic,panchenko2016taxi} and dependency parse-based features~\cite{mao2018end} infeasible. For instance, one may often see ``US'' and ``Seattle'' in the same document, but barely see ``Beverages'' and ``Coffee'' in the same item title. Third, blindly leveraging the co-occurrence patterns could be misleading: in an item titled ``\textit{Triple Scoop Ice Cream Mix, Premium Strawberry}'', ``Strawberry'' and ``Ice Cream'' co-occur but ``Strawberry'' is the flavor of the ``Ice Cream'' rather than its hypernym. The situation worsens as online catalog taxonomies\xspace are never static. There are new items (and thus new terms) emerging every day, making \textit{taxonomy construction from scratch} less favorable, since in practice we cannot afford to rebuild the whole taxonomy frequently and the downstream applications also require stable taxonomies to organize knowledge. To tackle the above issues of \textit{taxonomy construction from scratch}, we target the \textit{taxonomy enrichment} problem, which discovers emerging concepts\footnote{We use ``concept'', ``term'', ``type'', ``category'', and ``node'' interchangeably.} and attaches them to the existing taxonomy (named \textit{core taxonomy}) to precisely understand new customer interests. Different from taxonomy construction from scratch, the core taxonomies, which are usually built and maintained by experts for quality control and actively used in production, provide both valuable guidance and restrictive challenges for taxonomy enrichment. On the challenge side, the \textit{core taxonomy} requires term attachment to follow the existing taxonomy schema instead of arbitrarily building from scratch. On the bright side, we can base our work on the core taxonomy, which usually contains high-level and qualified concepts representing the fundamental categories in a domain (such as ``Beverages'' and ''Snacks`` for Grocery) and barely needs modification (or cannot be automatically organized due to business demands), but lacks fine-grained and emerging terms (such as ``Coconut Flour''). There are only a few prior works focused on taxonomy enrichment, which either employ simple rules~\cite{jurgens2015reserating} or represent taxonomy nodes by their associated items and totally neglect the lexical semantics of the concepts themselves~\cite{wang2014hierarchical}. In addition, prior studies~\cite{jurgens2016semeval,schlichtkrull2016msejrku} require manual training data and fail to exploit the structural information of the existing taxonomy. Despite the challenges, a unique opportunity for online catalog taxonomy\xspace enrichment is the availability of rich user behavior logs: vendors often carefully choose words to describe the type of their items and associate the items with appropriate taxonomy nodes to get more exposure; customers often include the item type in their queries and the majority of the clicked (purchased) items are instances of the type they are looking for. Such interactions among queries, items, and taxonomy nodes offer distinctive signals for hypernymy detection, which is unavailable in general-purpose text corpora. For instance, if a query mentioning ``hibiscus tea'' leads to the clicks of items associated with taxonomy node ``herbal tea'' or ``tea'', we can safely infer strong connections among ``hibiscus tea'', ``herbal tea'', and ``tea''. Existing works~\cite{wang2014hierarchical,liu2019user}, however, only utilize the user behavior heuristically to extract new terms or reduce the prediction space of hypernymy detection. \begin{figure*}[ht] \includegraphics[width=1.01\linewidth]{fig/octet} \vspace*{-.3cm} \caption{An overview of the proposed framework \textsc{Octet}\xspace. Item profiles and user queries in the target domain serve as framework input and the core taxonomy is used as self-supervision. New terms are automatically extracted via sequence labeling. Heterogeneous sources of signals, including the structure of the core taxonomy, the query-item-taxonomy interactions, and the lexical semantics of the term pairs are leveraged for hypernymy detection during term attachment.} \label{fig:framework} \vspace*{-.35cm} \end{figure*} In this paper, we present a self-supervised end-to-end framework, \textsc{Octet}\xspace, for online catalog taxonomy\xspace enrichment. \textsc{Octet}\xspace\ is novel in three aspects. First, \textsc{Octet}\xspace\ identifies new terms from item titles and user queries; it employs a sequence labeling model that is shown to significantly outperform typical term extraction methods. Second, to tackle the lack of text corpora, \textsc{Octet}\xspace leverages heterogeneous sources of signals; it captures the \textit{lexical semantics} of the terms and employs Graph Neural Networks (GNNs) to model the \textit{structure of the core taxonomy} as well as the \textit{query-item-taxonomy interactions} in user behavior. Third, \textsc{Octet}\xspace requires no human effort for generating training labels as it uses the core taxonomy for self-supervision during both term extraction and term attachment. We conduct extensive experiments on real-world online catalog taxonomies\xspace to verify the effectiveness of \textsc{Octet}\xspace via automatic, expert, and crowdsourcing evaluations. Experimental results show that \textsc{Octet}\xspace outperforms state-of-the-art methods by 46.2\% for term extraction and 11.5\% for term attachment on average. Notably, \textsc{Octet}\xspace doubles the size (2,163 to 4,355 terms) of an online catalog taxonomy\xspace in production with 0.881 precision. \start{Contributions.} (1) We introduce a self-supervised end-to-end framework, \textsc{Octet}\xspace, for online catalog taxonomy\xspace enrichment; \textsc{Octet}\xspace automatically extracts emerging terms and attaches them to the core taxonomy of a target domain with no human effort. (2) We propose a GNN-based model that leverages heterogeneous sources of information, especially the structure of the core taxonomy and query-item-taxonomy interactions, for term attachment. (3) Our extensive experiments show that \textsc{Octet}\xspace significantly improves over state-of-the-art methods under automatic and human evaluations. \subsection{Evaluation on Term Attachment} \label{sec:term_attach_exp} \subsubsection{Evaluation Setup.}\hfill \noindent For term attachment, we also conduct both closed-world and open-world evaluations, which involves ablating the core taxonomy $T$ and attaching newly extracted terms, respectively. In contrast, most of prior studies~\cite{bansal2014structured,jurgens2016semeval,mao2018end} only perform closed-world evaluation. \start{Closed-world Evaluation.} We take four taxonomies actively used in production as the datasets: \textit{Grocery \& Gourmet Food}, \textit{Home \& Kitchen}, and \textit{Beauty \& Personal Care} taxonomies at Amazon.com, and the \textit{Business Categories} at Yelp.com.\footnote{The taxonomies are available online. We use five-month user behavior logs on Amazon.com for structural\xspace representation and do not leverage user behavior on Yelp.com due to accessibility. See App.~\ref{app:repro} for more details on data availability.} \textit{Amazon Grocery \& Gourmet Food} is used for framework analysis unless otherwise stated. As the taxonomies are used in different domains and constructed according to their own business needs, they exhibit a wide spectrum of characteristics and almost have no overlap. Considering the real-world use cases where fine-grained terms are missing, we hold out the leaf nodes as the new terms $V'$ to be attached as in~\cite{jurgens2016semeval}. We split $V'$ into training, development, and test sets with a ratio of 64\% / 16\% / 20\%, respectively. Detailed statistics of the datasets can be found in Table~\ref{table:taxo_stats}. Note that if we regard term attachment as a classification problem, each class would have very few training samples (\eg, 1193 / 298 $\approx$ 4 in \textit{Amazon Grocery \& Gourmet Food}), which calls for a significant level of model generalizability. \begin{table}[ht] \caption{Taxonomy statistics for term attachment.} \centering \label{table:taxo_stats} \vspace*{-.3cm} \scalebox{.8}{ \begin{tabular}{l cccc c} \toprule \textbf{Taxonomy} & $|\textbf{V}|$ & $|\textbf{V}'|$ & $|\textbf{V}'_{\text{Train}}|$ & $|\textbf{V}'_{\text{Dev}}|$ & $|\textbf{V}'_{\text{Test}}|$ \\ \midrule Amazon Grocery \& Gourmet Food & 298 & 1,865 & 1,193 & 299 & 373 \\ Amazon Home \& Kitchen & 338 & 1,410 & 902 & 226 & 282 \\ Amazon Beauty \& Personal Care & 109 & 454 & 290 & 73 & 91 \\ Yelp Business Categories & 84 & 920 & 588 & 148 & 184 \\ \bottomrule \end{tabular} } \vspace*{-.2cm} \end{table} \start{Open-world Evaluation.} We conduct an open-world evaluation for term attachment on \textit{Amazon Grocery \& Gourmet Food}. Specifically, we ask the taxonomists to identify valid new terms among those discovered in the term extraction stage with frequency greater than 20. 106 terms are thus labeled as valid. We then ask the taxonomists to attach the 106 terms manually to the core taxonomy as ground truth and evaluate systems on these new terms with the same criteria as in the closed-world evaluation. \start{Evaluation Metrics.} We use Edge-F1 and Ancestor-F1~\cite{mao2018end} to measure the performance of term attachment. \textbf{Edge-F1} compares the predicted edge $(v, v')$ with the gold edge $(p(v'), v')$, \ie, whether $v = p(v')$. We use $P_{\text{Edge}}$, $R_{\text{Edge}}$, and $F1_{\text{Edge}}$ to denote the precision, recall, and F1-score, respectively. In particular, $P_{\text{Edge}} = R_{\text{Edge}} = F1_{\text{Edge}}$ if the number of predicted edges is the same as gold edges, \ie, when all the terms in $V'$ are attached. \textbf{Ancestor-F1} is more relaxed than Edge-F1 as it compares all the term pairs $(v_\text{sys}, v')$ with $(v_\text{gold}, v')$, where $v_\text{sys}$ represents the terms along the system predicted path (ancestors) to the root node, and $v_\text{gold}$ denotes those terms on the gold path. Similarly, we denote the ancesor-based metrics as $P_{\text{Ancestor}} = \frac{| v_{\text{sys}} \wedge v_{\text{gold}} |} {| v_{\text{sys}} |}$ and $R_{\text{Ancestor}} = \frac{| v_{\text{sys}} \wedge v_{\text{gold}} |} {| v_{\text{gold}} |}$. \start{Baseline Methods.} As discussed earlier, there are few existing methods for taxonomy enrichment. MSejrKu~\cite{schlichtkrull2016msejrku} is the winning method in the SemEval-2016 Task 14~\cite{jurgens2016semeval}. {HiDir}~\cite{wang2014hierarchical} is the state-of-the-art method for online catalog taxonomy\xspace enrichment. In addition, we compare with the substring method {Substr}~\cite{bordea2016semeval}, and {I2T} that finds one's hypernym by examining where its related items are assigned to. Two na\"ive baselines are also tested to better understand the difficulty of the task following convention~\cite{bansal2014structured,jurgens2016semeval}, where \textit{Random} attaches $v' \in V'$ randomly to $T$ and \textit{Root} attaches every term to the root node of $T$. More details of the baselines are in App.~\ref{app:baseline}. \subsubsection{Evaluation Results}\hfill \noindent We first evaluate different methods under the closed-world assumption (Tables~\ref{table:grocery_main} \& ~\ref{table:attachment_additional}). We observe that the Edge-F1 of two na\"ive baselines is very low since there are hundreds of $v \in V$ as candidates. The performance of I2T is similar to Substr but still far from satisfactory, implying that there might be noise in the matching between $V'$ and $I$, and the associations between $I$ and $V$. HiDir~\cite{wang2014hierarchical} and MSejrKu~\cite{schlichtkrull2016msejrku} achieve better performance than other baselines, especially in Edge-F1, while \textsc{Octet}\xspace outperforms all the compared methods by a large margin on both development and test sets across all of the four domains. \begin{table}[t] \caption{Comparison results of closed-world evaluation on \textit{Amazon Grocery \& Gourmet Food}.} \label{table:grocery_main} \vspace*{-.3cm} \centering \scalebox{.88}{ \begin{tabular}{l cccc} \toprule \multirow{2}{*}{\textbf{Method}} & \multicolumn{2}{c}{\textbf{Dev}} & \multicolumn{2}{c}{\textbf{Test}}\\ & Edge-F1 & Ancestor-F1 & Edge-F1 & Ancestor-F1\\ \midrule Random~\cite{bansal2014structured,jurgens2016semeval} & 0.3 & 30.3 & 0.5 & 31.2 \\ Root & 0.3 & 41.1 & 0 & 41.8 \\ I2T & 10.0 & 50.5 & 9.9 & 50.7 \\ Substr~\cite{bordea2016semeval} & 8.4 & 49.9 & 10.7 & 52.9 \\ HiDir~\cite{wang2014hierarchical} & 42.5 & 66.8 & 40.5 & 66.4 \\ MSejrKu~\cite{schlichtkrull2016msejrku} & 58.9 & 80.6 & 53.1 & 76.7 \\ \textsc{Octet}\xspace & \textbf{64.9} & \textbf{85.2} & \textbf{62.5} & \textbf{84.2} \\ \bottomrule \end{tabular} } \vspace*{-.3cm} \end{table} \begin{table}[t] \caption{Closed-world evaluation in different domains. Only competitive baseline methods that perform well on \textit{Amazon Grocery \& Gourmet Food} are listed.} \label{table:attachment_additional} \centering \vspace*{-.3cm} \scalebox{.8}{ \begin{tabular}{ll cc} \toprule \textbf{Dataset} & \textbf{Method} & \textbf{Edge-F1} & \textbf{Ancestor-F1}\\ \midrule \multirow{3}{*}{Amazon Home \& Kitchen} & HiDir~\cite{wang2014hierarchical} & 46.5 & 76.9 \\ & MSejrKu~\cite{schlichtkrull2016msejrku} & 46.0 & 74.1 \\ & \textsc{Octet}\xspace & \textbf{54.4} & \textbf{78.5} \\ \midrule \multirow{3}{*}{Amazon Beauty \& Personal Care} & HiDir~\cite{wang2014hierarchical} & 34.1 & 71.8 \\ & MSejrKu~\cite{schlichtkrull2016msejrku} & 49.5 & 75.0 \\ & \textsc{Octet}\xspace & \textbf{50.6} & \textbf{77.1} \\ \midrule \multirow{3}{*}{Yelp Business Categories} & HiDir~\cite{wang2014hierarchical} & 19.6 & 35.8 \\ & MSejrKu~\cite{schlichtkrull2016msejrku} & 29.9 & 35.7 \\ & \textsc{Octet}\xspace & \textbf{32.6} & \textbf{43.5} \\ \bottomrule \end{tabular} } \vspace*{-.2cm} \end{table} For the open-world evaluation, we compare \textsc{Octet}\xspace with the best performing baselines MSejrKu~\cite{schlichtkrull2016msejrku} and HiDir~\cite{wang2014hierarchical} on the expert-labeled data (Table~\ref{table:attachment_open}). Perhaps unsurprisingly, the performance of each method is lower than that under the closed-world evaluation, since the distributions of the existing terms on $T$ and the newly extracted terms are largely different (shown in Sec.~\ref{sec:term_extract_exp}). \textsc{Octet}\xspace again achieves the best performance thanks to its better generalizability. \begin{table}[t] \caption{Open-world expert evaluation. Note that the seemingly low \textit{absolute} performance is comparable to results on other datasets \cite{bansal2014structured,mao2018end} due to the difficulty of the task.} \label{table:attachment_open} \centering \vspace*{-.3cm} \scalebox{.95}{ \begin{tabular}{l cc} \toprule \textbf{Method} & \textbf{Edge-F1} & \textbf{Ancestor-F1}\\ \midrule HiDir~\cite{wang2014hierarchical} & 28.3 & 59.2 \\ MSejrKu~\cite{schlichtkrull2016msejrku} & 29.3 & 61.2 \\ \textsc{Octet}\xspace & \textbf{30.2} & \textbf{67.5} \\ \bottomrule \end{tabular} } \vspace*{-.3cm} \end{table} \subsection{Term Attachment Learning}\label{sec:term_attach} Term attachment extends taxonomy $(\bar{V} = V \cup V', R)$ with new edges $R'$ between terms in $V$ and $V'$. Following common practice~\cite{wang2014hierarchical,bansal2014structured}, we consider a taxonomy $\bar{T}$ as a Bayesian network where each node $v \in \bar{V}$ is a random variable. The joint probability distribution of nodes $\bar{V}$ can be then formulated as follows. \begin{equation*} P(\bar{V} \mid \bar{T}, \Theta) = P(v_0) \prod_{v \in \bar{V} \setminus v_0} P(v \mid p(v), \Theta), \end{equation*} where $v_0$ denotes the root node, $p(v)$ denotes the direct hypernym (parent) of node $v$, and $\Theta$ denotes model parameters. Maximizing the likelihood with respect to the taxonomy structure $\bar{T}$ gives the optimal taxonomy $\bar{T}^*$. As we do not modify the structure of core taxonomy $T$, the formulation can be simplified as follows. \begin{equation*} \vspace*{-.1cm} \begin{split} \bar{T}^* = \argmax_{\bar{T}} P(\bar{V} \mid \bar{T}, \Theta) &= \argmax_{\bar{T}} \prod_{v \in \bar{V} \setminus v_0} P(v \mid p(v), \Theta) \\ &= \argmax_{\bar{T}}\ \prod_{v' \in V'} P(v' \mid p(v'), \Theta). \end{split} \vspace*{-.1cm} \end{equation*} The problem definition further ensures that $p(v') \in V$ always holds true and thus no inter-dependencies exist between the new terms $v' \in V'$. Therefore, we can naturally regard term attachment as a \textit{multi-class classification problem} according to $P(v' \mid p(v'), \Theta)$ where each $p(v') = v \in V$ is a class. One unique challenge for online catalog taxonomy\xspace enrichment is the lack of conventional corpora. For example, it is rare to find co-occurrences of multiple item types in a single query (<1\% in Grocery domain on Amazon.com), let alone the ``such as''-style patterns in Hearst-based methods~\cite{kozareva2010semi}. Instead of using the limited text directly, we introduce signals from user behavior logs and the structure of the core taxonomy by modeling them in a graph (Sec.~\ref{sec:gnn}). The lexical semantics of the term pairs are further considered to better identify hypernymy relations (Sec.~\ref{sec:semantic_rep} \& \ref{sec:lexical_rep}). \subsubsection{Structural\xspace Representation}\hfill \label{sec:gnn} \noindent There is rich structural\xspace information for online catalog taxonomy\xspace enrichment which comes from two sources. First, the neighborhood (\eg, parent and siblings) of a node $v \in V$ on $T$ can serve as a meaningful supplement for the semantics of $v$. For example, one may not have enough knowledge of node $v=$ ``Makgeolli'' (Korean rice wine); but if she perceives that ``Sake'' (Japanese rice wine) is $v$'s sibling and ``Wine'' is $v$'s parent, she would have more confidence in considering ``Makgeolli'' as one type of ``Alcoholic Beverages''. Second, there exist abundant user behavior data, providing even richer structural information than that offered by the core taxonomy $T$. Specifically, items $I$ are associated with the existing taxonomy nodes $V$. New terms $V'$ are related to items $I$ and user queries $Q$ since $V'$ are extracted from the two sources. Furthermore, $I$ and $Q$ are also connected via clicks. Based on the observations above, we propose to learn a structural\xspace term pair representation to capture the structure in the core taxonomy and the query-item-taxonomy interactions as follows. \start{Graph Construction.} We construct a graph ${\mathcal{G}}$ where the nodes consist of the existing terms $v \in V$ and new terms $v' \in V'$. There are two sets of edges: one set is the same as $R$ in the core taxonomy $T$, which captures the ontological structure in $T$. The other set leverages the query-item-taxonomy interactions: for each new term $v' \in V'$, we find the user queries $Q_{v'}$ that mention $v'$ and collect the clicked items $I_{Q_{v'}}$ in the queries $Q_{v'}$. Then, we find the taxonomy nodes $\{v_i\}$ that $I_{Q_{v'}}$ is associated with. Finally, we add an edge between each $(v_i, v')$ pair. For instance, when determining the parent of a new term ``Figs'', we find that some queries mentioning ``Figs'' lead to clicked items associated with the taxonomy node ``Fruits'', evincing strong relations between the two terms. \start{Graph Embedding.} We leverage graph neural networks (GNNs) to aggregate the neighborhood information in ${\mathcal{G}}$ when measuring the relationship between a term pair. Specifically, we take the rationales in relational graph convolutional networks (RGCNs)~\cite{kipf2016semi,schlichtkrull2018modeling}. Let ${\mathcal{R}}$ denote the set of relations, including ($r_1$) The neighbors of $v$ on the core taxonomy $T$. The neighbors can be the (grand)parents or children of $v$ and we compare different design choices in Sec.~\ref{sec:graph_ablation}; ($r_2$) the interactions between $v \in V$ and $v' \in V'$ discovered in user behavior. We confine the interactions to be unidirectional (from $v$ to $v'$) since the terms $v \in V$ are already augmented with $r_1$ while there might be noise in the user behavior; and ($r_3$) the self-loop of node $v$. The self-loop of $v$ ensures that the information of $v$ itself is preserved and those isolated nodes without any connections can still be updated using its own representation. Let $N(v, r)$ denote the neighbors of node $v$ with relation $r$, and ${\bm{h}}^{\text{0}}_v$ the initial input representation of node $v$. The hidden representation of $v$ at layer (hop) $l$ is updated as follows: ${\bm{h}}^{l + 1}_v = \text{ReLU} (\sum_{r \in {\mathcal{R}}} \sum_{i \in \{N(v, r)\}} \frac{1}{c_{v, r}} {\bm{W}}^l_r {\bm{h}}^{l}_i)$, where ${\bm{W}}^l_r$ is the matrix at layer $l$ for linear projection of relation $r$ and $c_{v, r}$ is a normalization constant. We take the final hidden representation of each node ${\bm{h}}^{L}_v$ (\textit{denoted as ${\bm{g}}_v$}) as the graph embedding. \start{Relationship Measure.} \label{sec:sim_measure} One straightforward way of utilizing the structural\xspace representation is to use the graph embeddings ${\bm{g}}_v$ and ${\bm{g}}_{v'}$ as the representation of term $v$ and $v'$. Instead, we propose to measure the relationship between a term pair explicitly by cosine similarity and norm distance (more details in App.~\ref{app:repro}). We denote the relationship measure between two embeddings as $s({\bm{v}}, {\bm{v}}')$. One benefit of using $s({\bm{g}}_v, {\bm{g}}_{v'})$ is that empirically we observe $s({\bm{g}}_v, {\bm{g}}_{v'})$ alleviates overfitting compared with directly using ${\bm{g}}_v$ and ${\bm{g}}_v'$. Also, using $s({\bm{g}}_v, {\bm{g}}_{v'})$ makes the final output size much smaller and reduces the number of parameters in the following layer significantly. \subsubsection{Semantic Representation}\hfill \label{sec:semantic_rep} \noindent We use the word embedding ${\bm{w}}_{v}$ of each term $v$ to capture its semantics. For grouping nodes consisting of several item types (\eg, ``Fresh Flowers \& Live Indoor Plants'') and multi-word terms with qualifiers (\eg, ``Fresh Cut Bell Pepper''), we employ dependency parsing to find the noun chunks (``Fresh Flowers'', ``Live Indoor Plants'', and ``Fresh Cut Bell Pepper'') and respective head words (``Flowers'', ``Plants'', and ``Pepper''). Intuitively, $(v, v')$ tends to be related as long as one head word of $v$ is similar to that of $v'$. We thus use the relationship measure $s({\bm{v}}, {\bm{v}}')$ defined in Sec.~\ref{sec:sim_measure} to measure the semantic relationship of the head words: ${\bm{H}}(v, v') = \max_{i, j} s ({\bm{w}}_{\text{head}^i(v)}, {\bm{w}}_{\text{head}^{j}(v')})$, where ${\bm{w}}_{\text{head}^i(v)}$ denotes the word embedding of the i-th head word in the term $v$. Finally, the overall semantic representation ${\bm{S}}(v, v')$ is defined as ${\bm{S}}(v, v') = [{\bm{H}}(v, v'), {\bm{w}}_v, {\bm{w}}_{v'}]$, where ``,'' denotes the concatenation operation. \subsubsection{Lexical Representation}\hfill \label{sec:lexical_rep} \noindent String-level measures prove to be very effective in hypernymy detection~\cite{bansal2014structured,bordea2016semeval,gupta2017taxonomy,mao2018end}. For online catalog taxonomies\xspace, we also find many cases where lexical similarity provides strong signals for hypernymy identification. For example, ``Black Tea'' is a hyponym of ``Tea'' and ``Fresh Packaged Green Peppers'' is a sibling of ``Fresh Packaged Orange Peppers''. Therefore, we take the following lexical features~\cite{mao2018end} to measure the lexical relationship between term pairs: \emph{Ends with}, \emph{Contains}, \emph{Suffix match}, \emph{Longest common substring}, \emph{Length difference}, and \emph{Edit distance}. Values in each feature are binned by range and each bin is mapped to a randomly initialized embedding, which would be updated during model training. We denote the set of lexical features by ${\mathcal{M}}$ and compute lexical representation as the concatenation of the lexical features: ${\bm{L}}(v, v') = [{\bm{L}}_i(v, v')]_{ i \in {\mathcal{M}} }$. \subsubsection{Heterogeneous Representation}\hfill \noindent For each term pair $(v, v')$, we generate a heterogeneous term pair representation ${\bm{R}}(v, v')$ by combining the representations detailed above. ${\bm{R}}(v, v')$ captures several orthogonal aspects of the term pair relationship, which contribute to hypernymy detection in a complementary manner (Sec.~\ref{sec:feat_ablation}). To summarize, the structural\xspace representation models the core taxonomy structure as well as underlying query-item-taxonomy interactions, whilst the semantic and lexical representations capture the distributional and surface information of the term pairs, respectively. We further calculate $s({\bm{v}}, {\bm{v}}')$ between the graph embedding ${\bm{g}}_v$ (${\bm{g}}_v'$) of one term and the word embedding ${\bm{w}}_{v'}$ (${\bm{w}}_{v}$ ) of the other term in the term pair, which measures the relationship of the term pair in different forms and manifests improved performance. Formally, the heterogeneous term pair representation ${\bm{R}}(v, v')$ is defined as follows. \begin{equation*} {\bm{R}}(v, v')\! =\! [s({\bm{g}}_v, {\bm{g}}_{v'}), s({\bm{w}}_v, {\bm{g}}_{v'}), s({\bm{g}}_v, {\bm{w}}_{v'}), {\bm{S}}(v, v'), {\bm{L}}(v, v')]. \end{equation*} \subsubsection{Model Training and Inference}\hfill \noindent Similar to prior works~\cite{shwartz2016improving,mao2018end}, we feed ${\bm{R}}(v, v')$ into a two-layer feed-forward network and use the output after the sigmoid function as the probability of hypernym relationship between $v$ and $v'$. To train the term attachment module, we permute all the term pairs $(v_i, v_j)$ in $V$ as training samples and utilize the existing hypernym pairs $R$ on $T$ for self-supervision -- the pairs in $R$ are regarded as positive samples and other pairs are negative. The heterogeneous term pair representation, including the structural representation, is learned in an end-to-end fashion. We use binary cross-entropy loss as the objective function due to the classification formulation. An alternative formulation is to treat term attachment as a hierarchical classification problem where the positive labels are all the ancestors of the term (instead of only its parent). We found, however, that hierarchical classification does not outperform standard classification and thus opt for the simpler formulation following~\cite{wang2014hierarchical,bansal2014structured}. For inference, we choose $v_i \in V$ with the highest probability among all the permuted term pairs $(v_i, v')$ as the predicted hypernym of $v'$. \subsection{End-to-End Evaluation} \label{sec:e2e_exp} Besides the individual evaluations on term extraction and term attachment, we perform a novel \textit{end-to-end open-world evaluation} that helps us better understand the quality of the enriched taxonomy by examining errors throughout the entire framework: whether (A) the extracted term is invalid or (B) the term is valid but the attachment is inaccurate. To our knowledge, such an end-to-end evaluation has not been conducted in prior studies. We evaluate \textsc{Octet}\xspace on \textit{Amazon Grocery \& Gourmet Food} using Amazon MTurk. The details of crowdsourcing can be found in App.~\ref{app:crowdsourcing}. In total, \textsc{Octet}\xspace extracts and attaches 2,192 new terms from the item titles described in Sec.~\ref{sec:term_extract_setup}, doubling the size of the existing taxonomy (2,163 terms). As listed in Table~\ref{table:end2end}, only 6.5\% of extracted terms are considered invalid by average customers (MTurk workers). The top-1 edge precision and ancestor precision are relatively low, but they are comparable to the state-of-the-art performance on similar datasets with \textit{clean} term vocabulary \cite{mao2018end}. The neighbor precision, which considers the siblings on the predicted path as correct, is very high (88.1). One can further improve the precision by filtering low-confidence terms or allowing top-k prediction (Sec.~\ref{sec:tradeoff}). \begin{table}[h] \vspace*{-.3cm} \caption{Open-world end-to-end evaluation for \textsc{Octet}\xspace.} \label{table:end2end} \centering \vspace*{-.3cm} \scalebox{.8}{ \begin{tabular}{cc ccc} \toprule \textbf{Error A\%} & \textbf{Error B\%} & \textbf{Edge Prec}& \textbf{Ancestor Prec}&\textbf{Neighbor Prec}\\ \midrule 6.5 & 11.9 & 22.1 & 40.9 & 88.1 \\ \bottomrule \end{tabular} } \vspace*{-.35cm} \end{table} \subsection{Framework Analysis} \label{sec:analysis} \subsubsection{Feature Ablation} \label{sec:feat_ablation} \noindent We analyze the contribution of each representation for the term pair (Table~\ref{table:ablation_feat}). As one can see, only using word embedding (W) does not suffice to identify hypernymy relations while adding the semantics of head words (H) explicitly boosts the performance significantly. Lexical (L) features are very effective and combining lexical representation with semantic representation (L + W + H) brings 17.2 absolute improvement in Edge-F1. The structural information is very useful in that even if we use word embedding (W) as the input of the structural\xspace representation (G), the Edge-F1 improves by 4.8x and the Ancestor-F1 improves by 59.3\% upon W. The full model that incorporates various representations performs the best, indicating that they capture different aspects of the term pair relationship and are complementary to each other. \begin{table}[t] \caption{Ablation study of word embedding (W), head word semantics (H), lexical representation (L), and structural\xspace graph-based representation (G).} \centering \label{table:ablation_feat} \vspace*{-.3cm} \scalebox{.85}{ \begin{tabular}{l cccc} \toprule \multirow{2}{*}{\textbf{Representation}} & \multicolumn{2}{c}{\textbf{Dev}} & \multicolumn{2}{c}{\textbf{Test}}\\ & Edge-F1 & Ancestor-F1 & Edge-F1 & Ancestor-F1\\ \midrule W & 12.0 & 50.4 & 11.0 & 49.7 \\ H & 30.8 & 62.9 & 29.2 & 64.4 \\ W + H & 41.8 & 68.8 & 39.7 & 67.8 \\ L & 48.2 & 74.7 & 42.6 & 70.3 \\ L + W & 57.9 & 79.7 & 52.6 & 76.9 \\ G & 57.5 & 80.3 & 50.9 & 78.6 \\ L + W + G & 63.6 & 82.6 & 56.0 & 79.9 \\ L + W + H & 62.5 & 83.6 & 59.8 & 81.6 \\ L + W + H + G & \textbf{64.9} & \textbf{85.2} & \textbf{62.5} & \textbf{84.2} \\ \bottomrule \end{tabular} } \vspace*{-.2cm} \end{table} \subsubsection{Graph Ablation} \label{sec:graph_ablation} \noindent We analyze different variants regarding the design choices in the structural\xspace representation. As shown in Table~\ref{table:graph_choice}, considering multi-hop relations (\eg, grandparents and siblings) is better than only considering immediate family (\ie, parent and children). The directionality of edges does not have a huge effect on the model performance, although the information of the ancestors tends to be more benefitial for Ancestor-F1 and descendants for Edge-F1. Adding the query-item-taxonomy interactions in the user behavior ($r_2$) in addition to the structure in the core taxonomy further improves model performance, showing the benefits of leveraging user behavior for term attachment. \begin{table}[t] \caption{Comparison of various design choices in the structural\xspace representation. C and P denote Child and Parent. $r_1$, $r_2$, $r_3$ denote structure in the core taxonomy, query-item-taxonomy interactions, and self-loop, respectively.} \label{table:graph_choice} \centering \vspace*{-.3cm} \scalebox{.88}{ \begin{tabular}{c l cc} \cmidrule[0.06em]{2-4} &\textbf{Design Choice} & \textbf{Edge-F1} & \textbf{Ancestor-F1}\\ \cmidrule{2-4} \multirow{2}{*}{\rotatebox[origin=c]{90}{$L$}} &One-hop neighborhood & 50.4 & 75.9\\ &Two-hop neighborhood & \textbf{60.1} & \textbf{83.0}\\ \cmidrule{2-4} \multirow{3}{*}{\rotatebox[origin=c]{90}{$N(v, r_1)$}} &C->P & \textbf{60.1} & 83.0 \\ &C<->P & 59.8 & 83.2 \\ &P->C & 59.3 & \textbf{83.6} \\ \cmidrule{2-4} \multirow{2}{*}{\rotatebox[origin=c]{90}{${\mathcal{R}}$}} &$\{r_1, r_3\}$ & 60.1 & 83.0\\ &$\{r_1, r_2, r_3\}$ & \textbf{62.5} & \textbf{84.2}\\ \cmidrule[0.06em]{2-4} \end{tabular} } \vspace*{-.35cm} \end{table} \subsubsection{Performance Trade-Off} \label{sec:tradeoff} \noindent Precision recall trade-off answers the practical question in production ``how many terms can be attached if a specific precision of term attachment is required'', by filtering predictions with $\max_{v \in V} P(v' \mid v, \Theta) < c$, where $c \in [0, 1]$ is a thresholding constant. As depicted in Fig~\ref{fig:hit_pr} {\em (Left)}, more than 15\% terms can be recalled and attached perfectly. Over 60\% terms can be recalled when an edge precision of 80\% is achieved. We also analyze the performance changes if we relax term attachment to top-k predictions rather than top-1 prediction (as measured in Edge-F1). We observe that more than 95\% gold hypernyms of the query terms are in the top-50 predictions (Fig~\ref{fig:hit_pr} {\em (Right)}), which indicates that \textsc{Octet}\xspace generally ranks the gold hypernyms higher than other candidates even if its top-1 prediction is incorrect. Note that the results in all the previous experiments are regarding term recall equal to 1 (all extracted terms are attached) and Hit@1 (whether the top-1 prediction is correct). \begin{figure}[t] \includegraphics[width=1.01\linewidth]{fig/hit_pr} \vspace*{-.65cm} \caption{The precision recall trade-off {\em (Left)}\xspace and performance of term attachment in Hit@K {\em (Right)}.} \label{fig:hit_pr} \vspace*{-.35cm} \end{figure} \subsubsection{Case Studies} \noindent We inspect correct and incorrect term attachments to better understand model behavior and the contribution of each type of representation. As shown in Table~\ref{table:expand_example}, \textsc{Octet}\xspace successfully predicts ``Fresh Cut Flowers'' as the hypernym of ``Fresh Cut Carnations'', where lexical representation possibly helps with the matching of ``Fresh Cut'' and semantic representation identifies ``Carnations'' is a type of ``Flowers''. When lexical clues are lacking, \textsc{Octet}\xspace can still use semantic representation to recognize that ``Tilapia'' is a type of ``Fresh Fish''. Without structural\xspace representation, \textsc{Octet}\xspace detects that ``Bock Beer'' is closely related to ``Beer'' and ``Ales''. By adding the structural\xspace representation \textsc{Octet}\xspace could narrow down its prediction to the more specific type ``Lager \& Pilsner Beers''. For the wrongly attached terms, \textsc{Octet}\xspace is unconfident in distinguishing ``Russet Potatoes'' from ``Fingerling \& Baby Potatoes'', which is undoubtfully a harder case and requires deeper semantic understanding. \textsc{Octet}\xspace also detects a potential error in the core taxonomy itself as we found the siblings of ``Pinto Beans'' all start with ``Dried'', which might have confused \textsc{Octet}\xspace during training. \begin{table}[ht] \footnotesize \caption{Case studies of term attachment. Correct and incorrect cases are marked in green and red, respectively.} \label{table:expand_example} \vspace*{-.3cm} \centering \scalebox{.87}{ \begin{tabular}{p{2.2cm}p{2.cm}p{4.5cm}} \toprule \textbf{Query Term} & \textbf{Gold Hypernym} & \textbf{Top-3 Predictions}\\ \midrule \colorG{fresh cut carnations} & fresh cut flowers & \colorB{fresh cut flowers}, fresh cut root vegetables, fresh cut \& packaged fruits\\ \midrule \colorG{tilapia} & fresh fish & \colorB{fresh fish}, liquor \& spirits, fresh shellfish \\ \midrule \colorG{bock beers} & lager \& pilsner beers & \textbf{W/O structural\xspace representation:} ales, beer, tea beverages \newline \textbf{Full Model:} \colorB{lager \& pilsner beers}, porter \& stout beers, tea beverages\\ \midrule \colorR{fresh russet potatoes} & fresh potatoes \& yams & fresh fingerlings \& baby potatoes, fresh root vegetables, fresh herbs \\ \midrule \colorR{pinto beans} & dried beans & canned beans, fresh peas \& beans, single herbs \& spices \\ \bottomrule \end{tabular} } \vspace*{-.25cm} \end{table}
{'timestamp': '2020-06-19T02:08:52', 'yymm': '2006', 'arxiv_id': '2006.10276', 'language': 'en', 'url': 'https://arxiv.org/abs/2006.10276'}
arxiv
\section{Introduction} The Variational Auto-Encoder (VAE) belongs to a class of models, which we will refer to as \emph{deep maximum likelihood models}, that uses a deep neural network to learn a maximum likelihood model for some input data. They are perhaps the most simple and efficient deep maximum likelihood model available, and have thus gained popularity in representation learning and generative image modeling. Unfortunately, in my opinion, in some circles the term ``VAE" has become somewhat synonymous with ``an auto-encoder with stochastic regularization that generates useful or beautiful samples", which has led to various misconceptions about VAEs. In this tutorial, we will return to the probabilistic and information theoretic roots of VAEs, clarify common misconceptions about VAEs, and look at a toy example on 2D data that will illustrate the capabilities and limitations of VAEs. In Section~\ref{sec:overview}, we will give an overview of what is a maximum likelihood model and what a VAE looks like. In Sections~\ref{sec:prob} and~\ref{sec:information}, we will motivate the VAE and obtain intuitive insight into its behavior by deriving its objective. This derivation is broken into a probabilistic interpretation (Section~\ref{sec:prob})---in which we view a VAE through the lens of Bayes' Rule, importance sampling, and the change of variables formula---and an information theoretic interpretation(Section~\ref{sec:information})---in which we view a VAE through the lens of lossless compression and transmission through a noisy channel. In Section~\ref{sec:misconceptions}, we will clarify two misconceptions about VAEs that I have encountered in casual conversation and teaching materials: that they can be trained using the mean-squared error loss and that the latent vector of the VAE can be viewed as a parameter rather than a variable. These two misconceptions over the formulation may lead to the incorrect beliefs that VAEs have blurry reconstructions or that they can only model Gaussian data. Finally, in Section~\ref{sec:code}, we will gain insight into the capabilities and limitations of VAEs through a code example on toy 2D data. In this code example, we will visualize the VAE's density estimation abilities and latent space. An accompanying Jupyter Notebook is provided. \section{VAE Overview} \label{sec:overview} \subsection{What is Maximum Likelihood?} Suppose we have high-dimensional data that follows a ground truth distribution $p_{gt}(\mathbf{x})$. A maximum likelihood model learns a probabilistic model $p_\theta(\mathbf{x})$ parameterized by $\theta$ that seeks to approximate $p_{gt}(\mathbf{x})$. We can do so by collecting i.i.d. samples from $p_{gt}(\mathbf{x})$ to create a training set $\mathcal{D}=\{\mathbf{x}^{(1)}, \dots, \mathbf{x}^{(N)} \}$, and learning to maximize the likelihood of the joint distribution $p_\theta(\mathbf{x}^{(1)}, \dots, \mathbf{x}^{(N)}) = \prod_{i=1}^N p_\theta(\mathbf{x}^{(i)})$. For numerical stability, we instead minimize the negative log-likelihood: \begin{align} -\log p_\theta(\mathbf{x}^{(1)}, \dots, \mathbf{x}^{(N)}) = \sum_{i=1}^N -\log p_\theta(\mathbf{x}^{(i)}) \label{eq:empirical} \end{align} As is the case with virtually all machine learning models, we hope that by minimizing the empirical risk of our training set given by Equation~\ref{eq:empirical}, we will also minimize the true risk $\mathbb{E}_{\mathbf{x}\sim p_{gt}(\mathbf{x})} -\log p_\theta(\mathbf{x})$, which reaches a global minima if and only if $p_{gt}(\mathbf{x}) = p_\theta(\mathbf{x})$. Two key operations for a maximum likelihood model are \emph{inference} and \emph{generation}. Inference is the ability to evaluate $p_\theta(\mathbf{x})$ for any input vector $\mathbf{x}\in \mathbb{R}^n$. Generation is the ability to sample data from the distribution $p_\theta(\mathbf{x})$. In the asymptotic case where $p_\theta(\mathbf{x})$ approaches $p_{gt}(\mathbf{x})$, one application for inference is out-of-distribution data detection (e.g. adversarial examples). One application for generation is generative image modeling. However, existing maximum likelihood models are currently not powerful enough to reliably perform out-of-distribution detection or sample images that come close to achieving the diversity and perceptual quality of natural images. \subsection{What is a VAE?} The VAE performs inference and generation by introducing a latent variable $\mathbf{z}$ that follows a \emph{prior} distribution $p_\theta(\mathbf{z})$. The VAE then uses an auto-encoder with an encoder parameterized by $\phi$ and a decoder parameterized by $\theta$ to infer a \emph{posterior} distribution $q_\phi(\mathbf{z}|\mathbf{x})$ and an output distribution $p_\theta(\mathbf{x}|\mathbf{z})$. If inference and generation can be efficiently done for all three of these distributions, then they can also be done on $p_\theta(\mathbf{x})$. As in the case of a standard auto-encoder, the decoder tries to reconstruct the input $\mathbf{x}$ given a latent variable $\mathbf{z}$. The encoder predicts which $\mathbf{z}$ would be most capable of reconstructing $\mathbf{x}$. One advantage of latent models such as VAEs over maximum likelihood models without latent variables is the potential application of $\mathbf{z}$ for semi-supervised or disentangled representation learning. During generation, a latent vector $\mathbf{z}$ is sampled from $p_\theta(\mathbf{z})$, and the decoder outputs the parameters of $p_\theta(\mathbf{x}| \mathbf{z})$, from which we can sample an output vector. While exact inference cannot typically be efficiently done using a VAE, we can efficiently estimate an \emph{upper-bound} of the negative log-likelihood $\log p_\theta(\mathbf{x})$ given by: \begin{align} -\log p_\theta(\mathbf{x}) \leq \mathbb{E}_{\mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x})}[- \log p_\theta(\mathbf{x}| \mathbf{z})] + D_{KL}(q_\phi(\mathbf{z}|\mathbf{x}) || p_\theta(\mathbf{z})) \label{eq:elbo} \end{align} where $D_{KL}$ refers to the KL-Divergence. This bound is also commonly referred to as the \emph{negative Evidence Lower-BOund (ELBO)}, and can be denoted as $-\mathcal{L}(\mathbf{x})$. During training, we can use the negative ELBO as an objective, which in turn minimizes $-\log p_\theta(\mathbf{x})$. Before deriving Equation~\ref{eq:elbo} and discussing its intuitive meaning, let us first give a concrete example of what a VAE could look like in terms of neural network outputs. \subsection{A Typical VAE} \label{sec:example} The prior distribution is typically a standard isotropic multi-variate Gaussian $p_\theta(\mathbf{z})=\mathcal{N}(0,\mathbf{I})$. The inferred posterior distribution is typically a multi-variate Gaussian with diagonal co-variance $q_\phi(\mathbf{z}|\mathbf{x}) = \mathcal{N}(\boldsymbol \mu_\phi(\mathbf{x}), diag(\boldsymbol \sigma^2_\phi (\mathbf{x}))$. Practically speaking, our encoder would be a deep neural network that consumes $\mathbf{x}$ as input and outputs two vectors $\boldsymbol \mu_\phi(\mathbf{x}), \boldsymbol \sigma^2_\phi (\mathbf{x})\in \mathbb{R}^d$ where $d$ is the dimensionality of the latent space. Sampling $\mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x})$ can be done using the \emph{reparameterization trick}, by first sampling a random vector $\mathbf{u} \sim \mathcal{N}(0,\mathbf{I})$ and letting \begin{align} \mathbf{z} = \boldsymbol \mu_\phi(\mathbf{x}) + \boldsymbol \sigma_\phi(\mathbf{x}) \odot \mathbf{u} \label{eq:reparameterize} \end{align} where $\odot$ is the element-wise product. Since $\mathbf{z}$ is a deterministic function of $ \boldsymbol \mu_\phi(\mathbf{x})$ and $\sigma^2_\phi(\mathbf{x})$, the resulting gradient with respect to the encoder is quite stable. There is more variety for how the output distribution $p_\theta(\mathbf{x}|\mathbf{z})$ can be parameterized. One solution is to use an isotropic multi-variate Gaussian $p_\theta(\mathbf{x}|\mathbf{z}) = \mathcal{N}(\boldsymbol \mu_\theta(\mathbf{z}), diag(\boldsymbol \sigma^2_\theta(\mathbf{z})) )$. Practically speaking, our decoder would be a deep neural network that consumes $\mathbf{z}$ as input and outputs the vectors $\boldsymbol \mu_\theta(\mathbf{z}), \boldsymbol \sigma^2_\theta(\mathbf{z}) \in \mathbb{R}^n$. We are now ready to discuss the objective in terms of neural network outputs. Under this formulation, the first term in Equation~\ref{eq:elbo}, which is also commonly referred to as the \emph{reconstruction loss} or $L_{rec}$, is given by: \begin{align} L_{rec} &= \mathbb{E}_{\mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x})}[- \log p_\theta(\mathbf{x}| \mathbf{z})] \\ &= \mathbb{E}_{\mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x})}[ \sum_{i=1}^n \frac{1}{2}\log 2\pi \sigma^2_\theta(\mathbf{z})_i + \frac{(x_i - \mu_\theta(\mathbf{z})_i)^2}{2\sigma^2_\theta(\mathbf{z})_i}] \label{eq:reconloss} \end{align} where $v_i$ indicates the $i$th element of a vector $\mathbf{v}$. $L_{rec}$ is approximated via Monte-Carlo sampling; however, due to computational constraints, during training $\mathbf{z}$ is typically only sampled once per iteration. Under our formulation, the second term in Equation~\ref{eq:elbo}, which is also commonly referred to as the \emph{regularization loss} or $L_{reg}$, has a closed form expression given by: \begin{align} L_{reg} &= D_{KL}(q_\phi(\mathbf{z}|\mathbf{x}) || p_\theta(\mathbf{z})) \\ &= \frac{1}{2} ||\boldsymbol \mu_\phi(\mathbf{x})||_2^2 + \frac{1}{2} [ ||\boldsymbol \sigma_\phi(\mathbf{x}) ||_2^2 - d - \sum_{i=1}^d \log \sigma^2_{\phi}(\mathbf{x})_i] \label{eq:regloss} \end{align} The decoder is only affected by the reconstruction loss and seeks to best reconstruct $\mathbf{x}$ based on $\mathbf{z}$. The reconstruction loss thus encourages the encoder to increase the signal-to-noise ratio in $\mathbf{z}$ by decreasing $||\boldsymbol \sigma^2_\phi(\mathbf{x}) ||$ and increasing $||\boldsymbol \mu_\phi(\mathbf{x})||$. This effect is countered by the regularization loss, which encourages the encoder to increase $||\boldsymbol \sigma^2_\phi(\mathbf{x}) ||$ and decrease $||\boldsymbol \mu_\phi(\mathbf{x})||$. In many auto-encoding frameworks with regularization, whether deterministic (e.g. $L_2$ regularization) or stochastic, the weight of the regularization loss is manually tuned until the network achieves a certain desirable behavior. On the other hand, in Sections~\ref{sec:prob} and~\ref{sec:information} we will see that in a VAE the one-to-one ratio between the reconstruction loss and regularization loss has a probabilistic and information theoretic meaning. We will refer to the VAE constructed in this section as a \emph{Typical VAE} and will continue to refer to Equations~\ref{eq:reconloss} and~\ref{eq:regloss} as an illustration. However, keep in mind that a Typical VAE is just one of many possible examples of how we can choose to construct $p_\theta(\mathbf{z})$, $p_\theta(\mathbf{x}|\mathbf{z})$ and $q_\phi(\mathbf{z}|\mathbf{x})$. \section{Probabilistic Interpretation of VAEs} \label{sec:prob} \subsection{Bayes's Rule} \label{sec:bayes} The VAE was first introduced as an auto-encoder for performing Variational Bayes~\cite{vae,rezende2014stochastic}. The negative ELBO can be derived with a simple application of Bayes' Rule: \begin{align} p_\theta(\mathbf{x}) &= \frac{p_\theta(\mathbf{x}|\mathbf{z})p_\theta(\mathbf{z})}{p_\theta(\mathbf{z}|\mathbf{x})}\\ -\log p_\theta(\mathbf{x}) &= -\log p_\theta(\mathbf{x}|\mathbf{z}) - \log p_\theta(\mathbf{z}) + \log p_\theta(\mathbf{z}|\mathbf{x})\\ &= -\log p_\theta(\mathbf{x}|\mathbf{z}) - \log p_\theta(\mathbf{z}) + \log q_\phi(\mathbf{z}|\mathbf{x}) - \log q_\phi(\mathbf{z}|\mathbf{x}) + \log p_\theta(\mathbf{z}|\mathbf{x}) \label{eq:addsubtractq} \end{align} We can then take the expectation of both sides over $q_\phi(\mathbf{z}|\mathbf{x})$. Since $p_\theta(\mathbf{x})$ is constant over $\mathbf{z}$, $E_{\mathbf{z}\sim q_\phi(\mathbf{z}|\mathbf{x})} \log p_\theta(\mathbf{x}) = \log p_\theta(\mathbf{x})$. Hence: \begin{align} \begin{split} -\log p_\theta(\mathbf{x}) &= E_{\mathbf{z}\sim q_\phi(\mathbf{z}|\mathbf{x})} [-\log p_\theta(\mathbf{x}|\mathbf{z})] +\\ &\qquad D_{KL}( q_\phi(\mathbf{z}|\mathbf{x}) || p_\theta(\mathbf{z})) - D_{KL}(q_\phi(\mathbf{z}|\mathbf{x}) || p_\theta(\mathbf{z}|\mathbf{x}))\\ \end{split} \label{eq:variationalbayes} \end{align} Unfortunately, we cannot efficiently evaluate Equation~\ref{eq:variationalbayes} exactly since we do not know $p_\theta(\mathbf{z}|\mathbf{x})$. However, KL-Divergence is non-negative, so we can remove the last term in Equation~\ref{eq:variationalbayes} to obtain an upper bound equal to the negative log likelihood, which yields the negative ELBO: \begin{align} -\log p_\theta(\mathbf{x}) &\leq E_{\mathbf{z}\sim q_\phi(\mathbf{z}|\mathbf{x})} [-\log p_\theta(\mathbf{x}|\mathbf{z})] + D_{KL}( q_\phi(\mathbf{z}|\mathbf{x}) || p_\theta(\mathbf{z})) \end{align} with equality holding if and only if $D_{KL}(q_\phi(\mathbf{z}|\mathbf{x}) || p_\theta(\mathbf{z}|\mathbf{x})) = 0$ (i.e. when the encoder is able to perfectly predict $p_\theta(\mathbf{z}|\mathbf{x})$). \subsection{Importance Sampling} \label{sec:importance} Importance-Weighted Auto-Encoders~\cite{burda2015importance} use importance sampling to provide a similar derivation to Section~\ref{sec:bayes} for the negative ELBO by switching the order in which the expectation and logarithm are applied: \begin{align} -\log p_\theta(\mathbf{x}) &=-\log \int p_\theta(\mathbf{x}|\mathbf{z}) p_\theta(\mathbf{z}) d\mathbf{z}\\ &= -\log \int \frac{p_\theta(\mathbf{x}|\mathbf{z}) p_\theta(\mathbf{z}) q_\phi(\mathbf{z}|\mathbf{x})}{q_\phi(\mathbf{z}|\mathbf{x})} d\mathbf{z}\\ &=-\log \mathbb{E}_{\mathbf{z}\sim q_\phi(\mathbf{z}|\mathbf{x})} \frac{p_\theta(\mathbf{x}|\mathbf{z}) p_\theta(\mathbf{z})}{q_\phi(\mathbf{z}|\mathbf{x})} \label{eq:expectationq} \end{align} We can then apply Jensen's Inequality to switch the expectation with the logarithm, obtaining an upper bound on the negative log likelihood, which then simplifies to the negative ELBO: \begin{align} -\log p_\theta(\mathbf{x}) &\leq \mathbb{E}_{z\sim q_\phi(\mathbf{z}|\mathbf{x})} -\log \frac{p_\theta(\mathbf{x}|\mathbf{z}) p_\theta(\mathbf{z})}{q_\phi(\mathbf{z}|\mathbf{x})} \label{eq:jensen}\\ &=\mathbb{E}_{\mathbf{z}\sim q_\phi(\mathbf{z}|\mathbf{x})} [-\log p_\theta(\mathbf{x}|\mathbf{z})] + D_{KL}(q_\phi(\mathbf{z}|\mathbf{x}) || p_\theta(\mathbf{z})) \end{align} While it is not apparent under this derivation that the tightness of the negative ELBO can be quantified using $D_{KL}(q_\phi(\mathbf{z}|\mathbf{x}) || p_\theta(\mathbf{z}|\mathbf{x}))$, we can see that equality holds if $q_\phi(\mathbf{z}|\mathbf{x}) = p_\theta(\mathbf{z}|\mathbf{x})$ since the right-hand-side of Equation~\ref{eq:expectationq} becomes $-\log \mathbb{E}_{\mathbf{z} \sim p_\theta(\mathbf{z}|\mathbf{x})} \frac{p_\theta(\mathbf{x}|\mathbf{z}) p_\theta(\mathbf{z})}{p_\theta(\mathbf{z}|\mathbf{x})} = - \log \mathbb{E}_{\mathbf{z} \sim p_\theta(\mathbf{z}|\mathbf{x})} p_\theta(\mathbf{x}) = - \log p_\theta(\mathbf{x}) $. The key advantage of the importance sampling interpretation is that Equation~\ref{eq:expectationq} gives us a method to approximate the true negative log-likelihood without knowledge of $p_\theta(\mathbf{z}|\mathbf{x})$. In the asymptotic case where we take infinite samples, the approximation can become arbitrarily close. However, if the inferred posterior $q_\phi(\mathbf{z}|\mathbf{x})$ deviates too much from the true posterior $p_\theta(\mathbf{z}|\mathbf{x})$, importance sampling may require a prohibitively large number of samples to be accurate. \subsection{VAEs and Normalizing Flow} \label{sec:flow} An alternative maximum likelihood model to VAEs are the more expressive but heavyweight normalizing flow models~\cite{nice}. In this section, we will look at how a VAE with a Gaussian inferred posterior (but not necessarily diagonal, as in a Typical VAE) could in principle match the performance of normalizing flow models. However, such a VAE would be computationally no easier to train than a flow model. Normalizing flow leverages the change-of-variables formula: let $f$ be an invertible function and $J$ be the Jacobian of $f$. The negative log likelihood of $\mathbf{x}$ can be evaluated using: \begin{align} -\log p(\mathbf{x}) &= -\log p(f^{-1}(\mathbf{x})) - \log |J^{-1}| \label{eq:cov} \end{align} where $|J^{-1}|$ is the absolute value of the determinant of $J^{-1}$. Normalizing flow models learn neural networks that are guaranteed to be invertible and for which $|J^{-1}|$ can be efficiently computed. An invertible mapping $f$ is learned from a latent space $\mathbf{z}$ (where inference and generation can be easily done on $p_\theta(\mathbf{z})$) to the data space $\mathbf{x}$. Equation~\ref{eq:cov} can then be efficiently used as an objective function for maximum likelihood. Consider a VAE where $p_\theta(\mathbf{z})$ is an isotropic Gaussian as in a Typical VAE, but the covariance matrix of $q_\phi(\mathbf{z}|\mathbf{x})=\mathcal{N}(\boldsymbol \mu, \Sigma)$ is no longer restricted to be diagonal. For simplicity, we will assume that the output distribution is also an isotropic Gaussian (i.e. for all $\mathbf{z}$, $\boldsymbol \sigma^2_\theta(\mathbf{z})=\sigma^2_\theta \mathbf{1}$ where $\sigma^2_\theta$ is a scalar). We will refer to such a VAE as a $\Sigma$-VAE. We will now show that for any normalizing flow model that learns an invertible function $f$ from $\mathbf{z}$ to $\mathbf{x}$, a $\Sigma$-VAE can in theory approach a solution where the negative ELBO would be equivalent to Equation~\ref{eq:cov}. Consider a $\Sigma$-VAE where $\boldsymbol \mu_\theta(\mathbf{z}) = f(\mathbf{z})$, $\boldsymbol \mu_\phi(\mathbf{x}) = f^{-1}(\mathbf{x})$, the covariance matrix is $\Sigma_\phi(\mathbf{x}) = \epsilon^2 J^{-1} {J^{-1}}^T$, and $\sigma^2_\theta = \epsilon^2$ where $\epsilon^2>0$ is a small scalar. Note that since $f$ is invertible, $\mathbf{z}$ must have the same dimensionality as $\mathbf{x}$. Then we can sample a random vector $\mathbf{u}\sim \mathcal{N}(0,\mathbf{I})$ and use the reparameterization trick to sample from $q_\phi(\mathbf{z}|\mathbf{x}) = \mathcal{N}(\boldsymbol \mu_\phi(\mathbf{x}), \Sigma_\phi(\mathbf{x}))$, in which case \begin{align} \mathbf{z} &= f^{-1}(\mathbf{x}) + \epsilon J^{-1} \mathbf{u} \end{align} By definition of the Jacobian, for any vectors $\mathbf{z},\mathbf{v}$, we have: \begin{align} \frac{f(\mathbf{z}+\epsilon \mathbf{v}) - f(\mathbf{z})}{\epsilon} = J\mathbf{v} + \mathbf{r} \end{align} for some remainder vector $\mathbf{r}$ where $\lim_{\epsilon \to 0} \mathbf{r} = 0$. This gives us: \begin{align} \boldsymbol \mu_\theta(\mathbf{z}) &= f(f^{-1}(\mathbf{x}) + \epsilon J^{-1} \mathbf{u}) \\ &= f(f^{-1}(\mathbf{x}))+ \epsilon J J^{-1} \mathbf{u} + \epsilon \mathbf{r}\\ &= \mathbf{x} + \epsilon \mathbf{u} + \epsilon \mathbf{r} \end{align} Then according to Equation~\ref{eq:reconloss}, our reconstruction loss $L_{rec}$ is given by: \begin{align} L_{rec} &= \mathbb{E}_{\mathbf{u}\sim \mathcal{N}(0,\mathbf{I})} [\frac{n}{2}\log(2 \pi \epsilon^2) + \frac{ ||\mathbf{x} + \epsilon \mathbf{u} + \epsilon \mathbf{r} - \mathbf{x}||_2^2}{2\epsilon^2}] \\ & = \frac{1}{2} [n\log(2 \pi ) + n\log \epsilon^2 + \mathbb{E}_{\mathbf{u}\sim \mathcal{N}(0,\mathbf{I})}[||\mathbf{u}-\mathbf{r}||_2^2]] \end{align} The regularization loss is given by: \begin{align} L_{reg} &= D_{KL} ( \mathcal{N}(\boldsymbol \mu_\phi(\mathbf{x}), \Sigma_\phi(\mathbf{x})) || \mathcal{N}(0,\mathbf{I}) )\\ &= \frac{1}{2}[|| \boldsymbol \mu_\phi(\mathbf{x}) ||_2^2 - \log |\epsilon^2 J^{-1} {J^{-1}}^T| - n + \text{trace}(\epsilon^2 J^{-1} {J^{-1}}^T) ]\\ &= \frac{1}{2}[|| f^{-1}(\mathbf{x}) ||_2^2 - \log |J^{-1}|^2 - n \log \epsilon^2 - n + \epsilon^2 \text{trace} ( J^{-1} {J^{-1}}^T)] \end{align} Then the total objective function is given by: \begin{align} L &=L_{rec}+L_{reg}\\ \begin{split} &= \frac{1}{2} [ n\log(2 \pi ) + || f^{-1}(\mathbf{x}) ||_2^2] - \log |J^{-1}|^2 + \\ &\qquad \mathbb{E}_{\mathbf{u}\sim \mathcal{N}(0,\mathbf{I})}[||\mathbf{u}-\mathbf{r}||_2^2] - n + \epsilon^2 \text{trace} ( J^{-1} {J^{-1}}^T)]\\ \end{split} \end{align} If we take the limit as $\epsilon \to 0$, then $\mathbf{r}$ approaches $0$, so $\lim_{\epsilon\to 0} \mathbb{E}_{\mathbf{u}\sim \mathcal{N}(0,\mathbf{I})}[||\mathbf{u}-\mathbf{r}||_2^2] = \mathbb{E}_{\mathbf{u}\sim \mathcal{N}(0,\mathbf{I})}||\mathbf{u}||_2^2 = n$. Since $\text{trace} ( J^{-1} {J^{-1}}^T)$ is constant with respect to $\epsilon$, $\lim_{\epsilon\to 0} \epsilon^2 \text{trace} ( J^{-1} {J^{-1}}^T) = 0$. Thus \begin{align} \lim_{\epsilon\to 0} L &= \frac{1}{2} [ n\log(2 \pi ) + || f^{-1}(\mathbf{x}) ||_2^2 - \log |J^{-1}|^2 ] \\ &= -\log p_\theta(f^{-1}(\mathbf{x})) - \log |J^{-1}| \label{eq:simplifycov} \end{align} which is the same as Equation~\ref{eq:cov}. Note that the simplification in Equation~\ref{eq:simplifycov} can be done because $p_\theta(\mathbf{z}) = \mathcal{N}(0,\mathbf{I})$. Since the negative ELBO approaches the true negative log-likelihood as $\epsilon\to 0$, we can also conclude that $\lim_{\epsilon\to 0} D_{KL}( q_\phi(\mathbf{z}||\mathbf{x}) || p_\theta(\mathbf{z}||\mathbf{x})) = 0$. Hence, a $\Sigma$-VAE could in principle match the modelling capacity of any normalizing flow model. However, in practice there would be a computational bottleneck in computing the determinant of the Jacobian when calculating the regularization loss, meaning that training a $\Sigma$-VAE would be no easier than training a normalizing flow model. If we force the covariance matrix $\Sigma$ to be a diagonal matrix as in a Typical VAE, then inference becomes efficient, but log-likelihood can only be approximated as described in this section for functions such that $J^{-1} {J^{-1}}^T$ is diagonal. If we consider the SVD of $J^{-1} = UDV^T$, we see that the covariance matrix is diagonal when $VD^2V^T$ is diagonal. This can happen when all the eigenvalues of $J$ are equal or when $V$ is a permutation matrix. $V$ is a permutation matrix if each of the dimensions in the latent vector $\mathbf{z}$ influence $\mathbf{x}$ independently. Thus, though restricting $\Sigma$ to be a diagonal matrix limits the class of functions we can model, it may also naturally encourage disentanglement. The relationship between VAEs and disentanglement remains an active area of research~\cite{betavae,chen2018isolating}. We also highlight that regardless of whether $\Sigma$ is diagonal or not, the Gaussian modelling assumptions of our model do not restrict the modelling capacity of a VAE to only Gaussian-like data. \section{Information Theoretic Interpretation of VAEs} \label{sec:information} \subsection{Lossless Compression} \label{sec:lossless} Maximum likelihood can also be viewed as a lossless compression problem. The negative log likelihood $- \mathbb{E}_{\mathbf{x} \sim p_{gt}(\mathbf{x})} \log p_\theta(\mathbf{x}) $ is the optimal expected number of bits needed to describe a sample from $p_{gt}(\mathbf{x})$ based on $p_\theta(\mathbf{x})$. VLAE~\cite{vlae} shows that the negative ELBO $-\mathcal{L}(\mathbf{x})$ is an upper bound on this number by constructing a code to describe $p_{gt}(\mathbf{x})$ that on average uses $-\mathcal{L}(\mathbf{x})$ bits. Suppose a sender and receiver have access to our VAE, and the sender wishes to send a vector $\mathbf{x} \sim p_{gt}(\mathbf{x})$ to the receiver. The sender could first sample $\mathbf{z}\sim q_\phi(\mathbf{z}|\mathbf{x})$. Sending $\mathbf{z}$ will cost $-\log p_\theta(\mathbf{z})$ bits. The receiver can then use the VAE to decode $p_\theta(\mathbf{x}|\mathbf{z})$. The sender can then spend another $-\log p_\theta(\mathbf{x}|\mathbf{z})$ bits to send an additional code (e.g. the error-correcting code of a reconstruction) that could then describe $\mathbf{x}$ exactly. The sender on average spends $-\log p_\theta(\mathbf{z}) - \log p_\theta(\mathbf{x}|\mathbf{z})$ bits to describe $\mathbf{x}$. However, since the receiver now knows $\mathbf{x}$, it can then use the VAE to know $q_\phi(\mathbf{z}|\mathbf{x})$, from which it can decode a secondary message. For example, if the VAE is reparameterized as in Equation~\ref{eq:reparameterize}, then the receiver now also knows the value of $\mathbf{u}$, which contains $-\log q_\phi(\mathbf{z}|\mathbf{x})$ bits of information. The expected cost $C$ used to describe $\mathbf{x}$ with this coding scheme is thus given by: \begin{align} C = \mathbb{E}_{\mathbf{z}\sim q_\phi(\mathbf{z}|\mathbf{x})}[-\log p_\theta(\mathbf{z}) - \log p_\theta(\mathbf{x}|\mathbf{z}) + \log q_\phi(\mathbf{z}|\mathbf{x})] \end{align} which is equal to the negative ELBO. Based on this interpretation we can intuitively understand how the reconstruction loss and regularization loss interact with each other in a Typical VAE. The reconstruction loss essentially copies information from the input space to the latent space, and the regularization loss compresses that information. Even if information in the input space is incompressible (i.e. because it is pure noise), copying it into to the latent space will not hurt the negative log likelihood (although it will not help either). Thus, in an ideal optimization landscape, during training we would generally expect the reconstruction loss to decrease and the regularization loss to increase as more information gets stored in the latent space. Although VAEs are sometimes stereotypically associated with blurry reconstructions and heavy stochastic noise in the latent space, in reality as training progresses the VAE should exhibit essentially perfect reconstructions and increasingly deterministic behavior as training progresses. \subsection{Continuous versus Discrete Data} \label{sec:discrete} So far our discussion has been limited to continuous data. However, in practice the data we work with is often discrete or quantized, so our discussion is incomplete without considering to what degree of accuracy we wish to describe $\mathbf{x}$. For example, we typically wish to describe $RGB$ images to $8$-bit accuracy. Hence, assuming that our data is normalized to lie in the range $[0,1]$, the cost $L_{rec}$ to describe the reconstruction error for an image using the coding scheme in Section~\ref{sec:lossless} would more accurately be written as: \begin{align} L_{rec}(\mathbf{x},\mathbf{z}) &= - \log \int_{\mathbf{u} \in [0,\frac{1}{256})^n} p_\theta(\mathbf{x}+\mathbf{u} | \mathbf{z}) d\mathbf{u} \label{eq:discrete} \end{align} In Section~\ref{sec:lossless}, we discussed that in a nice optimization landscape, we expect the reconstruction loss to decrease and the regularization loss to increase during training. However, for discrete data, this can only occur until $L_{rec}$ reaches $0$, at which point the reconstruction loss can no longer decrease and the regularization loss will begin to decrease as compression occurs. Since Equation~\ref{eq:discrete} requires taking an integral, when working with discrete data it may be beneficial to model $-\log p_\theta(\mathbf{x}|\mathbf{z})$ using a distribution for which taking the cumulative distribution function (CDF) is efficient and differentiable. Thus instead of modelling $-\log p_\theta(\mathbf{x}|\mathbf{z})$ with an isotropic Gaussian as in a Typical VAE, VAE-IAF~\cite{kingma2016improved} instead uses the similarly bell-shaped isotropic logistic distribution, for which the CDF is given by the sigmoid function. The units for evaluating a maximum likelihood model for image data is bits per dim (bits/dim), which is the number of bits such a model would need to losslessly describe each pixel of the image to $8$-bit accuracy. Any model with a negative log-likelihood of more than $8$ bits/dim is worse than useless as describing the raw pixel values only requires $8$ bits/dim. Current state-of-the-art maximum likelihood models require a little less than $3$ bits/dim~\cite{child2019generating}. \subsection{Transmission Across a Noisy Gaussian Channel} \label{sec:transmission} Once $L_{rec}$ reaches $0$, we can draw an analogy between a VAE and the classical problem of transmission across a memoryless noisy Gaussian channel. In such a problem, a sender wishes to reliably describe $\mathbf{x}$ by transmitting a continuous number $\hat{z}$ across a noisy Gaussian channel $d$ times. However, due to power constraints, the sender can only send a strong enough signal such that $\mathbb{E} [\hat{z}^2] = P$. Moreover, every time the sender sends a signal, the channel adds Gaussian noise $y$ such that $\mathbb{E} [y^2] = N$. Hence the receiver receives $d$ transmissions of $z = \hat{z} + y$. If $P+N=1$, then $\mathbb{E} [z^2] = 1$. The capacity $R$ of a Gaussian channel with noise $N$ and power $P=1-N$ is given by~\cite{cover2012elements}: \begin{align} R &=-\frac{1}{2}\log(N) \end{align} If the channel has capacity $R$, then $dR$ bits of information can reliably be transmitted across the channel with arbitrarily low probability of error as $d$ increases. Transmission across a noisy channel can thus be viewed as the dual problem of compression, since the ability to describe reliably $\mathbf{x}$ using $d$ transmissions of a channel with capacity $R$ indicates an ability to compress $\mathbf{x}$ into a representation of at most $dR$ bits. In an analogous VAE, $p_\theta(\mathbf{z}) = \mathcal{N}(0,\mathbf{I})$, $q_\phi(\mathbf{z}|\mathbf{x}) = \mathcal{N}(\boldsymbol \mu_\phi(\mathbf{x}), N_\phi(\mathbf{x}) \mathbf{I})$ where $N_\phi(\mathbf{x})>0$ is a scalar, $\mathbf{x} \in \mathbb{R}^n, \mathbf{z} \in \mathbb{R}^d$. $P_\phi(\mathbf{x})= \frac{||\boldsymbol \mu_\phi(\mathbf{x})||_2^2}{d} $ corresponds to the power, each dimension of $\boldsymbol \mu_\phi(\mathbf{x})$ corresponds to a transmission $\hat{z}$ across the noisy channel, $N_\phi(\mathbf{x})$ corresponds to the noise, and each dimension of $\mathbf{z}$ corresponds to a received transmission $z$. If we set $N_\phi(\mathbf{x})=1-P_\phi(\mathbf{x})$, then according to Equation~\ref{eq:regloss}, the expected regularization loss $L_{reg}$ is given by: \begin{align} L_{reg}(\mathbf{x}) & = \frac{1}{2} ||\boldsymbol \mu_\phi(\mathbf{x})||_2^2 + \frac{1}{2} [ d N_\phi(\mathbf{x}) - d - d \log N_\phi(\mathbf{x})]\\ & = \frac{1}{2} dP_\phi(\mathbf{x}) + \frac{1}{2} [ dN_\phi(\mathbf{x}) - d - d \log N_\phi(\mathbf{x})] \\ & =-\frac{1}{2}d\log(N_\phi(\mathbf{x})) \end{align} which is equal to $dR$ in the transmission problem. We now give an intuitive geometric explanation for why a channel with power $P$ and noise $N$ (where $P+N=1$) has capacity $R=-\frac{1}{2}\log(N)$. A formal proof is given in~\cite{cover2012elements}. By the law of large numbers, as $d$ increases, $||\mathbf{z}||=1$ for almost all $\mathbf{z}\sim \mathcal{N}(0,\mathbf{I})$, so $\mathbf{z}$ essentially forms a uniform distribution on the surface of the unit hyper-sphere. Let $V$ be the volume of the unit hyper-sphere. Similarly, $\mathbf{z}$ will lie uniformly on the surface of the hyper-sphere with radius $\sqrt{N}$ and center $\boldsymbol \mu$ for almost all $\mathbf{z}\sim \mathcal{N}(\boldsymbol \mu, N \mathbf{I})$. The volume of a hyper-sphere with radius $\sqrt{N}$ is given by $V_N = V N^{\frac{d}{2}}$. We can thus expect to fit $\frac{V}{V_N} = N^{-\frac{d}{2}} = 2^{dR}$ unique non-overlapping hyper-spheres of radius $\sqrt{N}$ into the unit hyper-sphere. We can thus create a transmission scheme as follows. A codebook is created that maps every point $\mathbf{x}$ to a hyper-sphere with volume proportional to $p_{gt}(\mathbf{x})$ and revealed to both the sender and receiver. Each hyper-sphere has center $\boldsymbol \mu$ and radius $\sqrt{N}$ such that $N + \frac{||\boldsymbol \mu||_2^2}{d} =1$. During transmission, the sender maps each input $\mathbf{x}$ to the center $\boldsymbol \mu$ of its corresponding hyper-sphere, which is transmitted across the channel. The receiver then uses the codebook to map each received point $\mathbf{z}$ to the center $\boldsymbol \mu$ of the hyper-sphere that $\mathbf{z}$ belongs to, which can then be mapped to the input image $\mathbf{x}$. Since there are finitely many values $\mathbf{x}$ can take when it is discrete, constructing such a codebook is possible in theory. However, in practice, for a $32\times 32$ resolution RGB image, there would be $256^{3072}$ possible values of $\mathbf{x}$, so calculating such a codebook by brute force would be prohibitively expensive. Optimizing a neural network to learn such a coding scheme would also be difficult since mapping a point to the center of the hyper-sphere that it belongs to would be a non-diffierential operation. VQ-VAE~\cite{oord2017neural} takes a step in this direction by using the straight-through gradient estimator. One counter-intuitive result of information theory is that the rate of a memoryless noise channel is optimal, meaning that we could do no better if we were able to send each transmission $\hat{z}_i$ with knowledge of what the receiver received for $z_j$ for all all $j<i$. In other words, when $d$ is large enough, the modelling capacity of a VAE is not inhibited by the assumption that the inferred posterior has diagonal covariance, and in theory a Typical VAE should be able to model any distribution to arbitrary accuracy. Indeed, in the above transmission scheme $q_\phi(\mathbf{z}|\mathbf{x}) =p_\theta(\mathbf{z}|\mathbf{x})$, so the negative ELBO would be an exact estimate of the negative log-likelihood. This is despite making no assumptions about whether $p_{gt}(\mathbf{x})$ is Gaussian or that the latent dimensions of $\mathbf{z}$ affect $\mathbf{x}$ independently. This is consistent with the results of Section~\ref{sec:flow} since the mapping from $\mathbf{z}$ to $\mathbf{x}$ is not invertible. However, though VAEs may have the capacity to model a distribution $p_\theta(\mathbf{x})$, in practice they are usually unable to learn such a solution due to computational constraints and a difficult optimization landscape. \section{Misconceptions About VAEs} \label{sec:misconceptions} In this section, we will look at misconceptions about VAEs that I have encountered in teaching materials and among other researchers in computer vision and machine learning. Not all readers may hold these miconceptions, so those who can correctly answer all of the following questions can skip this section: \begin{itemize} \item \textbf{Q:} Can VAEs be trained using mean-squared error as the reconstruction loss? \textbf{A:} No. \item \textbf{Q:} Should VAEs have blurry or sharp reconstructions? \textbf{A:} Reconstructions should be essentially perfect. \item \textbf{Q:} Are VAEs only able to model data that is highly Gaussian? \textbf{A:} No. \item \textbf{Q:} Suppose $p_{gt}(\mathbf{x})$ is an isotropic Gaussian. How many dimensions does the latent space of a Typical VAE need to be in order to model $p_{gt}$? \textbf{A:} $0$. $\mathbf{z}$ can be ignored and need not exist. \item \textbf{Q:} Suppose $p_{gt}(\mathbf{x})$ where $\mathbf{x} \in \mathbb{R}^n$ consists of $k>1$ mixtures of isotropic Gaussians. How many dimensions does the latent space of a Typical VAE need to be in order to model $p_{gt}$? \textbf{A:} $n$. The number of mixtures $k$ is irrelevant. \end{itemize} \subsection{VAEs Cannot Be Trained With The Mean-Squared Error Loss} \label{sec:mse} Minimizing the Mean-Squared Error ($MSE$) in lieu of $-\log p_\theta(\mathbf{x}|\mathbf{z})$ is a common mistake I have encountered in casual conversation, a peer review, and at least one prominent blog/code tutorial on VAEs. In fact, using $MSE$ as the reconstruction loss is extremely problematic for maximum likelihood and results in the VAE being highly over-regularized. The $MSE$ objective can be defined as: \begin{align} MSE = \frac{1}{n}\mathbb{E}_{\mathbf{x}\sim p_{gt}(\mathbf{x}), \mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x})} ||\mathbf{x} - \boldsymbol \mu_\theta(\mathbf{z})||_2^2 \end{align} In a simplified Typical VAE where $\boldsymbol \sigma^2_\theta(\mathbf{z}) = \sigma^2_\theta \mathbf{1}$ as described in Section~\ref{sec:flow}, the reconstruction loss is given by: \begin{align} L_{rec} &= \frac{1}{n}\mathbb{E}_{\mathbf{x}\sim p_{gt}(\mathbf{x}), \mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x})}[-\log p_\theta(\mathbf{x}|\mathbf{z})]\\ &= \mathbb{E}_{\mathbf{x}\sim p_{gt}(\mathbf{x}), \mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x})} [ \frac{1}{2}[\log(2\pi\sigma_\theta^2)+\frac{||\mathbf{x}-\boldsymbol \mu_\theta(\mathbf{z})||_2^2}{\sigma_\theta^2}] ]\\ &=\frac{1}{2}[\log(2\pi\sigma_\theta^2) + \frac{1}{\sigma_\theta^2} MSE] \label{eq:lrecmse} \end{align} Note that we have normalized $MSE$ and $-\log p_\theta(\mathbf{x}|\mathbf{z})$ by $\frac{1}{n}$ for simplicity, which is common practice (see Section~\ref{sec:discrete}). We see that we obtain the $MSE$ objective by assuming $\sigma^2_\theta=\frac{1}{2}$ throughout training and ignoring the first term in Equation~\ref{eq:lrecmse}, which would now be constant. Such an assumption would obviously be sub-optimal from a maximum likelihood standpoint; in fact we can analytically see that, given $MSE$, Equation~\ref{eq:lrecmse} is minimized when $\sigma^2_\theta = MSE$, in which case $L_{rec}$ simplifies to: \begin{align} L_{rec} = \frac{1}{2}[\log(2 \pi MSE)+1] \label{eq:logmse} \end{align} Hence, minimizing negative log-likelihood introduces a logarithm operation in front of the $MSE$ objective. This should fall in line with our intuition from a lossless compression standpoint, since if the average value of the reconstruction error $|\mathbf{x} - \boldsymbol \mu_\theta(\mathbf{z})|$ were cut in half, which would cut $MSE$ by three-quarters, we would expect to require one fewer bit to describe the reconstruction error. The central practical difference between using $MSE$ and $\log MSE$ as a reconstruction loss for a VAE is that as the magnitude of $MSE$ decreases by a factor of $c^2$, the gradient of $c^2 MSE$ decreases by a factor of $c$ while the gradient of $\log c^2 MSE = \log c^2 + \log MSE$ remains constant. This results in several problems for $MSE$. First, since we expect $MSE$ to decrease during training, the gradient of the reconstruction loss relative to the regularization loss becomes weaker and weaker---often by several orders of magnitude---as training progresses. We expect the model to thus be much more highly regularized at the end of training compared to the beginning. Second, the scale of the input data essentially becomes a hyper-parameter that controls how much we wish to balance the initial weight of the reconstruction loss compared to the regularization loss. For example, we can make $MSE < \epsilon^2$ for arbitrarily small $\epsilon>0$ by simply normalizing all our input data to lie in the range $[0,\epsilon]$. Thus, training a VAE with $MSE$ as the reconstruction loss could more accurately be described as ``an auto-encoder with stochastic regularization that generates useful or beautiful samples". Using $MSE$ to assess the reconstruction capabilities of a VAE thus becomes quite meaningless. For example, one top tier conference paper incorrectly declared that their VAE had essentially memorized a natural image dataset when they had achieved a $MSE$ of roughly $0.01$, which is an ostensibly low number. However, since the data was normalized to lie in the range $[0,1]$, a $MSE$ of $0.01$ meant that reconstructions were off by an average of roughly 25 pixel values if normalized back to $0-255$ range. From a lossless compression standpoint as discussed in Section~\ref{sec:discrete}, if we calculated $L_{rec}+8$ using Equation~\ref{eq:logmse}, their model would cost an average of around $7.4$ bits just to describe the reconstruction error of each pixel to $8$-bit accuracy; for context, state-of-the-art VAEs with a diagonal Gaussian posterior can achieve a total negative log-likelihood (including both the reconstruction and the latent cost) of around $3.5$ bits per pixel. The above problems all point to VAEs trained with $MSE$ being extremely over-regularized during training when the input data is scaled to lie in the range $[0,1]$. The over-regularization due to incorrectly using $MSE$ instead of $\log MSE$ as a reconstruction loss is also a source of the stereotype that VAEs have ``blurry" reconstructions when in fact a properly trained VAE should have nearly perfect reconstructions as discussed in Section~\ref{sec:lossless}. Over-regularization can be further amplified when the architecture of the VAE is intentionally restricted so that the latent space is low-dimensional and thus inexpressive (e.g. an hour-glass shaped architecture). On the other hand, a potential benefit of over-regularization is that the latent space only stores the most highly compressible information, which tend to be global structures. Hence, an over-regularized VAE can also be thought of as a \emph{lossy} compressor. This may be beneficial for related downstream tasks like representation learning or disentanglement. Additionally, the required $MSE$ necessary to achieve state-of-the-art maximum likelihood results is often significantly lower than the threshold of human perception. If our goal is to sample perceptually pleasing images or perform lossy compression, then we may want to over-regularize our model to tolerate higher reconstruction errors (leading to sub-optimal likelihood) at the benefit of better compression and sampleability. A more thorough discussion and an algorithm to control these trade-offs associated with over-regularization can be found in~\cite{rezende2018taming}. \subsection{The Latent Vector Is Not A Parameter} \label{sec:latentparameter} The encoder in a Typical VAE \emph{learns} the parameters $\phi$ of a neural network so that given an input $\mathbf{x}$, it can \emph{predict} the parameters $\boldsymbol \mu_\phi(\mathbf{x}), \boldsymbol \sigma^2_\phi(\mathbf{x})$ of a Gaussian distribution from which $\mathbf{z}$ is sampled. The latent vector $\mathbf{z}$ is \emph{not} a parameter that describes the distribution, but rather a \emph{variable} that describes an individual data point $\mathbf{x}$. Another misconception about VAEs that I have encountered in casual conversation, a peer review, and at least one university graduate course is to think of the parameters $\boldsymbol \mu_\phi(\mathbf{x}), \boldsymbol \sigma^2_\phi(\mathbf{x})$ as \emph{learned} rather than predicted and/or to in turn think of the latent vector $\mathbf{z}$ as a parameter rather than a variable. To illustrate this, let us consider a toy case of a Typical VAE modelling $p_{gt}(\mathbf{x}) = \mathcal{N}(\boldsymbol \mu_{gt}, \sigma^2_{gt} \mathbf{I})$ where $\mathbf{x}, \mathbf{z} \in\mathbb{R}^n$. Those who view $\mathbf{z}$ as a parameter may incorrectly guess that the global optimum to ``learn the distribution" involves setting $q_\phi(\mathbf{z}|\mathbf{x}) = \mathcal{N}(\boldsymbol \mu_{gt}, \sigma^2_{gt} \mathbf{I}) = p_{gt}(\mathbf{x})$. This would clearly be sub-optimal as $q_\phi(\mathbf{z}|\mathbf{x})$ contains no information about $\mathbf{x}$ while incurring a non-zero regularization loss (unless the prior is constructed so that $p_\theta(\mathbf{z}) = p_{gt}(\mathbf{x})$). Let us consider two valid solutions. One obvious global optimum would be for the VAE to ignore the latent space, so $q_\phi(\mathbf{z}|\mathbf{x}) = p_\theta(\mathbf{z})$ and $p_\theta(\mathbf{x}|\mathbf{z}) = p_\theta(\mathbf{x}) = p_{gt}(\mathbf{x}) = \mathcal{N}(\boldsymbol \mu_{gt}, \sigma^2_{gt} \mathbf{I})$. Another solution would be for the VAE to learn to essentially act as a deterministic regular auto-encoder, so $q_\phi(\mathbf{z}|\mathbf{x}) = \mathcal{N}(\frac{\mathbf{x} - \boldsymbol \mu_{gt}}{\sigma_{gt}}, \epsilon^2 \mathbf{I})$ and $p_\theta(\mathbf{x}|\mathbf{z}) = \mathcal{N}(\sigma_{gt}\mathbf{z} +\boldsymbol \mu_{gt}, \sigma^2_{gt} \epsilon^2 \mathbf{I})$. It is easy to verify that this solution is a global minimum that achieves the same negative log-likelihood as the first solution as $\epsilon \to 0$. In both solutions, knowledge about the distribution (i.e. knowledge about $\boldsymbol \mu_{gt}$ and $\sigma^2_{gt}$) are embedded in the parameters $\theta$ and (in the second solution) $\phi$. In the first solution $\mathbf{z}$ is completely uninformative and would still be a valid solution if $\mathbf{z}$ did not exist. In the second solution, $\mathbf{z}$ describes the data point $\mathbf{x}$ exactly but contains no information of the distribution or its parameters. As $\mathbf{z}$ describes a data point, even if $p_{gt}$ were a $k$-mixture of Gaussians, $\mathbf{z}$ would still only need to be $n$-dimensional and not $kn$-dimensional (which would be the case if $\mathbf{z}$ were estimating parameters). A consequence of incorrectly viewing $\mathbf{z}$ as a parameter is that one will under-estimate the expressivity of a VAE. Since the information about $p_{gt}$ is all embedded in $\phi$ and $\theta$, which can be arbitrarily powerfully parameterized, VAEs can model complicated non-Gaussian distributions as discussed in Sections~\ref{sec:flow} and~\ref{sec:transmission} and empirically shown in Section~\ref{sec:code}. However, if one incorrectly believes that the purpose of the latent vector $\mathbf{z}$ is to estimate the parameters of a distribution, then one may expect that a VAE can only model data similar to the isotropic Gaussian prior $p_\theta(\mathbf{z})$. \section{Example: Toy 2D Data} \label{sec:code} \begin{figure}[t] \centering \begin{subfigure}[b]{0.48\textwidth} \centering \includegraphics[width=\linewidth]{figures/prob8g.png} \includegraphics[width=\linewidth]{figures/probc.png} \includegraphics[width=\linewidth]{figures/prob2s.png} \caption{The ground truth probability of each pixel (left) and estimated probability from the VAE (right).} \label{fig:density} \end{subfigure} \begin{subfigure}[b]{0.48\textwidth} \centering \includegraphics[width=\linewidth]{figures/color8g.png} \includegraphics[width=\linewidth]{figures/colorc.png} \includegraphics[width=\linewidth]{figures/color2s.png} \caption{Color correspondence between the ground truth distribution (left) and the latent space (right).} \label{fig:latent} \end{subfigure} \caption{We perform density estimation and visualize the latent space for three 2D distributions. Yellow indicates high probability density and purple indicates low density.} \label{fig:typical} \end{figure} \begin{figure}[t] \centering \begin{subfigure}[b]{0.48\textwidth} \centering \includegraphics[width=\linewidth]{figures/prob8g_big.png} \includegraphics[width=\linewidth]{figures/probc_big.png} \includegraphics[width=\linewidth]{figures/prob2s_big.png} \caption{The ground truth probability of each pixel (left) and estimated probability from the VAE (right).} \end{subfigure} \begin{subfigure}[b]{0.48\textwidth} \centering \includegraphics[width=\linewidth]{figures/color8g_big.png} \includegraphics[width=\linewidth]{figures/colorc_big.png} \includegraphics[width=\linewidth]{figures/color2s_big.png} \caption{Color correspondence between the ground truth distribution (left) and the latent space (right).} \end{subfigure} \caption{Density Estimation and Latent Space Visualization for VAEs trained on a large batch size of 40000.} \label{fig:big} \end{figure} \begin{table} \begin{subtable}{0.65\textwidth} \centering \begin{tabular}{|c|c|c|c|} \hline Data&$H$&-ELBO&NLL\\ \hline 8 Gaussians& -1.92&-1.81&-1.86\\ Checkerboard& -1&-0.73&-0.81\\ 2 Spirals& -2.34&-1.98&-2.15\\ \hline \end{tabular} \caption{Batch Size 200.} \label{tab:nll} \end{subtable} \begin{subtable}{0.32\textwidth} \begin{tabular}{|c|c|c|} \hline Data&-ELBO&NLL\\ \hline 8G& -1.90&-1.91\\ C&-0.87&-0.92\\ 2S&-2.09&-2.21\\ \hline \end{tabular} \caption{Batch Size 40000.} \label{tab:nll_big} \end{subtable} \caption{Negative Log Likelihood Results on each of the 2D datasets for a Typical VAE. $H$ is the entropy of the ground truth distribution. -ELBO is the negative ELBO calculated using one sample from $\mathbf{z}\sim q_\phi(\mathbf{z}|\mathbf{x})$. NLL is the approximate negative log-likelihood. We show results for a VAE trained on a standard batch size of 200 (Table~\ref{tab:nll}) and a VAE trained on a prohibitively large batch size of 40000 (Table~\ref{tab:nll_big}).} \end{table} We train VAEs on several toy 2D distributions. Details of results and implementation can be found in the Jupyter notebook\footnote{Notebook can be found at https://github.com/ronaldiscool/VAETutorial}. We summarize key results below. \subsection{Typical VAEs} Each Typical VAE has two latent dimensions. The architecture takes roughly 1 to 2 GB of GPU and takes 20 minutes to train on a K80 on Google Colab. We trained for 60000 iterations with a batch size of 200 input samples at each iteration. In Figure~\ref{fig:density}, we see density estimation results on several 2D datasets: a multi-modal Gaussian distribution (which we will call ``8 Gaussians``) , a uniform distribution over a checkerboard (``Checkerboard"), and a uniform distribution over 2 spirals (``2 Spirals"). A Typical VAE with 2 latent dimensions can capture the general shape of each distribution. However, the VAE also assigns non-trivial amounts of probability density to what should be low-density areas such as the space between two Gaussian clusters in ``8 Gaussians", the connection between two squares in ``Checkerboard", and the center of ``2 Spirals". As a result, less density is estimated on the ground-truth high-density areas, so in Figure~\ref{fig:density} the ground truth distributions are more yellow than the predicted distributions. We display the negative log-likelihood of a Typical VAE trained on each dataset in Table~\ref{tab:nll}. The second column indicates the entropy $H$ of the ground truth distribution, which is also a lower bound for the negative log likelihood of a maximum likelihood model since $\mathbb{E}_{\mathbf{x} \sim p_{gt}(\mathbf{x})} -\log p_\theta(\mathbf{x}) = H + D_{KL}(p_{gt}(\mathbf{x}) || p_\theta(\mathbf{x})) \geq H$. The third column is the negative ELBO. The fourth column is the negative log likelihood approximated by taking 250 importance samples using Equation~\ref{eq:expectationq}. We can see how tight of a bound the negative ELBO is by comparing its value with the true negative log likelihood. We see that the VAE is nearly optimal on the ``8 Gaussians" dataset and the negative ELBO is almost exact. However, there is room for improvement on the other two distributions. We visualize the correspondence between the input space and the latent space in Figure~\ref{fig:latent}. We see that the VAE copies information from the input space into the latent space and then expands the high density (colored) regions, which by extension contracts the low-density (dark) regions. However, a significant portion of the latent space still maps to dark areas of low density, even for the ``8 Gaussians" dataset on which the VAE was nearly optimal. Why did the VAE not achieve optimal negative log-likelihood? Another way to look at this question is, over the course of 60000 iterations and 12 million input samples, why did the VAE fail to learn to expand the colored regions in Figure~\ref{fig:latent} until the dark regions were arbitrarily small? Based both on our discussion in Sections~\ref{sec:prob} and~\ref{sec:information} and visual inspection of Figure~\ref{fig:latent}, it does not necessarily appear that the model is incapable of expressing a model for which the colored regions are fully expanded. We can partially probe the limits of our model's expressivity by training a model with a batch size of 40000. Such a model consumes 2.4 billion training samples, takes 18 hours to train, and would be prohibitively expensive in virtually any other setting besides from a synthetic 2D example. We see that there indeed is a sizable gap between what the model is capable of expressing---which is at least as powerful as the results in Figure~\ref{fig:big} and Table~\ref{tab:nll_big}---and what it actually learns given a reasonable amount of data and resources---which is reflected in the results in Figure~\ref{fig:typical} and Table~\ref{tab:nll}. This may suggest that a large part of the problem with VAEs in this toy setting and perhaps even in practical applications may lie in optimization difficulties. \begin{table} \centering \begin{tabular}{|c|c|c|c|} \hline Dataset&$H$&Loss&NLL\\ \hline 8 Gaussians& -1.92&-1.85&-1.91\\ Checkerboard& -1&-0.84&-0.88\\ 2 Spirals& -2.34&-2.25&-2.30\\ \hline \end{tabular} \caption{Negative Log Likelihood Results on each of the 2D datasets for IWAEs. $H$ is the entropy of the ground truth distribution. Loss is the objective function of the IWAE, which is the approximate NLL using 10 samples. NLL is the approximate negative log-likelihood using 250 samples.} \label{tab:nll_iwae} \end{table} \begin{figure}[t] \centering \begin{subfigure}[b]{0.48\textwidth} \centering \includegraphics[width=\linewidth]{figures/prob8g_iwae.png} \includegraphics[width=\linewidth]{figures/probc_iwae.png} \includegraphics[width=\linewidth]{figures/prob2s_iwae.png} \caption{The ground truth probability of each pixel (left) and estimated probability from the IWAE (right).} \label{fig:density_iwae} \end{subfigure} \begin{subfigure}[b]{0.48\textwidth} \centering \includegraphics[width=\linewidth]{figures/color8g_iwae.png} \includegraphics[width=\linewidth]{figures/colorc_iwae.png} \includegraphics[width=\linewidth]{figures/color2s_iwae.png} \caption{Color correspondence between the ground truth distribution (left) and the latent space (right).} \label{fig:latent_iwae} \end{subfigure} \caption{Density Estimation and Latent Space Visualization for IWAEs.} \label{fig:iwae} \end{figure} \subsection{IWAEs and Beyond} One possible reason for the VAE's sub-optimal results may be that the decoder does not receive samples from $p_\theta(\mathbf{z})$ as input, but rather samples from $q_\phi(\mathbf{z}|\mathbf{x})$, which would presumably be centered around colored regions of the latent space. During early phases of training, $q_\phi(\mathbf{z}|\mathbf{x})$ has high variance, allowing the decoder to encounter inputs sampled from dark regions and ``explore" the latent space, which in turn allows it to learn to expand the colored regions. However, as the VAE grows more powerful, the regularization loss quickly increases and the variance of $q_\phi(\mathbf{z}|\mathbf{x})$ decreases. The decoder then explores increasingly fewer inputs from the dark regions, so the decoder will expand the colored region at an increasingly slower rate. If the variance of $q_\phi(\mathbf{z}|\mathbf{x})$ decreases too quickly, then the VAE may not be able to converge to the global optimum in a reasonable amount of time. One remedy to this limitation is the Importance-Weighted Auto-Encoder (IWAE)~\cite{burda2015importance} mentioned in Section~\ref{sec:importance}. For its loss function, the IWAE samples from $q_\phi(\mathbf{z}|\mathbf{x})$ multiple times during each iteration of training to approximate Equation~\ref{eq:expectationq}. One key advantage of minimizing an approximation of the negative log-likelihood instead of an upper bound is that $p_\theta(\mathbf{z}|\mathbf{x})$ no longer needs to closely match $q_\phi(\mathbf{z}|\mathbf{x})$, allowing for more flexibility. For a visual intuition of the utility of importance sampling, considering the following scenario: Suppose we have a multi-modal distribution where the chief job of the encoder is to select which cluster $\mathbf{x}$ belongs to. The VAE infers an accurate but not perfect posterior distribution $q_\phi(\mathbf{z}|\mathbf{x})$ such that $p_\theta(\mathbf{x}|\mathbf{z})=1$ with probability $0.9$ and $p_\theta(\mathbf{x}|\mathbf{z})=2^{-10}$ with probability $0.1$ (e.g. the tail end of a Gaussian extends to a region of latent space belonging to another cluster). This small chance of error is amplified in the negative ELBO, as $-\mathbb{E}[ \log p_\theta(\mathbf{x}|\mathbf{z})] = -0.9 \times \log 1 - 0.1 \times \log 2^{-10} = -1$. On the other hand, if we swap the order of the expectation and logarithm as done in importance sampling, the accurate predictions will drown out the inaccurate ones as $- \log \mathbb{E}[ p_\theta(\mathbf{x}|\mathbf{z}) ] = -\log [0.9+0.1\times2^{-10}] = -0.15$. Hence, compared to an IWAE, training a VAE using the negative ELBO will encourage lower variance estimates of $q_\phi(\mathbf{z}|\mathbf{x})$, which highly discourages the VAE from exploring the dark regions in Figure~\ref{fig:latent} for which $p_\theta(\mathbf{x}|\mathbf{z})$ are low. We train an IWAE using ten importance samples during each training iteration for 30000 iterations with a batch size of 200, which takes roughly the same amount of time as our Typical VAE but receives half the amount of input data. We see that, compared to a VAE, the IWAE achieves better negative log-likelihood numbers in Table~\ref{tab:nll_iwae}---rivaling or even surpassing the negative log-likelihood of the VAE trained with extremely large batch size---and thus achieves a more faithful probability density map in Figure~\ref{fig:density_iwae}. Table~\ref{tab:nll_iwae} also shows that the objective of the IWAE is a tighter bound on $-\log p_\theta(\mathbf{x})$ compared to the negative ELBO. However, the most striking difference can be seen in Figure~\ref{fig:latent_iwae}, in which the colored regions have been significantly expanded. From this toy example, we have seen the capabilities and limitations of a VAE in an empirical setting. While they are capable of capturing the general shape of even highly non-Gaussian distributions, the negative ELBO may prevent the VAE from efficiently filling the latent space with high-probability data-points. Even though we have shown in Sections~\ref{sec:flow} and~\ref{sec:transmission} that there are certain situations (i.e. when the latent space is fully disentangled or when the latent space is high-dimensional and the input data is discrete) where the VAE could theoretically perfectly model the ground truth input distribution, in practice these solutions could be virtually impossible to learn via gradient descent. As a result of these limitations, in addition to IWAEs, further research on VAEs include allowing for a more flexible posterior distribution using normalizing flows in which $q_\phi(\mathbf{z}|\mathbf{x})$ can accurately infer $p_\theta(\mathbf{z}|\mathbf{x})$ even when its variance is large~\cite{rezende2015variational,kingma2016improved}. Other improvements to the VAE including allowing for a more flexible latent prior distribution~\cite{tomczak2018vae,bauer2019resampled} or output distribution~\cite{vlae}. With these improvements, VAEs are becoming an increasingly powerful probabilistic model that can be used for a variety of applications like lossless compression, generative image modeling, and representation learning. \bibliographystyle{ieeetr}
{'timestamp': '2020-07-02T02:03:49', 'yymm': '2006', 'arxiv_id': '2006.10273', 'language': 'en', 'url': 'https://arxiv.org/abs/2006.10273'}
arxiv
\section{Introduction} Deep neural networks have achieved great success in various domains due to powerful hierarchical feature representations generated by well-designed neural architectures. For example, convolution neural networks (CNN) have evolved from AlexNet \cite{krizhevsky2012imagenet} into several architectures, including VGG \cite{simonyan2014very}, Inception \cite{szegedy2015going}, ResNet \cite{he2016deep} and DenseNet \cite{huang2017densely}. However, the design of network architectures highly depends on the artificial experience and extremely inefficient, which promotes the research on \textit{Neural Network Search (NAS)} \cite{zoph2016neural,baker2016designing,real2017large,zoph2018learning,luo2018neural,zhou2019bayesnas}. NAS discovers promising architectures via optimization on the search space, outperforming handcrafted networks \cite{zoph2018learning,luo2018neural,real2019regularized}. There are two key issues: 1) \textbf{Representation}. Typically, neural architectures are represented in a high dimensional discrete space according to the candidate operators and hyperparameters, such as graph representations in reinforcement learning (RL) \cite{zoph2018learning} and evolutionary algorithms (EA) \cite{real2017large,real2019regularized}. However, discrete representations of architecture lead to enormous search space and hard to optimize. Researchers tried to encode network architectures to a continuous space, where the mapping is the key to finding novel architectures in the continuous space. Bayesian optimization (BO) \cite{kandasamy2018neural} and gradient-based methods \cite{luo2018neural,liu2018darts} encode architectures into a continuous space and then optimize architectures in the space. 2) \textbf{Optimization}. Based on the discrete space of different layers in architectures, RL methods \cite{zoph2016neural,zoph2018learning} use policy optimization to choose a layer's type and corresponding hyperparameters. EA approaches \cite{real2017large,gaier2019weight,real2019regularized} utilize genetic algorithms to optimize both the neural architectures and their weights. Typical Bayesian optimization (BO) approaches \cite{kandasamy2018neural,zhou2019bayesnas} are based on Gaussian process and more suitable for low-dimensional continuous optimization problems, thus they first map the discrete representations to continuous representations. Gradient-based methods optimize \cite{luo2018neural,liu2018darts,cai2018proxylessnas,xie2018snas} the network architecture on the continuous space w.r.t performance of architectures. \begin{figure}[t] \centering \includegraphics[width=\textwidth]{architecture.png} \caption{The learning framework of \texttt{NGAE}. The neural architecture is mapped into a continuous representation by the encoder network. Using stochastic gradient ascent, the continuous representation is optimized via maximizing the predictor, combining performance and complexity predictor. The optimized continuous representation is decoded out to a network architecture using the decoder.} \label{fig.architecture} \end{figure} Gradient-based approaches have drawn much attention because of their continuous optimization and high efficiency. However, existing gradient methods have two weaknesses: 1) Graph representations use continuous relaxation \cite{liu2018darts} or sequential embeddings \cite{luo2018neural} focus on the structure but fail to extract computations in the neural architectures. 2) Existing gradient methods pursue architectures with better performances but ignore the computational efficiency. In this paper, we propose a gradient-based Neural architecture optimization with Graph variational AutoEncoder (\texttt{NGAE}), which aims to find architectures with both preferable performance and high computational efficiency. As shown in Figure \ref{fig.architecture}, three are three parts in the framework \texttt{NGAE}: 1) The \textit{encoder} is to map the architectures to a latent space, where we use graph neural networks (GNN) to obtain continuous representations of architectures. 2) The \textit{predictor} consists of two regression models fitting the performance and the computational complexity in the latent space. 3) The \textit{decoder} is to recover neural architectures from the continuous representations. \section{Related Work} \subsection{Variational Graph Autoencoder} Variational graph autoencoder is a kind of graph generative model using \textbf{variational autoencoder (VAE)} on graph embeddings. VAE aims to learn both the decoder $p_\theta(\boldsymbol x|\boldsymbol s)$ and the encoder $q_\phi(\boldsymbol s|\boldsymbol x)$ via maximizing the variational evidence lower bound (ELBO) \cite{kingma2013auto}, which is stated as \begin{align} \label{eq.lower_bound} \mathcal{L}({\boldsymbol \phi}, {\boldsymbol \theta}; \boldsymbol x) = \mathbb{E}_{z \sim q_{\boldsymbol \phi}(\boldsymbol s|\boldsymbol x)} \left[\log p_{\boldsymbol \theta}(\boldsymbol x | \boldsymbol s)\right] - D_\text{KL} \left[q_{\boldsymbol \phi}(\boldsymbol s | \boldsymbol x) ~ || ~ p_{\boldsymbol \theta}(\boldsymbol s)\right]. \end{align} The first term estimates the reconstruction accuracy which reflects the similarity between the primal graphs and the decoded graphs. The KL divergence term $D_\text{KL}$ regularizes the latent space. NAO employed two LSTM models as the encoder and the decoder, which generates sequential representations of neural architectures \cite{luo2018neural}. Graphrnn used a second-level RNN to capture edge dependencies \cite{you2018graphrnn}. To better extract characteristics of graphs, recent work began to incorporate VAE and \textbf{graph neural networks (GNNs)}. Using graph convolutional networks (GCN), \cite{li2018learning} represented neural architectures with the synchronous message passing scheme. In contrast, D-VAE \cite{zhang2019d} employed asynchronous message passing schema as known from directed acyclic graphs (DAGs), to extract representations of nodes and edges in neural architectures. Using GNNs, VS-GAE \cite{friede2019variational} was specialized in the representations of architectures with varying lengths. \subsection{Gradient-based NAS methods} While RL and EA methods search architectures in a discrete space, gradient-based methods use continuous representations to enable differentiable optimization. NAO \cite{luo2018neural} encodes the neural architectures into continuous representations using VAE and discover new powerful architectures via stochastic gradient ascent by maximizing the predictor. DARTS \cite{liu2018darts} uses a continuous relaxation to enable gradient-based optimization, where the graph is represented by the convex combination of the possibilities of all edges. Both SNAS \cite{xie2018snas} and ProxylessNAS \cite{cai2018proxylessnas} optimize a parametrized distribution over the possible operations. NASP \cite{yao2020efficient} searches architectures in a differentiable space with a discrete constraint on architectures and a regularizer on model complexity. \section{Learning Framework} Let $(\boldsymbol x, y, z) \in \mathcal{X} \times \mathcal{Y} \times \mathcal{Z}$ be a triplet of the architecture, its performance (e.g. classification accuracy of the network) and its computational complexity (e.g. the amount of computations), where $\mathcal{X}$ is the search space and $\mathcal{Y}, \mathcal{Z} \in \mathbb{R}^+$ are performance measure and computational measure, respectively. The learning framework consists of four components: the encoder $E$, the performance predictor $f_{perf}$, the complexity predictor $f_{comp}$ and the decoder $D$. The encoder $E: \mathcal{X} \to \mathcal{S}$ and the decoder $D: \mathcal{S} \to \mathcal{X}$ are used to convert representations between networks search space $\mathcal{X}$ and a continuous space $\mathcal{S}$. Based on the latent space $\mathcal{S}$, the performance predictor $f_{perf}: \mathcal{S} \to \mathcal{Y}$ is used to fit the performance of network architectures, while the complexity predictor $f_{comp}: \mathcal{S} \to \mathcal{Z}$ is used to fit the computational complexity of network architectures, We first train the encoder, two predictors and the decoder in an end-to-end manner, and then use them to infer new architectures. \subsection{Encoder} Neural networks pass computations step-wise without circles, therefore networks are directed acyclic graphs (DAGs), where layers correspond to nodes in DAG and mappings between layers are edges in DAG. To fully extract underlying characteristics of neural architectures, we employ a specialized GNN built for DAG \cite{zhang2019d}, which produces more powerful representations than traditional GNN. DAG encoders focus on \textit{computations} rather than the \textit{structure}, dramatically reducing the search space. We let the encoder be $E: \mathcal{X} \to \mathcal{S}$, where the encoder maps neural networks to continuous representations. The continuous representation of a network architecture $\boldsymbol x \in \mathcal{X}$ is built up in following steps: $\boldsymbol x \to h_{out} \to \boldsymbol s$, where the architecture $\boldsymbol x$ is first encoded as a discrete vector $h_{out}$ by GNN and then mapped to a continuous representation $\boldsymbol s$ by a variational autoencoder (VAE). \subsubsection{Discrete Representations: $\boldsymbol x \to h_{out}$} We consider the asynchronous message passing schema in DAG where the computation of a node is carried out until it receives all incoming messages. Therefore, the representations of nodes need to embed both the node type and incoming edges. The discrete embedding of node $v$ is given by: \begin{align} \label{eq.graph_embedding} h_v = \mathcal{U} \big(T_v, ~ \mathcal{A}(\{h_u: u \to v\}) \big), \end{align} where $T_v$ is the type of node $v$, represented as a one-hot vector. $u \to v$ denotes the directed edge from node $u$ to node $v$, thus $\{h_u: u \to v\}$ is the set of $v$'s predecessors, which are determined by incoming edges. The aggregate function $\mathcal{A}$ is used to aggregate all predecessors of $v$ and $\mathcal{U}$ fuses the representations of the node type and incoming edges. There are no predecessors for the input node, so the aggregation for the input node is an all-zeros vector. Following the topological ordering in the DAG, we iteratively compute the discrete vector for each node and finally the computations end in the output node $h_{out}$, where $h_{out}$ is used to represent the neural network $\boldsymbol x$. Although the graph embedding $h_{out}$ extracts structural information of neural networks, it is hard to optimized due to the discrete representations. \begin{remark} Due to the asynchronous messages passing schema of DAG, the incoming edges $\{h_u: u \to v\}$ are invariant to nodes order permutations, so the aggregate function $\mathcal{A}$ should be invariant to the order of inputs. Meanwhile, to ensure the correspondence of $\boldsymbol x$ and $h_{out}$, the aggregate function $\mathcal{A}$ and the update function $\mathcal{U}$ should be injective. In this paper, we let $\mathcal{A}$ be a gated sum and $\mathcal{U}$ be a gated recurrent unit (GRU). \end{remark} \subsubsection{Continuous Representations: $h_{out} \to \boldsymbol s$} We then introduce variational autoencoder (VAE) to obtain continuous representations of neural networks. For the sake of simplification, we let the variational approximate posterior $q_{\boldsymbol \phi}(\boldsymbol s | h_{out})$ be a multivariate Gaussian with a diagonal structure: \begin{align*} q_{\boldsymbol \phi}(\boldsymbol s | h_{out}) = \mathcal{N}(\boldsymbol s; {\boldsymbol \mu}, {\boldsymbol \sigma}^2 \mathbf{I}) \end{align*} where we use two multilayer perceptrons (MLPs) to generate the mean ${\boldsymbol \mu}$ and the logarithm of variance $\log ({\boldsymbol \sigma^2})$, respectively. To generate samples in the latent space $\mathcal{S}$ efficiently and accelerate the computation of the KL term in the variational lower bound \eqref{eq.lower_bound}, we let the prior be $p_\theta(\boldsymbol s) = \mathcal{N}({\boldsymbol 0}, \mathbf{I})$. The maximization of the variational lower bound means to minimize the Kullback-Leibler divergence between the posterior $q_\phi(\boldsymbol s | \boldsymbol x)$ and the prior $p_\theta(\boldsymbol s)$, then it holds \cite{kingma2013auto}: \begin{equation} \label{eq.kl_divergence} \begin{aligned} - D_\text{KL} \big[q_\phi(\boldsymbol s|h_{out}) ~||~ p_\theta(\boldsymbol s)\big] &= \frac{1}{2} \sum_{j=1}^J \big[ 1 + \log ({\boldsymbol \sigma}_j^2) - {\boldsymbol \mu}_j^2 - {\boldsymbol \sigma}_j^2\big] \end{aligned} \end{equation} where $J$ is the dimensionality of the latent space $\mathcal{S}$. Therefore, we can directly sample points in the latent space from the standard normalization distribution and connect those two MLPs $f_{mean}$ and $f_{logvar}$ to the variational lower bound \eqref{eq.lower_bound}. \subsection{Predictor} The architecture with its performance and complexity $(\boldsymbol x, y, z) \in \mathcal{X} \times \mathcal{Y} \times \mathcal{Z}$ is converted to $(\boldsymbol s, y, z) \in \mathcal{S} \times \mathcal{Y} \times \mathcal{Z}$ after encoding. The performance predictor $f_{perf}: \mathcal{S} \to \mathcal{Y}$ is a regression model to fit the performance of neural networks, where the performance rating is the accuracy for classification tasks and $\mathcal{Y} = [0, 1].$ The complexity predictor $f_{comp}: \mathcal{S} \to \mathcal{Z}$ is another regression model to fit the computational complexity of neural networks, where we regularize the computational complexity to $[0, 1].$ Those two predictors can be implemented by any nonlinear regression models, such as kernel ridge regression (KRR), Gaussian process regression and multilayer perceptron (MLP). To facilitate the training of the predictor together with the encoder/decoder, we use two two-hidden-layers neural network (MLP) as the performance predictor $f_{perf}$ and the complexity predictor $f_{comp}$, respectively. For classification, we use Sigmoid as the activation function of the last layers, to ensure the predicted accuracy and complexity valid. In the training process, we train two predictors w.r.t the squared loss $[f_{perf}(\boldsymbol s) - y]^2, [f_{comp}(\boldsymbol s) - z]^2,$ where $\boldsymbol s$ is the latent representation of an architecture, $y$ is the corresponding performance and $z$ is the corresponding computational complexity. The optimization objective of predictors is to minimize the empirical loss on the training data $(X, Y, Z)$, written as \begin{align} \label{eq.squared_loss} \mathcal{L}_{pred} = \sum_{(\boldsymbol x, y, z) \in (X, Y, Z)} \big[ f_{perf}(\boldsymbol s) - y \big]^2 + \big[ f_{comp}(\boldsymbol s) - z \big]^2. \end{align} In the inference process, we directly optimize the neural architectures in the latent space based on the performance predictor $f_{perf}$ and the complexity predictor $f_{comp}$, where the objective is to maximize the predicted performance and minimize the predicted complexity. Then, we use the decoder $D$ to decode the network architecture from the latent space $\mathcal{S}$ to the search space $\mathcal{X}$. \subsection{Decoder} We utilize the generative model of the graph autoencoder $D: \mathcal{S} \to \mathcal{X}$ to decode latent representations to DAGs (the network architectures), where the decoder also exerts the asynchronous message passing schema to construct valid DAGs. Using another MLP, we decode the continuous representation $\boldsymbol s$ to $h_0$ as the initial discrete representation of the graph $\boldsymbol x$. We generate nodes in the graph until the output node $h_{out}$ is generated or reach the max allowed layers, where the representation of each node $h_v$ and the neural network architecture are generated as the following steps: \textbf{1) Add a node.} Based on the representation of last generated node $h_v'$, we use an MLP followed by a softmax to determine the probability of the types of $h_v$, where we sample the node type w.r.t the distribution and represent it as a one-hot vector $T_v$. We update the discrete representation of a node $h_v$ according to its type based on the operation $\mathcal{U}$ in \eqref{eq.graph_embedding}. Besides the discrete representation $h_v$, we add a node with the sampled type to the neural network architecture $\boldsymbol x$. \textbf{2) Add incoming edges.} Similarly, to compute the probability of directed edges $\{u \to v\}$ ($u$ is a node before the node $v$), we employ an another MLP base on the representation $h_u$ and $h_v$. and sample the edges. Using on the incoming edges, we then update the representation $h_v$ by updating the aggregation of the incoming edges $\mathcal{A}(\{h_u:u \to v\})$ in \eqref{eq.graph_embedding}. Meanwhile, we build connections to the current node in the architecture $\boldsymbol x$ according to the sampled edges. At the very beginning, we generate the input node by directly setting $T_v$ as the input and use $h_0$ as the initial state of the input node. Meanwhile, there are no incoming edges thus we set the aggregation as an all-zeros vector. The input node is added into the network architecture $\boldsymbol x$ as well. In fact, the decoder is the generate model $p_\theta(h_{out} | \boldsymbol s)$ in the evidence lower bound \eqref{eq.lower_bound}. The first term in \eqref{eq.lower_bound} $\mathbb{E}_{z \sim q_{\boldsymbol \phi}(\boldsymbol s|\boldsymbol x)} \left[\log p_{\boldsymbol \theta}(\boldsymbol x | \boldsymbol s)\right]$ estimates the reconstruction accuracy, where the maximization of this term urges the high similarity between the primal DAG and the decoded graph. We evaluate the reconstruction accuracy by summing up the similarity of nodes and edges between the primal DAG and the generated graph, where the reconstruction accuracy is denoted as: \begin{align} \label{eq.reconstruction_acc} \mathcal{L}_{rec} = \mathcal{L}_n + \mathcal{L}_e. \end{align} \section{Training and Inference} \begin{figure} \centering \includegraphics[width=\textwidth]{training.png} \caption{The training process of \texttt{NGAE}. \texttt{NGAE} jointly optimize the encoder $E: \mathcal{X} \to \mathcal{S}$, the decoder $D: \mathcal{S} \to \mathcal{X}$, the performance predictor $f_{perf}: \mathcal{S} \to \mathcal{Y}$ and the complexity predictor $f_{comp}: \mathcal{S} \to \mathcal{Z}$ via maximizing the objective \eqref{eq.training_objective}.} \label{fig.training} \end{figure} To facilitate the training of the search models, we optimize the encoder, two predictors and the decoder in an end-to-end manner. The objective of VAE is to maximize evidence lower bound in \eqref{eq.lower_bound}, while the objective of two predictors is to minimize the squared loss. Therefore, to jointly learn those components, we combine the minimization of the KL divergence \eqref{eq.kl_divergence}, the squared loss \eqref{eq.squared_loss} and the reconstruction loss \eqref{eq.reconstruction_acc}, aiming to minimize the following objective: \begin{equation} \label{eq.training_objective} \begin{aligned} \operatornamewithlimits{arg\,min}\limits_{\phi, \theta, f_{perf}, f_{comp}} \quad \mathcal{L} = \sum_{(\boldsymbol x, y, z) \in (X, Y, Z)} &~\mathcal{L}_n + \mathcal{L}_e + D_\text{KL} \big[q_\phi(\boldsymbol s|h_{out}) ~||~ p_\theta(\boldsymbol s)\big] \\ + ~&\big[ f_{perf}(\boldsymbol s) - y \big]^2 + \big[ f_{comp}(\boldsymbol s) - z \big]^2, \end{aligned} \end{equation} where $\phi, \theta, f_{perf}, f_{comp}$ are the parameters for the encoder, the decoder, the performance predictor and the complexity predictor, respectively. $\mathcal{L}_n$ and $\mathcal{L}_e$ measure the reconstruction loss in terms of nodes and edges. Generated by the encoder, $h_{out}$ and $\boldsymbol s$ are the discrete representation and the latent continuous representation for the architecture $\boldsymbol x$, respectively. Figure \ref{fig.training} illustrates the training process of \texttt{NGAE}, which outputs the latent space $\mathcal{S}$ and the objective regression model. After the training process, we obtain a latent space $\mathcal{S}$ and two regression models $f_{perf}$ and $f_{comp}$ on this continuous space. To find the architecture with optimal performance and high computational efficiency, we maximize the performance predictor and minimize the complexity predictor: \begin{align} \label{eq.inference_objective} \operatornamewithlimits{arg\,max}\limits_{\boldsymbol s \in \mathcal{S}} \quad f(\boldsymbol s) = \quad f_{perf}(\boldsymbol s) - f_{comp}(\boldsymbol s). \end{align} To solve the optimization problem in \eqref{eq.inference_objective}, we sample a point $\boldsymbol s \in \mathcal{S}$ according to the prior $p_\theta(\boldsymbol s) = \mathcal{N}({\boldsymbol 0}, \mathbf{I})$. We use the first-order stochastic gradient method to optimize \eqref{eq.inference_objective}, and the continuous representation $\boldsymbol s$ is updated along the direction of the gradient: \begin{align*} \boldsymbol s^{l+1}= \boldsymbol s^{l} + \eta \frac{\partial f}{\partial \boldsymbol s^{l}}, \qquad \text{where} ~~ l \in \{1, \cdots, L\}, \end{align*} where $L$ is the maximal iterations. After the inference, we use the decoder $D: \mathcal{S} \to \mathcal{X}$ to construct a valid neural architecture from the optimized representation $\boldsymbol s'$ according to the generative mode $p_\theta(\boldsymbol x|\boldsymbol s)$. So, the discovered architecture is $\boldsymbol x' = D(\boldsymbol s').$ \begin{algorithm}[t] \caption{Neural Architecture Optimization with Graph Embedding} \label{alg.NGAE} \begin{algorithmic}[1] \Require The training data $(X, Y)$ with the architectures and their performance. The initialized encoder $E$, performance predictor $f_{perf}$, complexity predictor $f_{comp}$ and decoder $D$. Step size $\lambda$, batch size $b$ and number of iterations $T$ for training. Step size $\eta$ and number of iterations $L$ for testing. \Ensure The neural architecture $\boldsymbol x'$ with the optimal performance. \Procedure{Training}{} \Comment{Optimize $D, f_{perf}, f_{comp}, E$ by maximizing the objective \eqref{eq.training_objective}} \For{$t = 1, \cdots, T$} \State Split the training data $(X, Y)$ with batch size $b$. \For{each batch $(X_i, Y_i)$} \Comment{Use sgd on each batch $(X_i, Y_i)$} \State $\phi \gets \phi - \lambda \frac{\partial \mathcal{L}}{\partial \phi}$ \Comment{$\phi$ is the parameter set of the encoder $D$} \State $f_{perf} \gets f_{perf} - \lambda \frac{\partial \mathcal{L}}{\partial f_{perf}}$ \State $f_{comp} \gets f_{comp} - \lambda \frac{\partial \mathcal{L}}{\partial f_{comp}}$ \State $\theta \gets \theta - \lambda \frac{\partial \mathcal{L}}{\partial \theta}$ \Comment{$\theta$ is the parameter set of the encoder $D$} \EndFor \EndFor \State \textbf{return} the optimized $D, f, E$ \EndProcedure \Procedure{Inference}{} \Comment{Optimize $\boldsymbol x'$ by maximizing the objective \eqref{eq.inference_objective}} \State Sample a point $\boldsymbol s' \in \mathcal{S}$ w.r.t $p_\theta(\boldsymbol s)$. \For{$l = 1, \cdots, L$} \State $\boldsymbol s'= \boldsymbol s' + \eta \frac{\partial f}{\partial \boldsymbol s'}$ \EndFor \State Decode $\boldsymbol s'$ to a architecture $\boldsymbol x' = D(\boldsymbol s')$ \State \textbf{return} the discovered architecture $\boldsymbol x'$ \EndProcedure \end{algorithmic} \end{algorithm} We complete the detailed algorithm as shown in Algorithm \ref{alg.NGAE}. In the training, the algorithm optimizes the encoder $E$, the performance predictor $f_{perf}$, the complexity predictor $f_{comp}$ and the decoder $D$ by maximizing the objective \eqref{eq.training_objective}, where we use the stochastic gradient descent (sgd) to solve the optimization. In the inference, the algorithm starts with a sampled point $\boldsymbol s'$ w.r.t the prior $p_\theta(\boldsymbol s)$ and then optimize $\boldsymbol s'$ by maximizing the performance and computational efficiency $f$ \eqref{eq.inference_objective}. \section{Experiments} Our experiments aim to estimate the effectiveness of the proposed framework in the neural architecture search domain, covering three complementary tasks: {1) \bf Basic properties of the variational graph VAE.} The graph VAE is the core of our approach, which determines the continuous latent space and the ability of representations for architectures. So, we first estimate the convergence of the reconstruction loss and KL divergence. Finally, the smoothness of the latent space is illustrated by the visualization in the 2D subspace. {2) \bf Predictive ability of the predictor $f$.} The predictor $f$ includes two nonlinear regression models that fit the performance and the complexity of architectures. We optimize architectures in the latent space by maximizing the predictor $f$, thus the fitness of $f$ is significant to explore better architectures. We compare the predicted performance and ground truth for randomly sampled graphs, and estimate the rooted-mean-squared error (RMSE) of $f$ in training and testing. {3) \bf The comparison of the generalization ability and efficiency.} Towards the generalization ability and efficiency, we compared the end-to-end framework \texttt{NGAE} with/without the complexity predictor and D-VAE. DAG variational autoencoder (D-VAE) \cite{zhang2019d} first learns the VAE to obtain the latent space and then use Bayesian optimization to generate new architectures. Different from the traditional NAS methods, our approach focus on powerful representations of neural architectures and the predictive model, thus the proposed methods don't need to train networks in the training. Here, our training dataset $(X, Y, Z)$ consists of 19, 020 neural architectures from the ENAS software \cite{pham2018efficient}. The architectures include 6 nodes except the input node and the output node, where those nodes are sampled from 6 kinds of different operations: $3 \times 3$ convolution, $3 \times 3$ separable convolution, $5 \times 5$ convolution, $5 \times 5$ separable convolution, average pooling and max pooling. We split the dataset into $90\%$ training data and $10\%$ testing data, where we use the training data to learn the VAE and the predictor and testing data for evaluation. \subsection{Basic properties of the variational graph VAE} \begin{figure} \subfigure{\centering \includegraphics[width=0.5\textwidth]{exp1_convergence.pdf}} \subfigure{\centering \includegraphics[width=0.5\textwidth]{exp1_smooth300.pdf}} \caption{The basic properties of the proposed approach. (left) The reconstruction loss and KL divergence during the training process. (right) Visualization of 2D subspace of the latent space.} \label{fig.exp1_properties} \end{figure} During the training process, we record the reconstruction loss $\mathcal{L}_n + \mathcal{L}_e$ and the KL divergence $D_\text{KL} \big[q_\phi(\boldsymbol s|h_{out}) ~||~ p_\theta(\boldsymbol s)\big]$. The left figure in Figure \ref{fig.exp1_properties} reports the convergence of the reconstruction loss and the KL divergence that can be summarized as follows: (1) The reconstruction loss plays a dominant role in the training loss \eqref{eq.training_objective}, which reflects the match between the encoder $E$ and the decoder $D$. (2) The reconstruction loss is the main optimization term and decreases dramatically during the training. It convergence to a small constant near zero after 200 epochs. (3) At the beginning, the encoder is relatively simple where the posterior approximation $q_\phi(\boldsymbol s|h_{out})$ is close to the prior $p_\theta(\boldsymbol s)$, thus the KL divergence is small. As the encoder becomes more complex, the KL divergence grows while the reconstruction loss decreases. (4) After the reconstruction loss no longer reduces (100 epochs), the KL divergence begins to reduce to near zero. \begin{table}[t] \centering \setlength\extrarowheight{1.3pt} \begin{tabular}{@{\extracolsep{0.2cm}}l|l|l|l} \hline Measures & 100 epoch & 200 epoch & 300 epoch \\ \hline Accuracy & 82.83 & 99.97 & 99.99 \\ \hline Validity & 99.98 & 100 & 100 \\ \hline Uniqueness & 51.55 & 42.05 & 38.56 \\ \hline Novelty & 100 & 100 & 100 \\ \hline \end{tabular} \vspace{10pt} \caption{Reconstruction accuracy, prior validity, uniqueness and novelty ($\%$) for different periods.} \label{tab.performance_measures} \end{table} Using the optimized models under 100/200/300 epochs, we evaluate the performance of the proposed approach on testing dataset via four measures: (1) The \textit{reconstruction accuracy} estimates the rate of perfectly recovered graphs via graph VAE. (2) The \textit{validity} measures the proportion of valid DAGs generated from the prior distribution $p_\theta(\boldsymbol s)$. (3) The \textit{uniqueness} show the frequency of unique graphs from valid DAGs. (4) The \textit{novelty} measures the proportion of novel graphs from valid DAGs which are not in the training set. Table \ref{tab.performance_measures} reports the performance measures after 100/200/300 epochs. From Table \ref{tab.performance_measures}, we find (1) reconstruction accuracy is growing from $82.83\%$ and finally achieves $99.99\%$, (2) uniqueness declines as the training epochs increases because many optimized architectures tend to be same, (3) prior validity and novelty remain unchanged around $100\%$. To estimate the smoothness of our method, we use the first two principal components of a continuous representation $\boldsymbol s$ sampled by $p_\theta(\boldsymbol s)$. We then obtain more continuous representations by moving $\boldsymbol s$ in the first two principal components and measure their performance predicted by the predictor $f$. Results are reported in the right of Figure \ref{fig.exp1_properties} where two dimensionalities correspond to two principal components and the color bar indicates the predicted accuracies. In the right of Figure \ref{fig.exp1_properties}, the predicted accuracy (the color) changes smoothly as the move of two principal components, showing that the generated latent space is continuous thus it can be optimized by gradient methods easily. \subsection{Predictive ability of the predictor $f$} \begin{figure} \subfigure{\centering \includegraphics[width=0.33\textwidth]{exp2_scatter.pdf}} \subfigure{\centering \includegraphics[width=0.33\textwidth]{exp2_rmse.pdf}} \subfigure{\centering \includegraphics[width=0.33\textwidth]{exp2_sgd.pdf}} \caption{Predictive performance of the predictor $f$. (left) True accuracies and predicted accuracies on sampled test architectures. (medium) The convergence of RMSE on training data and test data. (right) The predicted accuracy during inference using SGD.} \label{fig.exp2_predictor} \end{figure} In the left of Figure \ref{fig.exp2_predictor}, we record true accuracies and predicted accuracies of randomly sampled 100 architectures on the test set. The fit line is close to the line $y_{true} = y_{pred},$ that means our predictor $f$ achieve excellent predictive ability on accuracy. The middle of Figure \ref{fig.exp2_predictor} illustrates the convergence of RMSE on training data and test data, where we only evaluate test RMSE on 100/200/300 epochs. RMSE convergent to a small number, improving the performance of $f$. In the inference, we use the stochastic gradient ascent method to optimize the continuous representations by maximizing the output of predictor $f$. The update of predicted accuracy in the inference is recorded in the right of Figure \ref{fig.exp2_predictor}. The convergence of predicted accuracy reveals the superiority of multiple steps update of gradient over one-step update in NAO \cite{luo2018neural}. \subsection{The comparison of the generalization ability and efficiency} \begin{figure}[t] \centering \includegraphics[width=\textwidth]{discovered_architectures.png} \caption{Top 3 architectures found by \texttt{NGAE}, \texttt{NGAE} without complexity predictor and D-VAE.} \label{fig.found_architectures} \end{figure} Figure \ref{fig.found_architectures} reports the top 3 neural architectures found by \text{NGAE}, \text{NGAE} without complexity predictor and D-VAE \cite{zhang2019d} on CIFAR-10. \text{NGAE} without complexity predictor is a simpler version of \texttt{NGAE}, which only use the encoder, the performance predictor, the decoder in the framework, waiving the complexity predictor. D-VAE use similar encoder and decoder to \texttt{NGAE}, but D-VAE only learns the encoder and decoder in representations training. Then D-VAE trains a Bayesian optimization model and use it to search architectures. \texttt{NGAE} and D-VAE apply similar graph VAE to construct a connections space, but \texttt{NGAE} learns the VAE and the optimizer (two predictors) in an end-to-end manner, while D-VAE split the training of VAE and the optimizer (Bayesian model). From Figure \ref{fig.found_architectures}, we find that (1) Both \text{NGAE} with/without complexity predictor outperform D-VAE, proving the effectiveness of jointly training VAE and predictors. (2) \text{NGAE} without complexity predictor found architectures with best results but high computational complexity. (2) \text{NGAE} reduce computational complexity significantly by sacrificing little accuracy. \section{Conclusion and Future Work} In this paper, we have proposed \texttt{NGAE}, using GNN-based VAE to construct a continuous space and gradient-based optimization to search new architectures on it. There are two predictors (performance and complexity) built upon the latent space using the training set. The combination of those predictors is used to find architectures with both better performance and lower computational complexity. Due to our limited computational resources, we can't perform complex NAS methods, such as NAO \cite{luo2018neural}, \cite{liu2018darts} and NASP \cite{yao2020efficient}. Meanwhile, we can also train the proposed \texttt{NGAE} using recent NAS-Bench-101 \cite{ying2019bench} and NAS-Bench-201 \cite{yao2020efficient}. \texttt{NGAE} can not only search convolutional network architectures but also can search other types of architectures (e.g. RNN, GNN), only need to use their corresponding performance measures instead of accuracies on CIFAR-10. We leave more compared methods, larger training datasets and other types of architecture for future work. \bibliographystyle{unsrt}
{'timestamp': '2020-06-19T02:10:12', 'yymm': '2006', 'arxiv_id': '2006.10310', 'language': 'en', 'url': 'https://arxiv.org/abs/2006.10310'}
arxiv
\section{Introduction} Hand tracking is a vital component to provide a natural way for interaction and communication in AR/VR, and has been an active research topic in the industry \cite{oculus} \cite{snap}. Vision-based hand pose estimation has been studied for many years. A large portion of previous work requires specialized hardware, \eg depth sensors \cite{oikonomidis2011efficient}\cite{tagliasacchi2015robust}\cite{wan2019self}\cite{ge2016robust}\cite{ge2018robust}. Other solutions are not lightweight enough to run real-time on commodity mobile devices\cite{ge20193d} and thus are limited to platforms equipped with powerful processors. In this paper, we propose a novel solution that does not require any additional hardware and performs in real-time on mobile devices. Our main contributions are: \vspace{-\topsep} \begin{itemize} \setlength{\parskip}{0pt} \setlength{\itemsep}{0pt plus 1pt} \item An efficient two-stage hand tracking pipeline that can track multiple hands in real-time on mobile devices. \item A hand pose estimation model that is capable of predicting 2.5D hand pose with only RGB input. \item And open source hand tracking pipeline as a ready-to-go solution on a variety of platforms, including Android, iOS, Web (Tensorflow.js\cite{tfjs}) and desktop PCs. \end{itemize} \begin{figure}[t!] \begin{center} \includegraphics[width=1\linewidth]{hand_tracking.png} \end{center} \caption{Rendered hand tracking result. (Left): Hand landmarks with relative depth presented in different shades. The lighter and larger the circle, the closer the landmark is towards the camera. (Right): Real-time multi-hand tracking on Pixel 3.} \label{fig:hand_tracking} \end{figure} \section{Architecture} \label{architecture} Our hand tracking solution utilizes an ML pipeline consisting of two models working together: \vspace{-\topsep} \begin{itemize} \setlength{\parskip}{0pt} \setlength{\itemsep}{0pt plus 1pt} \item A palm detector that operates on a full input image and locates palms via an oriented hand bounding box. \item A hand landmark model that operates on the cropped hand bounding box provided by the palm detector and returns high-fidelity 2.5D landmarks. \end{itemize} Providing the accurately cropped palm image to the hand landmark model drastically reduces the need for data augmentation (\eg rotations, translation and scale) and allows the network to dedicate most of its capacity towards landmark localization accuracy. In a real-time tracking scenario, we derive a bounding box from the landmark prediction of the previous frame as input for the current frame, thus avoiding applying the detector on every frame. Instead, the detector is only applied on the first frame or when the hand prediction indicates that the hand is lost. \subsection{BlazePalm Detector} To detect initial hand locations, we employ a single-shot detector model optimized for mobile real-time application similar to BlazeFace\cite{blazeface}, which is also available in MediaPipe\cite{mediapipe}. Detecting hands is a decidedly complex task: our model has to work across a variety of hand sizes with a large scale span (\( \sim \)20x) and be able to detect occluded and self-occluded hands. Whereas faces have high contrast patterns, \eg, around the eye and mouth region, the lack of such features in hands makes it comparatively difficult to detect them reliably from their visual features alone. Our solution addresses the above challenges using different strategies. First, we train a palm detector instead of a hand detector, since estimating bounding boxes of rigid objects like palms and fists is significantly simpler than detecting hands with articulated fingers. In addition, as palms are smaller objects, the non-maximum suppression algorithm works well even for the two-hand self-occlusion cases, like handshakes. Moreover, palms can be modelled using only square bounding boxes \cite{ssd}, ignoring other aspect ratios, and therefore reducing the number of anchors by a factor of 3\( \sim \)5. Second, we use an encoder-decoder feature extractor similar to FPN\cite{fpn} for a larger scene-context awareness even for small objects. Lastly, we minimize the focal loss\cite{focalloss} during training to support a large amount of anchors resulting from the high scale variance. High-level palm detector architecture is shown in Figure \ref{fig:detectorpic}. We present an ablation study of our design elements in Table \ref{tab:detector}. \begin{figure}[t!] \begin{center} \includegraphics[width=0.85\linewidth]{palm_detector_model.png} \end{center} \caption{Palm detector model architecture.} \label{fig:detectorpic} \end{figure} \subsection{Hand Landmark Model} \label{hand_landmark_model} After running palm detection over the whole image, our subsequent hand landmark model performs precise landmark localization of 21 2.5D coordinates inside the detected hand regions via regression. The model learns a consistent internal hand pose representation and is robust even to partially visible hands and self-occlusions. The model has three outputs (see Figure \ref{fig:landmarkpic}): \vspace{-\topsep} \begin{enumerate} \setlength{\parskip}{0pt} \setlength{\itemsep}{0pt plus 1pt} \item 21 hand landmarks consisting of x, y, and relative depth. \item A hand flag indicating the probability of hand presence in the input image. \item A binary classification of handedness, \eg left or right hand. \end{enumerate} \vspace{-\topsep} We use the same topology as \cite{cmuhand} for the 21 landmarks. The 2D coordinates are learned from both real-world images as well as synthetic datasets as discussed below, with the relative depth \wrt the wrist point being learned only from synthetic images. To recover from tracking failure, we developed another output of the model similar to \cite{facemesh} for producing the probability of the event that a reasonably aligned hand is indeed present in the provided crop. If the score is lower than a threshold then the detector is triggered to reset tracking. Handedness is another important attribute for effective interaction using hands in AR/VR. This is especially useful for some applications where each hand is associated with a unique functionality. Thus we developed a binary classification head to predict whether the input hand is the left or right hand. Our setup targets real-time mobile GPU inference, but we have also designed lighter and heavier versions of the model to address CPU inference on the mobile devices lacking proper GPU support and higher accuracy requirements of accuracy to run on desktop, respectively. \begin{figure}[t!] \begin{center} \includegraphics[width=1.0\linewidth]{hand_landmark_model.png} \end{center} \caption{Architecture of our hand landmark model. The model has three outputs sharing a feature extractor. Each head is trained by correspondent datasets marked in the same color. See Section \ref{hand_landmark_model} for more detail.} \label{fig:landmarkpic} \end{figure} \section{Dataset and Annotation} \label{dataset} To obtain ground truth data, we created the following datasets addressing different aspects of the problem: \vspace{-\topsep} \begin{itemize} \setlength{\parskip}{0pt} \setlength{\itemsep}{0pt plus 1pt} \item In-the-wild dataset: This dataset contains 6K images of large variety, \eg geographical diversity, various lighting conditions and hand appearance. The limitation of this dataset is that it doesn't contain complex articulation of hands. \item In-house collected gesture dataset: This dataset contains 10K images that cover various angles of all physically possible hand gestures. The limitation of this dataset is that it's collected from only 30 people with limited variation in background. The in-the-wild and in-house dataset are great complements to each other to improve robustness. \item Synthetic dataset: To even better cover the possible hand poses and provide additional supervision for depth, we render a high-quality synthetic hand model over various backgrounds and map it to the corresponding 3D coordinates. We use a commercial 3D hand model that is rigged with 24 bones and includes 36 blendshapes, which control fingers and palm thickness. The model also provides 5 textures with different skin tones. We created video sequences of transformation between hand poses and sampled 100K images from the videos. We rendered each pose with a random high-dynamic-range lighting environment and three different cameras. See Figure \ref{fig:dataset} for examples. \end{itemize} For the palm detector, we only use in-the-wild dataset, which is sufficient for localizing hands and offers the highest variety in appearance. However, all datasets are used for training the hand landmark model. We annotate the real-world images with 21 landmarks and use projected ground-truth 3D joints for synthetic images. For hand presence, we select a subset of real-world images as positive examples and sample on the region excluding annotated hand regions as negative examples. For handedness, we annotate a subset of real-world images with handedness to provide such data. \begin{figure}[t!] \begin{center} \includegraphics[width=1.0\linewidth]{dataset.png} \end{center} \caption{Examples of our datasets. (Top): Annotated real-world images. (Bottom): Rendered synthetic hand images with ground truth annotation. See Section \ref{dataset} for details.} \label{fig:dataset} \end{figure} \section{Results} \label{results} For the hand landmark model, our experiments show that the combination of real-world and synthetic datasets provides the best results. See Table \ref{tab:datasets} for details. We evaluate only on real-world images. Beyond the quality improvement, training with a large synthetic dataset leads to less jitter visually across frames. This observation leads us to believe that our real-world dataset can be enlarged for better generalization. \begin{table}[h!] \begin{center} \begin{tabular}{c|c} \textbf{Model Variation} & \textbf{Average Precision}\\ \hline No decoder + cross entropy loss & 86.22\%\\ Decoder + cross entropy loss & 94.07\%\\ Decoder + focal loss & 95.7\%\\ \end{tabular} \caption{Ablation study of palm detector design elements of palm detector.} \label{tab:detector} \end{center} \end{table} \begin{table}[h!] \begin{center} \begin{tabular}{l|c} \textbf{Dataset} & \textbf{MSE normalized by palm size}\\ \hline Only real-world & 16.1\%\\ Only synthetic & 25.7\%\\ Combined & 13.4\%\\ \end{tabular} \caption{Results of our model trained from different datasets.} \label{tab:datasets} \end{center} \end{table} Our target is to achieve real-time performance on mobile devices. We experimented with different model sizes and found that the \enquote{Full} model (see Table \ref{tab:performance}) provides a good trade-off between quality and speed. Increasing model capacity further introduces only minor improvements in quality but decreases significantly in speed (see Table \ref{tab:performance} for details). We use the TensorFlow Lite GPU backend for on-device inference\cite{tflite}. \begin{table}[h!] \begin{center} \begin{tabular}{l|c|c|c|c|c} \thead{\textbf{Model}} & \thead{\textbf{Params} \\ \textbf{(M)}} & \thead{\textbf{MSE}} & \thead{\textbf{Time(ms)} \\ \textbf{Pixel 3}} & \thead{\textbf{Time(ms)} \\ \textbf{Samsung} \\ \textbf{S20}} & \thead{\textbf{Time(ms)} \\ \textbf{iPhone11}}\\ \hline Light & 1 & 11.83 & 6.6 & 5.6 & 1.1\\ Full & 1.98 & 10.05 & 16.1 & 11.1 & 5.3\\ Heavy & 4.02 & 9.817 & 36.9 & 25.8 & 7.5\\ \end{tabular} \caption{Hand landmark model performance characteristics.} \label{tab:performance} \end{center} \end{table} \section{Implementation in MediaPipe} \label{implementation} With MediaPipe\cite{mediapipe}, our hand tracking pipeline can be built as a directed graph of modular components, called Calculators. Mediapipe comes with an extensible set of Calculators to solve tasks like model inference, media processing, and data transformations across a wide variety of devices and platforms. Individual Calculators like cropping, rendering and neural network computations are further optimized to utilize GPU acceleration. For example, we employ TFLite GPU inference on most modern phones. Our MediaPipe graph for hand tracking is shown in Figure \ref{fig:mediapipe_graph}. The graph consists of two subgraphs — one for hand detection and another for landmarks computation. One key optimization MediaPipe provides is that the palm detector only runs as needed (fairly infrequently), saving significant computation. We achieve this by deriving the hand location in the current video frames from the computed hand landmarks in the previous frame, eliminating the need to apply the palm detector on every frame. For robustness, the hand tracker model also outputs an additional scalar capturing the confidence that a hand is present and reasonably aligned in the input crop. Only when the confidence falls below a certain threshold is the hand detection model reapplied to the next frame. \begin{figure}[t!] \begin{center} \includegraphics[width=1.0\linewidth]{mediapipe_graph.png} \end{center} \caption{The hand landmark model’s output controls when the hand detection model is triggered. This behavior is achieved by MediaPipe’s powerful synchronization building blocks, resulting in high performance and optimal throughput of the ML pipeline.} \label{fig:mediapipe_graph} \end{figure} \section{Application examples} \label{application} Our hand tracking solution can readily be used in many applications such as gesture recognition and AR effects. On top of the predicted hand skeleton, we employ a simple algorithm to compute gestures, see Figure \ref{fig:gesture}. First, the state of each finger, \eg bent or straight, is determined via the accumulated angles of joints. Then, we map the set of finger states to a set of predefined gestures. This straightforward, yet effective technique allows us to estimate basic static gestures with reasonable quality. Beyond static gesture recognition, it is also possible to use a sequence of landmarks to predict dynamic gestures. Another application is to apply AR effects on top of the skeleton. Hand based AR effects currently enjoy high popularity. In Figure \ref{fig:areffect}, we show an example AR rendering of the hand skeleton in neon light style. \begin{figure}[t!] \begin{center} \includegraphics[width=1.0\linewidth]{gesture_recognition.png} \end{center} \caption{Screenshots of real-time gesture recognition. Semantics of gestures are rendered at top of the images.} \label{fig:gesture} \end{figure} \begin{figure}[t!] \begin{center} \includegraphics[width=1.0\linewidth]{ar_effects.png} \end{center} \caption{Example of real-time AR effects based on our predicted hand skeleton.} \label{fig:areffect} \end{figure} \section{Conclusion} In this paper, we proposed MediaPipe Hands, an end-to-end hand tracking solution that achieves real-time performance on multiple platforms. Our pipeline predicts 2.5D landmarks without any specialized hardware and thus, can be easily deployed to commodity devices. We open sourced the pipeline to encourage researchers and engineers to build gesture control and creative AR/VR applications with our pipeline. {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2020-06-19T02:06:30', 'yymm': '2006', 'arxiv_id': '2006.10214', 'language': 'en', 'url': 'https://arxiv.org/abs/2006.10214'}
arxiv
\section{Introduction} \label{sec:intro} \ac{GNSS} technologies today are used massively in several application scenarios, spanning from turn-by-turn terrestrial navigation, airborne and maritime navigation, timing purposes in smart grid, to name a few~\cite{yasuda2020_csur}. Despite Global Positioning System (GPS) by the US is the most famous, in the last years several region-specific solutions with the same aim have appeared, such as the European GALILEO, the Russian GLONASS, and the Chinese BEIDOU, to name a few. The vast majority of the functionalities provided by GNSS systems are open and available to the public, e.g., GPS provides an unencrypted (and un-authenticated) signal. While the lack of encryption fueled their adoption worldwide, in many use-case scenarios, unfortunately, the lack of authentication makes these systems prone to cybersecurity attacks. Indeed, the adversary can easily generate fake GNSS signals, and broadcast them to a set of targets, biasing the computation of their actual positions. We refer to the previous behavior as \emph{spoofing}~\cite{schmidt2016survey}. While requiring minimum background knowledge, cheap hardware, and free-to-use software, location spoofing is easy to play, but hard to detect and mitigate. Indeed, since GNSS satellites are orbiting in a Medium Earth Orbit (MEO), far away from the ground (about 20,000 Km), GNSS signals reach the ground with a very weak signal-to-noise ratio. Therefore, an adversary can easily overcome the aforementioned received signal strength, being always much closer to the target device than the satellite constellation. Eventually, the (spoofed) signals transmitted by the adversary reach the target device and---having a higher SNR---are considered as the actual ones, and adopted for the final computation of the device's location~\cite{Tippenhauer2011}. The low strength of the GNSS received signal makes GNSS technologies also vulnerable to jamming, being it intentional (attack) or unintentional. While there is an active research community on localization of malicious jamming sources and mitigation of their effect, the unintentional jamming, due to radar, radios, and electromagnetic interference (e.g. from pumps and engines), is more difficult to mitigate, and can cause significant issues to the correct reception of GNSS satellite signals, by breaking the link for even long period of time~\cite{mpitz2009}. During the years, several techniques have been adopted to detect and mitigate GNSS spoofing attacks~\cite{schmidt2016survey}. Some of them analyze the physical layer, trying to distinguish if the signals are coming from one only source (that could be a potential spoofer) or a set of sources, such as a genuine satellite constellation~\cite{magiera2015_jart}. Other solutions resort to crowd-sourcing, i.e., combining context information from neighbors, ad-hoc infrastructure, and cellular network information. However, the current state of the art does not take into account the specific scenario where signal sources are, by design, solo sources, or when just a few additional sources can be leveraged, but for a limited, intermittent, not predictable, period of time. In such scenarios, the deployment of additional infrastructures might be impractical, and the usage of physical layer information might not be possible due to either the lack of the underlying physical phenomenon, or because of the high price of ad-hoc hardware needed to exploit it. A striking example is represented by open seas navigation, where ships resort only to GNSS positioning for computing their current location and heading up to the destination. Indeed, open seas navigation is witnessing an emergent trend, and similarly to the automotive industry, ships are becoming more and more autonomous. According to recent forecasts, a landscape of fully autonomous vessels is predicted by the year 2035, where GNSS technology will be massively adopted to provide location awareness~\cite{septentrio}. In such a scenario, GNSS jamming and spoofing will become dreadful threats, since autonomous vessels---even more than the human-controlled ones---require a trusted and precise localization procedure~\cite{caprolu2020_commag}. {\bf Contribution.} In this paper, we provide two main contributions. First, we reverse-engineer several infrastructure configuration parameters of the IRIDIUM constellation. Second, leveraging the previously mentioned result, we exploit opportunistic \ac{IRA} messages to provide yet another independent localization solution. As for the former contribution, one should notice that, though \acl{IRA} are accessible, all other information about IRIDIUM are treated as proprietary by the infrastructure owner: Iridium Communications Inc.. To overcome this lack of information, we ran an extensive measurement campaign using commercially available \acp{SDR}, acquiring \acl{IRA} messages for more than $1000$~hours. Using this large dataset, we reverse-engineered several network configuration parameters of the IRIDIUM constellation, including the satellites speed, packet interarrival times, maximum satellite coverage, satellite pass duration, and the satellite beam constellation---all these data have been released as open-source~\cite{crilab}. We used the above parameters to model the IRIDIUM constellation. Later, we moved to exploit opportunistic \ac{IRA} messages, combining them with the information acquired during the reverse-engineering process, to estimate the current position of the receiving device. Our research contributes not only to validate the GNSS information, but also to provide yet another independent localization solution---although being slightly inaccurate compared to the GNSS, given the harsh system conditions---in the presence of GNSS jamming. Being the IRIDIUM constellation characterized by worldwide availability, our solution can be used even in unattended scenarios (deserts and oceans), where no other ad-hoc in-land network infrastructure can be used for crowd-sourcing, and where the available GNSS hardware cannot be replaced or updated with multiple-antenna setups. Finally, we also highlight some novel, challenging research directions. {\bf Paper organization.} The paper is organized as follows. Section~\ref{sec:related} reviews recent related work on GNSS spoofing detection and mitigation, Section~\ref{sec:iridium} introduces the main system features of the IRIDIUM satellite platform, Section~\ref{sec:adversary_model} depicts the adversarial model assumed throughout the work, Section~\ref{sec:measurement_setup} illustrates our measurement setup, Section~\ref{sec:iridium_data_analytics} includes the features of the IRIDIUM constellation platform inferred through our measurement campaign, Section~\ref{sec:position_error_estimation} provides the details of our spoofing detection technique based on opportunistic \ac{IRA} messages, while Section~\ref{sec:comparison} provides a systemic comparison between our proposal and the most important related work. Finally, Section~\ref{sec:conclusion} draws conclusions and highlights our future research directions. \section{Related Work} \label{sec:related} \ac{GNSS} spoofing identification, detection, and mitigation are all research areas that attracted the attention of a lot of researchers during the years. Major contributions are coming from the idea of resorting to other over-the-air information to cross-check the actual position of the targeted spoofed device. A very recent contribution~\cite{oligeri2019_wisec} involves crowd-sourced information from cellular network access points to verify the actual position of the device. Authors showed that beacons broadcast from cellular networks access points can be exploited to retrieve their position, and therefore, checking the consistency of the current position of the device received from the GPS constellation. Authors in~\cite{jansen2016_acsac} showed that multiple (colluding) GPS receivers can be used to detect a spoofer. Authors showed that by leveraging spatial noise correlations, the false acceptance rate of the countermeasure can be improved while preserving the sensitivity to attacks. A collaborative detection scheme is proposed in~\cite{milaat2018_commlett}. The authors assume a set of vehicles exchange measured GPS code pseudo-ranges using a dedicated short-range communication. Each vehicle elaborates on the exchanged GPS data and derives independent statistics. These statistics are then exploited to detect high correlations in the time of arrival of spoofed GPS signals, and therefore, highlighting the presence of a GPS spoofer. A physical layer solution is proposed by~\cite{zhang2012_milcom}, involving two antennas with different radiation patterns. Genuine GPS signals are supposed to come from several sources (satellites), and therefore, exploiting a two-antenna deployment involves a different signal-to-noise ratio measured by the two antennas. If the two antennas experience the same signal-to-noise, it means the signal is coming from the same source, and therefore, a GPS spoofer is likely to be in the neighborhood. Authors in~\cite{sciancalepore2018_cns} proposed a solution exploiting meteor burst communications to verify the location of the spoofed device. The solution exploits the radio reflection properties of ephemeral meteor trails, combined with multiple anchors that can be deployed even hundreds of Km from the receiver. Although being robust to jamming and eavesdropping, their solution requires dedicated infrastructure. Another crowd-sourcing solution has been proposed by~\cite{Jansen2018}. The authors proposed the deployment of multiple nodes at the ground to monitor the air traffic from GPS-derived position advertisements that aircraft periodically broadcast for air traffic control purposes. Spoofing attacks are detected and localized by the independent infrastructure on the ground which continuously analyzes the contents and the times of arrival of these advertisements. A vision-based GPS spoofing detection method for unmanned aerial vehicles (drones) is proposed by~\cite{qiao2017_cis}. The on-board camera and the inertial measurement unit are used to get the velocity and position of the aircraft, thus detecting unexpected changes in the flight path. Another cooperative solution has been proposed by~\cite{heng2015_tis}. The GPS signal is verified by resorting to a network of cooperative GPS receivers. Each receiver in the network correlates its version of the signal with those received by other receivers to detect spoofing attacks. The authors in~\cite{magiera2015_jart} exploited phase delay measurements from an antenna array to infer between single and multiple GPS sources, and therefore, detect the presence of a spoofer. In Section~\ref{sec:comparison} we will provide a comparison between our solution and the ones introduced in this section, based on some distinctive system requirements. We remark that the Iridium satellite network has been previously exploited for localization purposes by~\cite{leng}. The authors exploited physical layer information and a reference anchor in a well-known position to locate the receiver by resorting to both time difference of arrival (TDOA) and frequency difference of arrival (FDOA) techniques. Another similar contribution is provided by~\cite{Tan2019_access} and~\cite{tan2020_electronics}. The authors exploited the instantaneous Doppler effect of \ac{IRA} messages to infer the position of the receiver. However, using the Doppler shift for GNSS spoofing detection would require the deployment of multiple receivers, organized in ad-hoc network infrastructure, typically not available in deserts and oceans~\cite{ghose2015}, \cite{schafer2016}. Finally, we recall that localization and spoofing detection are two different research problems, characterized by different system requirements. Localization techniques are used to either replace or support the traditional GNSS signals, while spoofing detection schemes are usually designed to work in conjunction with the GNSS, taking an active part (raising alarms and indicating corrections) only when they detect inconsistencies between the position reported by the GNSS and the one obtained via local computations. \section{Background on IRIDIUM} \label{sec:iridium} The IRIDIUM satellite platform has been described for the first time in the seminal paper~\cite{iridium}. The platform has been set up in 1993, and it is mainly constituted by a set of \ac{LEO} satellites, able to guarantee the full earth coverage for data and voice communications. IRIDIUM RF operations take place in the L-band, i.e., in the range $[1,616 - 1,626.5]$~MHz, by resorting to dedicated satellite-phones, while the communications between the satellites happen in the 23GHz band. The name of the satellite platform is due to the initial intended number of satellites, being 77 the atomic number of the chemical element Iridium. However, the final deployment of the satellite constellation counts only 66 satellites, which are the ones necessary to guarantee coverage for the whole Earth's surface. On the ground, to initiate and receive IRIDIUM calls, a user can leverage dedicated satellite phones and pagers provided by companies such as Motorola and Kyocera. IRIDIUM services are also used on a subscription basis by aircraft and vessels, thanks to dedicated transceivers units. Moreover, short IRIDIUM-compliant transceivers are also available and currently used within \ac{IoT} products to provide backhaul connections~\cite{iridium_iot}. Each IRIDIUM satellite is characterized by a three-antenna array, forming a honeycomb pattern of 48 beams on the ground. Therefore, a generic IRIDIUM user might experience two types of hand-off, i.e., either from one beam to another beam (intra-satellite) or from one satellite to another one (inter-satellite). In general, when the user is served by a beam at the edge of the honeycomb, the system manages the hand-off to a neighbor satellite. The channels provided by the system can be divided into two categories, i.e., \emph{system overhead channels} and \emph{bearer service channels}~\cite{icao}. In this paper, we are interested in one specific \emph{system overhead} channel, i.e., the \acl{IRA} (IRA) broadcast channel. This channel operates at $1,626.27$~MHz, and it is an unencrypted downlink-only channel used to send \emph{\ac{IRA}} messages to individual subscriber units---to be used for handover operations. \ac{IRA} messages contain the following plain-text information: satellite ID, beam ID, location at ground (in terms of longitude and latitude, as computed by the satellite based on a proprietary algorithm), altitude information (typically around $800$~km), and other information useful for handover purposes, such as the Temporary Mobile Subscriber Identity (TMSI) of the end-user equipment performing the handover. Note that, being an unencrypted channel, the IRA broadcast channel can be received by using a general-purpose \acl{SDR} (\ac{SDR}) and a generic antenna. The position information computed by the IRIDIUM satellites and emitted through the broadcast IRA channel is used in this paper to compute a location estimation at the receiver side. This information is used to cross-check the position estimated from the GNSS constellation. \section{Adversary and System Model} \label{sec:adversary_model} Our adversary model consists of a malicious entity, able to generate fake GNSS signals by resorting to the combination of an \ac{SDR}, an antenna, and a GNSS spoofing software tool, such as~\cite{gpssdrsim}. We assume an isolated playground, not relying on any Internet connection and any other means (e.g., WiFi and Cellular Networks) to derive location information. A typical scenario that fits the previous assumptions might be constituted by wide inhabited open areas, such as deserts, or open seas (oceans), where the target devices cannot receive any additional information to verify their actual GNSS location. Figure~\ref{fig:adversary_model} shows the system model considered throughout this paper. As a reference scenario, we consider a boat relying on GNSS information for its navigation. The adversary is willing to de-tour the boat by performing a GNSS spoofing attack; in particular, the adversary wants to re-route the boat from path $1$ to path $2$ in Fig.~\ref{fig:adversary_model}. Our solution exploits the IRIDIUM satellite network to independently verify the actual position of the boat, and therefore, raising an alarm when a de-tour is detected. It is worth noting that we do not assume any active IRIDIUM subscription. Thus, the IRIDIUM position-providing service \ac{STL} cannot be used. Indeed, purchasing unlimited subscription plans to IRIDIUM services can be particularly expensive for shipowners, and it could also require the hiring of dedicated teams to perform the deployment and maintenance in all the vessels. On the contrary, our solution exploits opportunistic IRIDIUM messages; in particular, the \ac{IRA} messages delivered in clear-text on the \emph{Ring Alert Broadcast Channel} (at the frequency $1,626.27$~MHz). Indeed, being unencrypted these messages can be received with a generic low-cost SDR. In our system model, as depicted by the gray circle in Fig.~\ref{fig:adversary_model}, the boat continuously performs a loose localization process, and therefore, it checks if the current, locally computed, GNSS position is far away from the position provided by our solution exploiting the IRIDIUM constellation. In the remainder of this paper, we will estimate the configuration parameters and evaluate the thresholds to provide timely, independent, and effective verification of the GNSS localization. \begin{figure} \includegraphics[width=\columnwidth]{adversary_model.pdf} \centering \caption{Scenario and Adversary model: The target (boat) is re-routed by the adversary from path 1 to path 2, but our solution enables independent location verification by exploiting the IRIDIUM satellite network. Therefore, eventually the target will be able to detect the GNSS spoofing attack.} \label{fig:adversary_model} \end{figure} \section{Measurement setup} \label{sec:measurement_setup} Figure~\ref{fig:setup} shows the setup we adopted to receive the messages from the Iridium constellation. The hardware is mainly constituted by a Software Defined Radio USRP X310, a telescopic \emph{stilo} antenna, and a Laptop Dell XPS15 9560, equipped with 32GB of RAM and 8 Intel Core i7700HQ processors running at 2.80 GHz. As for the software, we adopted the GNURadio development toolkit and the related Iridium module \cite{iridiumgr}. The output is subsequently parsed to generate meaningful data analytics, available for downloading at \cite{crilab}. Our measurement campaign has been carried out in very harsh conditions: from a balcony outside our office. This sub-optimal setup significantly affects the number of received packets, being the antenna very close to the wall of the building. Moreover, the stylo antenna is recommended for operation from 75MHz to 1GHz, being therefore not optimal for the reception of the IRIDIUM signals at 1626.270833 MHz. While our setup still guarantees the collection of a reasonable amount of messages in a long term measurement, due to a high packet loss, it does not provide the best performance for a live-test of GPS spoofing detection. In later sections, we provide more details on statistics related to packet loss and how the later one affects our solution. The good results achieved in such harsh conditions undoubtedly show the viability of our approach. \begin{figure} \includegraphics[width=0.8\columnwidth]{setup.jpeg} \centering \caption{Our receiver setup to collect the \ac{IRA} messages: a Dell XPS15 9560 laptop and a USRP X310.} \label{fig:setup} \end{figure} We collected a total of about $1019$~hours of measurements consisting of $569,431$ samples. An excerpt from the dataset is reported in Table~\ref{table:excerpt}. For each data sample, we have the time (seconds and milliseconds), the satellite ID, the beam ID, and both latitude and longitude of the satellite/beam at the ground. Specifically, when the Beam ID is equal to zero, the position (latitude/longitude) refers to the position of the satellite at the ground, e.g., satellite 115 in the example of Table~\ref{table:excerpt}. When the Beam ID is different than zero, latitude and longitude refer to the position of the beam at the ground, e.g., the second sample is related to beam 44 belonging to satellite 115 having a position at the ground of $\langle +23.06, +49.81 \rangle$. In all our measurements we counted a total of 66 satellite IDs, i.e., \{2, 3, 4, 5, 6, 7, 8, 9, 13, 16, 17, 18, 22, 23, 24, 25, 26, 28, 29, 30, 33, 36, 38, 39, 40, 42, 43, 44, 46, 48, 49, 50, 51, 57, 65, 67, 68, 69, 71, 72, 73, 74, 77, 78, 79, 81, 82, 85, 87, 88, 89, 90, 92, 93, 94, 96, 99, 103, 104, 107, 109, 110, 111, 112, 114, 115\}, coinciding with the number of active IRIDIUM satellites reported by the service provider, and the full-beam constellation equal to 48 beam IDs, i.e., $\{1, \ldots, 48\}$. \begin{table}[htbp] \footnotesize \caption{Excerpt of the collected dataset.} \begin{tabular}{cccccc} \textbf{Time (s)} & \textbf{Time (ms)} & \textbf{\begin{tabular}[c]{@{}c@{}}Satellite \\ ID\end{tabular}} & \textbf{\begin{tabular}[c]{@{}c@{}}Beam \\ ID\end{tabular}} & \textbf{Latitude} & \textbf{Longitude} \\ \hline 1580712040 & 000000739 & 115 & 0 & +29.81 & +046.10 \\ 1580712040 & 000004519 & 115 & 44 & +23.06 & +049.81 \\ 1580712040 & 000005059 & 115 & 46 & +25.95 & +051.69 \\ 1580712040 & 000005599 & 115 & 47 & +26.94 & +047.71 \\ 1580712040 & 000008839 & 115 & 0 & +30.29 & +046.13 \\ 1580712040 & 000013159 & 115 & 44 & +23.56 & +049.80 \\ 1580712040 & 000013699 & 115 & 46 & +26.46 & +051.72 \end{tabular} \label{table:excerpt} \end{table} \section{IRIDIUM Data Analytics} \label{sec:iridium_data_analytics} In this section, we provide a thorough analysis of the network information that can be extracted from \ac{IRA} messages. {\bf Satellites speed.} Figure~\ref{fig:satellite_speed} shows the probability distribution function associated with the satellites speed at the ground. We took into account all the satellites IDs collected during our measurement campaign, by considering their positions and the absolute time associated with the reception of the packets. The satellite speed $v$ has been computed as the ratio of the difference between two consecutive positions, i.e., $\delta$, and the elapsed time, i.e., $\epsilon$, yielding $v = \frac{\delta}{\epsilon}$. We observe that the most likely speed is about $6.89$ Km/s, consistent with the approximate speed of a generic LEO satellite~\cite{ganz94}. We also notice the presence of many (unlikely) high-speed samples ($v>10$ Km/s). These inconsistent speeds are experienced when the time difference between two consecutive messages is particularly high, likely due to the packet loss. In particular, packet loss, especially when experienced in bursts, accumulates a lot of errors as for time and space, leading to inconsistent high speeds. Since we are not aware of the actual accuracy of beam and satellite coordinates at the ground, we guess that large periods between packets (due to packet loss) accumulate the aforementioned errors. However, we notice that this phenomenon does not affect the quality of our solution. \begin{figure} \includegraphics[width=\columnwidth]{figures/satellite_speed.pdf} \centering \caption{Satellite speed at ground: probability distribution function associated with satellite speeds at ground and most likely speed (6.89Km/s).} \label{fig:satellite_speed} \end{figure} {\bf \ac{IRA} message rate.} All our analysis is based on the reception of \ac{IRA} messages. Figure~\ref{fig:timings} shows the probability distribution function associated with the interarrival times of the \ac{IRA} messages. The inset figure shows the relative error to the expected interarrival time of 90 milliseconds, as reported by related work on IRIDIUM~\cite{leng}\cite{Tan2019_access}. Indeed, each beam transmits an \ac{IRA} message every $4.32$~seconds. Being the number of beams 48, a receiver will receive a generic \ac{IRA} message every 90ms ( $4320/48$). We observe also that the link is characterized by an extremely high packet error rate. Indeed, the likelihood for the interarrival time is about 4.87 seconds, i.e., one message is received every 66 lost ones. Conversely, the jitter is small; indeed, the computational overhead for message decoding is negligible and the vast majority of the messages experience an interarrival time that is multiple of 90 ms. \begin{figure} \includegraphics[width=\columnwidth]{figures/timings.pdf} \centering \caption{\ac{IRA} interarrival times: probability distribution function associated to \ac{IRA} interarrival times and their maximum likelihood at 4.87 seconds. The inset figure represents the relative error respect to 90ms representing the actual rate at the transmitting side (for different beams).} \label{fig:timings} \end{figure} {\bf Coverage.} To understand the maximum coverage range of an Iridium-compliant device, we consider the furthest satellite positions at the ground, independently of the time they have been collected. Figure~\ref{fig:coverage} shows the furthest satellite positions (at ground) from our locatio represented by the red cross. Many factors can affect the reception of \ac{IRA} messages: mountains in the north-east and south-west significantly affect the signal propagation, especially when the satellite is far-away from the receiver, at the minimal altitude over the horizon, or simply the presence of buildings. The overall area covered through our setup sums up to about $10^6 \cdot 8.3 km^{2}$, further demonstrating the capability of a very simple setup to cover even large areas. \begin{figure} \includegraphics[width=\columnwidth]{figures/coverage.pdf} \centering \caption{Maximum satellite distances (at ground) from the receiving source.} \label{fig:coverage} \end{figure} Figure~\ref{fig:sat_distance} shows the probability density function associated with the distance between the receiver and the satellite positions at the ground. As previously discussed, the transmission distance is significantly affected by the geography characterizing the neighborhood of the receiver. The likelihood of the maximum distance is $1,625$~Km. Note that a similar result can be extracted also by fitting the red dots in Fig.~\ref{fig:sat_distance}, using the Pratt method \cite{pratt}, obtaining a distance of about $2,346$~Km. \begin{figure} \includegraphics[width=\columnwidth]{figures/sat_distance.pdf} \centering \caption{Probability distribution function associated with the maximum satellite distances (at ground) from the receiving source. The maximum likelihood is $1,625~$Km.} \label{fig:sat_distance} \end{figure} {\bf Satellite pass.} Let us consider a specific satellite, i.e., the Iridium satellite 78. Figure~\ref{fig:satellite78} shows all the passes extracted from all the measurements we collected about the aforementioned satellite. We adopted the red and green colors for the upward and downward directions, respectively. The overall coverage is consistent with the data we previously discussed for Fig.~\ref{fig:coverage}, while we observe a total of $59$ passes upward and $59$ downward in a period of time of about $1000$~hours. \begin{figure} \includegraphics[width=\columnwidth]{figures/satellite78.pdf} \centering \caption{Satellite 78 passes: data collected from Iridium satellite 78, where red and green dots represent upward and downward passes, respectively.} \label{fig:satellite78} \end{figure} The pass duration can be computed by considering the time between the instant when the satellite appears at the receiver and the last sample before disappearing. Figure~\ref{fig:pass_duration} shows the probability distribution function associated with the pass duration, considering all the satellites data collected from all our measurements. The maximum likelihood for the pass is about $7.59$ minutes. The distribution presents a heavy tail on the left side, i.e., pass duration less than 4 minutes: this is due to satellites crossing the coverage region far away from the receiver, and therefore, being characterized by short periods of intersection with the coverage area of the receiver. We searched for the best fit distribution and we found that to be the Extreme Value Distribution $evd(t)$, as depicted by Eq.~\ref{eq:passes}. \begin{equation} \label{eq:passes} evd(t) = \frac{1}{\sigma} \exp{\bigg(\frac{t-\mu}{\sigma}\bigg)} \exp{\bigg(-\exp{\bigg(\frac{t-\mu}{\sigma}\bigg)}\bigg)}, \end{equation} where $\mu=7.28$ and $\sigma=1.67$ are the best-fit location parameter and the scale parameter of the distribution, respectively. \begin{figure} \includegraphics[width=\columnwidth]{figures/pass_duration.pdf} \centering \caption{Pass duration: probability distribution function associated with the duration of a satellite pass.} \label{fig:pass_duration} \end{figure} {\bf Satellite and beams.} Figure \ref{fig:satellite78_beams} shows an example pass (red circles) of satellite 78 and the beams (red dots) with the related beam IDs. We recall that both the beam positions at the ground and the beam IDs have been collected from the \ac{IRA} messages. Due to the previously mentioned packet loss rate, many beams are missing and only a subset of them are available at the receiver. In the aforementioned case study, we were able to retrieve 89 beam positions belonging to 15 different beams (for one satellite pass). \begin{figure} \includegraphics[width=\columnwidth]{figures/satellite78_beams.pdf} \centering \caption{Single satellite pass and beams: red circles represent the position of satellite 78 (at ground) while red dots show the beams' position at the ground. Beams IDs are reported accordingly to the information collected from the \ac{IRA} message.} \label{fig:satellite78_beams} \end{figure} {\bf Beam constellation.} We consider all the satellite beams collected from all our measurements and we computed their displacement to the satellite position. Black dots in Fig.~\ref{fig:beam_positions} show the beam constellation, while red crosses represent the centroid for each cloud of beams. The labels are consistent with the beam IDs retrieved from the \ac{IRA} messages. The beam constellation is constituted by 48 beams organized in three concentric circles with radii of about 3.36, 7.98, and 14.35 Km, respectively. Finally, we observe that, to represent the beams in a well-organized constellation, we had to detect, distinguish, and subsequently compensate, satellites moving north (upward) from the ones moving south (downward). Indeed, as previously discussed, data collected from beams might seem inconsistent, but actually, it is not, when making the following considerations: \begin{itemize} \item \emph{Same beams belonging to the same satellite moving on different directions.} The same satellite can be observed going north, and subsequently south, after approximately 650 minutes. Indeed, due to its inclined orbit, the satellite will be back to the original position with the opposite transit direction. \item \emph{Same beams belonging to different satellites moving on different directions.} Each location experiences different satellites going to different directions, either north or south. \end{itemize} For both the above configurations, the beam IDs should be mirrored to the x-axis. In particular, the beam constellation reported in Fig.~\ref{fig:beam_positions} is consistent with satellites going upward, i.e., from the south pole to the north pole. \begin{figure} \includegraphics[width=\columnwidth,height=80mm]{figures/beam_positions.pdf} \centering \caption{Relative beam positions (at ground) respect to the satellite position (at ground). Each black dot represents a different measurement while crosses represent the centroid of each cloud associated to a different beam. Labels are consistent with the beam identifiers retrieved from the \ac{IRA} messages.} \label{fig:beam_positions} \end{figure} \section{GPS Spoofing Detection} \label{sec:position_error_estimation} In this section, we provide the details of our GNSS spoofing detection technique, aimed at detecting GNSS spoofing attacks using the IRIDIUM satellite constellation. Section~\ref{sec:pos_error} introduces the error in the position estimation via the \ac{IRA} messages, Section~\ref{sec:solution} presents the details of our spoofing detection solution, Section~\ref{sec:performance} shows the performance of the described technique, while Section~\ref{sec:spoofing} discusses the feasibility of a combined spoofing attack involving both the GNSS system and the IRIDIUM constellation. \subsection{Position error estimation} \label{sec:pos_error} In this subsection, we estimate the error between the actual receiver position (taken from the GPS) and the one computed from the information extracted from the \ac{IRA} messages. The intuition behind our solution consists of computing the mean of all the latitude and longitude coordinates (centroid) collected from the beams. In general, the precision of the position estimation will be affected by the number of collected \ac{IRA} messages, and therefore, the time required to receive such a number of messages (waiting time). Figure~\ref{fig:position_error} shows the error between the receiver position and the estimated location, as a function of the number of collected \ac{IRA} messages. We observe that an error of about 10Km can be reached by collecting about 6,100 \ac{IRA} messages. \begin{figure} \includegraphics[width=\columnwidth]{figures/position_error.pdf} \centering \caption{Localization error as a function of the number of received \ac{IRA} messages. } \label{fig:position_error} \end{figure} Interestingly, the relationship between the localization error $L_{err}$ and the number of \ac{IRA} messages $n$ is characterized by a power-law, as depicted by the red line in Fig.~\ref{fig:position_error}, that in turn, is represented by Eq.~\ref{eq:loc_err}: \begin{equation} \label{eq:loc_err} L_{err} = n^m \cdot 10^q, \end{equation} where $m=-0.5974$ and $q=3.2826$. Figure~\ref{fig:time_ring} shows the relation between the number of \ac{IRA} messages and the time to collect them, given different packet error rates, i.e., $\{0.01, 0.1, 0.5, 0.99\}$. In our scenario, given the adopted equipment and setup, we experienced a very high packet error rate (CFR. Fig.~\ref{fig:timings}), summing up to about 1 message received every 66, i.e., a packet error just slightly less than $0.99$. In better conditions, lower packet error rates can be easily achieved, leading to a significantly higher amount of collected packets per unit of time. As depicted in Fig.~\ref{fig:time_ring}, in the worst-case scenario---our deployment, $6100$ packets, guaranteeing a localization error of about 10Km, require about 10 hours. Assuming lower packet error rates and good receiving conditions (such as in a desert or ocean), the same amount of packets can be collected in 1 hour or even in 6 minutes, assuming a packet error rate of either 10\% or 1\%, respectively. \begin{figure} \includegraphics[width=\columnwidth]{figures/time_ring.pdf} \centering \caption{Waiting Time (delay) to collect the \ac{IRA} messages as a function of the packet error rate.} \label{fig:time_ring} \end{figure} \subsection{Exploiting IRA messages to estimate receiver location} \label{sec:solution} Our solution involves a multi-stage algorithm described in the following. \begin{enumerate} \item {\bf Collect data.} The user continuously collects \ac{IRA} messages from the IRIDIUM constellation network, as described in the previous sections. \item {\bf Compensate movement.} Given the movement of the receiver during the message collection, the acquired data should be compensated as a function of the movement. Therefore, assuming the acquisition process starts at $t_0$, and the user is moving with speed $v$, the collected information from the \ac{IRA} messages should be compensated as reported by Eq.~\ref{eq:comp}. \begin{eqnarray} \label{eq:comp} \Delta x & = & x(t_0) + \cos(v \cdot \Delta t), \nonumber\\ \Delta y & = & y(t_0) + \sin(v \cdot \Delta t), \end{eqnarray} where $\Delta t$ is the time between two consecutive IRIDIUM packets, while $x$ and $y$ are latitude and longitude, respectively. \item {\bf Compute location $I_{pos}$.} The position of the receiver is estimated as the centroid computed over the beams' positions at ground, yielding Eq.~\ref{eq:centroid}. \begin{equation} \label{eq:centroid} I_{pos} = \bigg(\frac{1}{N} \sum_{i=1}^{N} x_i,\quad \frac{1}{N} \sum_{i=1}^{N} y_i\bigg), \end{equation} where $(x_i, y_i)$ are the latitude and longitude of the position at ground for beam $i$ , while $N$ is the number of beams taken into account for the computation (cfr. Fig.~\ref{fig:position_error}). \item {\bf Compare $I_{pos}$ with $G_{pos}$.} The estimated position $I_{pos}$ from the IRIDIUM satellite network is compared with that one received from the GNSS system $G_{pos}$. Depending on different parameters, that will be discussed later on, an alarm is raised if the difference is greater than a predetermined threshold $thr$, i.e., $\mid I_{pos} - G_{pos} \mid > thr$. \end{enumerate} \subsection{Performance} \label{sec:performance} Our solution is particularly suitable for scenarios where crowd-sourcing is not possible, i.e., there are no other independent sources in the neighborhood to verify the current GNSS localization. A few examples of such scenarios are deserts, forests, remote rural areas, and open seas. We choose the latter one as our reference scenario, and without loss of generality, we consider a ship moving through a pre-defined path according to different speeds. According to the specific cruise speed, we provide different indicators to measure the performance of our solution. In the following, we consider different classes of ships~\cite{marineinsight}, as depicted in Table~\ref{tab:shiptype}. Class S1, i.e., \emph{bulk carriers}, carry unpacked bulk cargo, class S2, i.e., \emph{Container Ships}, carry containers, S3, i.e., \emph{Oil and chemical tankers}, are designed specifically to carry oil and chemicals, S4, i.e., \emph{RORO vessels}, roll on roll off ships are special types of vessels used for the transportation of automobile vehicles, and finally, S5, i.e., \emph{Cruise Ships}, are luxury vessels used to take passengers on pleasure journey. \begin{table}[] \caption{Ship type and speeds.\label{tab:shiptype}} \begin{tabular}{llll} & \textbf{Ship Type} & \textbf{\begin{tabular}[c]{@{}l@{}}Speed\\ {[}knots{]}\end{tabular}} & \textbf{\begin{tabular}[c]{@{}l@{}}Speed \\ {[}km/h{]}\end{tabular}} \\ \hline \multicolumn{1}{l|}{S1} & Bulk Carriers & 13-15 & 24-28 \\ \multicolumn{1}{l|}{S2} & Container Ships & 16-24 & 30-44 \\ \multicolumn{1}{l|}{S3} & Oil and chemical tankers & 13-17 & 24-31 \\ \multicolumn{1}{l|}{S4} & RORO vessels & 16-22 & 30-41 \\ \multicolumn{1}{l|}{S5} & Cruise Ships & 20-25 & 37-46 \end{tabular} \end{table} \begin{figure} \includegraphics[width=\columnwidth]{figures/false_positive.pdf} \centering \caption{False positive events as a function of the number of collected \ac{IRA} messages.} \label{fig:false_positive} \end{figure} \begin{table*}[h] \centering \caption{Overview of related work on GNSS spoofing detection and related system requirements. \label{tab:related}} \begin{tabular}{|P{2cm}|P{2.2cm}| P{2.2cm}| P{2.cm}| P{2.cm}| P{2.cm}|} \hline \textbf{Ref.} & \textbf{No need for Auxiliary Ad-Hoc Infrastructure} & \textbf{No need for Auxiliary In-land Infrastructure} & \textbf{No need for PHY-layer Information} & \textbf{No need for Dedicated Hardware} & \textbf{No need for Multiple Antennas} \\ \hline \cite{oligeri2019_wisec} & \cmark & \xmark & \cmark & \cmark & \cmark \\ \hline \cite{jansen2016_acsac} & \cmark & \cmark & \xmark & \xmark & \xmark \\ \hline \cite{milaat2018_commlett} & \cmark & \cmark & \xmark & \cmark & \xmark \\ \hline \cite{zhang2012_milcom} & \cmark & \cmark & \xmark & \xmark & \xmark \\ \hline \cite{sciancalepore2018_cns} & \xmark & \xmark & \xmark & \cmark & \xmark \\ \hline \cite{Jansen2018} & \xmark & \xmark & \xmark & \cmark & \xmark \\ \hline \cite{qiao2017_cis} & \cmark & \cmark & \cmark & \xmark & \cmark \\ \hline \cite{heng2015_tis} & \xmark & \xmark & \xmark & \cmark & \xmark \\ \hline \cite{magiera2015_jart} & \cmark & \cmark & \xmark & \xmark & \cmark \\ \hline Our Proposal & \cmark & \cmark & \cmark & \cmark & \cmark \\ \hline \end{tabular} \hfill \end{table*} As previously discussed, the accuracy of the estimated location $I_{pos}$ depends on the number of collected messages. Indeed, recalling Fig.~\ref{fig:time_ring}, the number of collected messages is correlated to the time dedicated to collect them. Considering a location estimation error of about $10$~Km, meaning $6,100$ \ac{IRA} messages to be collected in about 6 minutes (packet loss equal to 1\%), the fastest ship, i.e., S5, would have moved off about 4.1Km (worst case). In the best-case scenario, the slowest ship, i.e., either S1 or S3, would have traveled less than 3.1 Km in the same amount of time (6 minutes). This means that, for all the considered cases, the movement performed by the ship is in the same order of the localization error, and therefore, our solution can be effectively adopted to detect GPS spoofing attacks. \begin{definition} Given a threshold $thr$, we define a \emph{False Positive} event when no GNSS spoofing attack is present, and a position $I_{pos}$ computed exploiting the \ac{IRA} messages verifies $|I_{pos} - G_{pos}| > thr$ ---where $G_{pos}$ is the position computed from the GNSS constellation. \end{definition} Figure~\ref{fig:false_positive} shows the false positive rate as a function of the collected \ac{IRA} messages, considering three different thresholds, i.e., $thr \in \{10, 15, 20\}$ Km, for a number of \ac{IRA} messages varying from 10 to 10,000. We want to stress that we are considering \emph{single} false-positive events, while a more in-depth analysis considering the temporal distribution of false-positive events (bursts of consecutive events) might significantly improve the robustness of our solution to false alarms---this task is left for future work. Finally, it is interesting to observe that there is a relationship between the false positive rate and the number of \ac{IRA} messages considered in the location estimation technique. Indeed, we fit the samples belonging to the three different thresholds by using a linear regression model, yielding the solid lines in Fig.~\ref{fig:false_positive}, i.e., the red solid line for $thr=10$ Km, the green solid line for $thr=15$ Km, and finally, the blue solid line for $thr=20$km. The best-fit model associated with the aforementioned samples is represented by Eq.~\ref{eq:fp_fit}: \begin{equation} \label{eq:fp_fit} y = 10^{m \cdot n} \cdot 10^q \end{equation} \noindent where $n$ is the number of \ac{IRA} messages, $q \approx 0$, and $m=-4.6 \cdot 10^{-5}$, $m=-8.9 \cdot 10^{-5}$, $m=-1.4 \cdot 10^{-4}$ for $thr = 10$, $thr = 15$, and $thr = 20$, respectively. Overall, Eq.~\ref{eq:loc_err} and Eq.~\ref{eq:fp_fit} allow an end-user deploying our solution to have an immediate idea of the expected system performance. In particular, knowing the number of messages received in a given unit of time, the cited equations can be used to provide an estimation of the expected location accuracy and false-positives rate of the system---this latter one with the caveat that just a single value exceeding the threshold would trigger the alarm. \subsection{Spoofing the IRIDIUM satellite constellation} \label{sec:spoofing} With our solution in place, the only chance for the adversary to fool the receiver would be to perform a combined attack on both the GNSS and IRIDIUM platforms. In the following, we discuss the feasibility of spoofing IRIDIUM signals. As detailed in the following, it runs out that, given the nature of our solution, spoofing IRIDIUM signals to subvert our localization system is more challenging compared to all the GNSS ones. {\bf Time.} Our solution requires a not-negligible amount of time (depending on the packet loss) to locate the vessel with a small precision error (less than 10Km). While GNSS requires seconds to be spoofed, to affect our IRIDIUM-based localization system, the adversary has to deploy a transmitter that should keep transmitting for either minutes or hours, thus becoming easier to detect, identify, and locate. {\bf Signal strength.} The IRIDIUM satellite infrastructure is significantly different from the typical GNSS constellations. GNSS satellites are far away from the ground (in a MEO orbit, at about $20,000$~Km), while the Iridium constellation is composed of LEO satellites, orbiting at about $800$~Km. Therefore, the received signal strength on the ground is higher than the GNSS ones~\cite{tan2020_electronics}, and hence the adversary requires higher transmission power to overcome the legitimate signal. {\bf Complexity.} The adversary should mimic a consistent array of beams moving coherently all together, at a consistent speed, with consistent interarrival times, and eventually, with compatible passes duration. We consider this event very unlikely, especially considering the time factor previously described. \section{System-Level Comparison with Other Solutions} \label{sec:comparison} To provide further insights, Table~\ref{tab:related} wraps up an overview of the system requirements for both the works previously discussed in Section~\ref{sec:related} and our proposal. We notice that most of the already proposed solutions rely on auxiliary network infrastructures. These auxiliary infrastructures can be set up ad-hoc for the spoofing detection task (such as in~\cite{sciancalepore2018_cns},~\cite{Jansen2018} and~\cite{heng2015_tis}), or they can be already in place for other purposes (e.g., the mobile cellular network used in~\cite{oligeri2019_wisec} and the avionics network in~\cite{Jansen2018}). However, these infrastructures are generally not available in remote or offshore areas, such as deserts and open seas. Other proposals, such as \cite{jansen2016_acsac},~\cite{milaat2018_commlett},~\cite{zhang2012_milcom}, and~\cite{heng2015_tis}, rely on multi-antenna detection schemes, requiring a dedicated setup and the hard swap of existing GNSS receivers. Moreover, schemes such as~\cite{magiera2015_jart} require access to physical layer information of the GNSS signal, and therefore, requiring dedicated equipment to be deployed, they come with consequently high costs. Overall, the comparison shows that our proposal leveraging opportunistic IRIDIUM signals is the only one that does not require any auxiliary ad-hoc infrastructure, it does not leverage any physical layer information and, finally, it does not require the deployment of either multiple antennas or dedicated hardware. Therefore, our solution is ideal when a specific target receiver is meant to be operated in remote areas (desert or open seas), and whose hardware cannot be modified after deployment. \section{Conclusion and Future Work} \label{sec:conclusion} In this paper, we have provided two major contributions: we have reverse-engineered several system features of the IRIDIUM satellite constellation, and we have proposed a new solution to detect GNSS spoofing attacks--- combining the cited features with the publicly available \acl{IRA} messages. We have provided an efficient and effective location verification algorithm, independent from GNSS technology, that can be used to verify the actual position computed from standard GNSS technologies. Overall, our solution is worldwide-available, cheap, non-invasive, and it does not require either information from the radio physical-layer or multiple antennas. Therefore, it is particularly suitable for unattended scenarios, where there are no other entities that can help to verify the actual position of the receiver. These scenarios include deserts, poles, and open seas, to name a few. The data have been obtained thanks to an extensive measurement campaign lasting over $1000$ hours, and they have been also made public to foster research in this challenging field. Our future work will focus on the characterization of the power-law obeying phenomena highlighted by our experimental campaign, to improve the accuracy of the location verification scheme, as well as to analyze the time-correlation among false-positive events to declare a GNSS spoofing attack. We will also collect further measurements data, using newly acquired dedicated equipment, such as powerful IRIDIUM-compliant L-band antennas. \section*{Acknowledgements} This publication was partially supported by awards NPRP-S-11-0109-180242, NPRP12S-0125-190013, and NPRP X-063-1-014 from the QNRF-Qatar National Research Fund, a member of The Qatar Foundation. The information and views set out in this publication are those of the authors and do not necessarily reflect the official opinion of the QNRF. \bibliographystyle{ACM-Reference-Format} \balance
{'timestamp': '2020-06-19T02:09:12', 'yymm': '2006', 'arxiv_id': '2006.10284', 'language': 'en', 'url': 'https://arxiv.org/abs/2006.10284'}
arxiv
\section{Introduction} The Coronavirus 2019 (COVID-19) pandemic has significantly changed the way people live and work. Many people have been forced to work from home through telecommuting, potentially affecting their productivity. We study how this pandemic shock affected academics' research productivity using data from the world's largest open-access repository for social science---the Social Science Research Network (SSRN).\footnote{Source:\url{https://en.wikipedia.org/wiki/Social\_Science\_Research\_Network}, accessed June 2020.} We provide evidence that, as a result of the lockdown in the United States, female researchers' productivity dropped significantly relative to that of male researchers. In response to the pandemic, the US and many other countries required their citizens to stay at home. As a result of the lockdown, many people have had to perform work duties at home along with household duties. Most countries have also closed schools and daycare centers, massively increasing childcare needs. With the childcare provided by grandparents and friends limited due to the social distancing protocol, parents must care for their children themselves. In addition, restaurants have been either closed or do not allow dine-ins, which has increased the need for food preparation at home. Given that women, on average, carry out disproportionately more childcare, domestic labor, and household responsibilities \citep{bianchi2012housework}, they are likely to be more affected than men by the lockdown. The lockdown has also disrupted how academics carry out their activities. Many countries have closed their universities, so faculty have to teach and conduct research from home. A researcher's productivity is jointly determined by his or her available time for research and research efficiency \citep{kc2020handbook}. First, given the unequal distribution of domestic duties, the pandemic is more likely to burden female researchers with more home-related tasks, leaving them less time to dedicate to research. Second, scientific research generally requires a quiet and interruption-free environment. As a result of the pandemic, female researchers are more likely to multitask between research and home-related tasks and thus to have lower efficiency in conducting research. Together, these factors suggest that female academics' productivity is likely to be disproportionately affected compared with that of male academics. \begin{comment} \footnote{ Women spend almost twice as much time on housework and childcare in the US \citep{bianchi2012housework}. There are 8.5 million more single mothers than single fathers in the US \citep{alon2020impact}. Even in the gender-egalitarian countries of northern Europe, women do almost two-thirds of the unpaid work \citep{EUwomenunpaid}. Among heterosexual couples with female breadwinners, women still do most of the care work \citep{chesley2017signs}. The same pattern exists in the academia \citep{schiebinger2010housework,andersen2020meta}. Women professors spend more time doing housework and carework than men professors across various ranks, for example, 34.1 hours versus 27.6 hours per week for lecturers, 29.6 hours versus 25.1 hours per week for assistant professors, and 37.7 hours versus 24.5 hours per week for associate professors \citep{misra2012gender}.} \end{comment} Anecdotal evidence provides mixed support for this prediction \citep{AJPSSubmission}. A recent survey involving 4,500 principal investigators reported significant and heterogeneous declines in the time they spend on research \citep{myers2020unequal}. Several journal editors have noticed that, while there was a 20--30-percent increase in submissions after the pandemic started, most was from male academics \citep{reserachlab}. \cite{whoresearch} find a particularly large number of senior male economists, rather than mid-career economists, exploring research questions arising from the COVID-19 shock. Others have seen no change or have been receiving comparatively more submissions from women since the lockdown \citep{TheLily}. Overall, there is a dearth of systematic evidence on whether and to what extent the shock has affected gender inequality in academia. We provide such systematic evidence, showing an unequal impact on productivity for female and male researchers. It is an important operations and societal question to understand the change in productivity and the related gender equity caused by the reorganization of work and care at home. In this paper, we use a large dataset on female and male academics' production of new research papers to systematically study whether COVID-19 and the subsequent lockdown have had a disproportionate effect on female academics' productivity. We also identify the academic ranks, universities, and countries in which this inequality is intensified. We collect data on all research papers uploaded to SSRN in 18 disciplines from December 2018 to May 2019 and from December 2019 to May 2020. We extract information on paper titles and the authors' names, affiliations, and addresses, which we use to identify the authors' countries and academic ranks, and the ranking of their institutions. We also use their names and faculty webpages to identify their gender. In particular, we use a large database to predict authors' gender. For author names with a prediction confidence level lower than 80 percent, we use Amazon Mechanical Turk to identify gender manually. The final dataset includes 41,858 papers written by 76,832 authors from 25 countries. Our main analysis focuses on US academics; we then perform the same analysis for other countries. We use a difference-in-differences (DID) approach to estimate the effect. We compute the number of papers produced by female and male academics in each week, then compare the variations in the productivity gap between genders before and after the start of the lockdown and show that the gap increased after the start of the lockdown. We also validate that female and male authors' preprint volumes followed the same parallel time trend before the lockdown and that there was no significant change in the research productivity gap in 2019 during the same time of year. Taken together, these results suggest that the intensified disparity has primarily been driven by the pandemic shock. We find that during the 10 weeks since the lockdown began in the US, female academics' research productivity dropped by 13.2 percent compared to that of male academics. The effect persists when we vary the time window since the pandemic outbreak. Our findings show that when female and male academics face a reorganization of care and work time, women become significantly less productive by producing fewer papers. We also find that the quality of their uploaded papers, measured by the download and view rates, does not change. Finally, we find that the effect is more pronounced among assistant professors and among researchers in top-ranked research universities and that it exists in six other countries. While gender inequality has been long documented for academics in terms of tenure evaluation \citep{antecol2018equal}, coauthoring choices \citep{sarsons2017recognition}, and number of citations \citep{ghiasi2015compliance}, the COVID-19 pandemic brings this issue to the forefront. Our study is among the first to rigorously quantify such inequality in research productivity as a result of the pandemic and our results highlight that this disruption has exacerbated gender inequality in the academic world. Because all academics participate together in open competition for promotions and positions, these short-term changes in productivity will affect their long-term career outcomes \citep{pendamicandfemale}. Thus, institutions should take this inequality into consideration when evaluating faculty members. Our paper contributes to the literature on productivity, a central topic in operations management. Previous studies have examined key determinants of workers' productivity, such as workers' capacity \citep{tan2014does,kc2020handbook}, multitasking \citep{kc2014multi,bray2016multitasking,kc2020heuristic}, peer effects \citep{song2018closing,tan2019you}, and task sequences \citep{ibanez2018discretionary}. We contribute to the literature by showing that the disruption due to the pandemic has significantly enlarged the productivity gap between female and male researchers, highlighting fairness as an important factor in performance evaluation. Our work also sheds light on the fairness issues that could arise from telecommuting, an operations choice faced by companies. Since working from home can provide a flexible work schedule for employees and reduce office-related costs for companies, an increasing number of companies are choosing this operating model. Between 2005 and 2015, the number of US employees who chose to telecommute increased by 115\% \citep{2005-2015-115}. By 2019, about 16\% of the total workforce in the US was working remotely full time or part time \citep{us-remote16}. During the pandemic, telecommuting is a constraint rather than a choice; many companies were forced to allow telecommuting. But going forward, an increasing number of companies may choose to offer this operating model to provide flexible work schedule to employees and reduce office-related costs. For example, Twitter and Facebook have already announced that their employees could work from home permanently \citep{facebook-twitter} and JP Morgan planned to expand its telecommuting program \citep{jpmorgan}. Despite the growing popularity of telecommuting, scholars and practitioners still lack a comprehensive understanding of the managerial and societal impact of this operational choice \citep{nicklin2016telecommuting}. We contribute to the literature by pointing out the productivity inequality caused by the lockdown and telecommuting, which might lead to a longer-term unemployment risk for women, an unintended consequence that companies and society should take into account when making their operational choices or designing policies for performance evaluation. Our findings help institutions and firms understand the potential implications in designing and implementing telecommuting. \section{Literature Review} Our work is closely related to three streams of literature: productivity, social operations, and telecommuting. \subsection{Productivity} According to the productivity literature \citep{kc2009impact,tan2014does}, working in different environments causes significant changes in operational factors that drive worker's productivity. In our context, due to the pandemic, researchers have to change to working from home, potentially affecting several drivers of productivity identified by research, such as multitasking, workload, task sequence, and peer effects. Multitasking is particularly relevant to our research context. When working from home during the pandemic, researchers may need to allocate their limited cognitive capacity across home-related and work-related tasks, thus dealing with more distractions arising from multitasking. Prior studies have shown mixed effects of multitasking on workers' productivity, such as an increased service speed with a lower service quality for restaurant waiters \citep{tan2014does} and a slower processing for bank associates \citep{staats2012specialization}. The productivity losses could be greater for jobs requiring greater cognitive capacity. For example, in the judiciary system, reducing multitasking has been shown to help judges focus on the most recent cases, reduce the switching costs between cases, and increase the case completion rate \citep{bray2016multitasking}. In healthcare, excessive multitasking and frequent interruptions in the work flow have been shown to undermine the productivity of discharging \citep{kc2014multi}, processing \citep{berry2017past}, and medication delivery \citep{batt2017early}. Workload, task sequences, and peer effects are examples of other operations drivers in researchers' productivity during the pandemic. Workers have been shown to adjust their productivity based on their workload, slowing down when facing more workload and speeding up when facing less because they internalize the congestion cost \citep{kc2009impact,tan2014does}. However, the extra workload could make workers fatigued, which could reduce productivity \citep{salvendy2012handbook, kc2020handbook}. Technology---such as tabletop technology in restaurants---has been shown to improve workers' productivity by reducing their non-value-added tasks, enabling them to focus on more important tasks \citep{tan2020tabletop}. The literature has also identified workers' choice of task sequence as a productivity factor \citep{staats2012specialization,ibanez2018discretionary}. Workers tend to deviate to suboptimal task sequences when facing a higher workload or when fatigued \citep{KC2020task}. Another driver of workers' productivity is peer effects---workers adapt their own productivity to that of their peers' \citep{schultz1998modeling}. For example, having a particularly capable worker on a shift could motivate slower workers to speed up but could also discourage good performers as it becomes more difficult for them to outperform their peers and reach their goals \citep{tan2019you}. Displaying peers' productivity publicly has been shown to improve productivity \citep{song2018closing}. \subsection{Social Operations} This paper sheds light on a key social issue---fairness and equity---in research productivity, adding to the growing literature on the social impact of operational choices. Several recent influential papers by \cite{tang2012research}, \cite{lee2018socially}, and \cite{dai2020twenty} encourage OM researchers to work on socially responsible topics that are important to corporations and to society at large. Papers have examined the use of review information to reduce racial discrimination arising in the sharing economy \citep{cui2020reducing,mejia2020transparency} and the gender inequality driven by specific compensation schemes \citep{pierce2020peer}. The literature on gender bias has shown evidence that female researchers and students tend to be discredited when they are evaluated alongside equally competent male candidates \citep{moss2012science,sarsons2017recognition}, that women are more likely to be assigned more service-oriented and less desirable tasks \citep{guarino2017faculty} with fewer promotion opportunities \citep{babcock2017gender}, and that women are often responsible for more housework and childcare \citep{schiebinger2010housework,misra2012gender}. In our context, when working from home, the unequal distribution of housework means that women are more likely to deal with non-work-related tasks during the lockdown and lose productivity. A recent survey involving 4,500 principal investigators shows that female scientists self-reported a sharper reduction in research time during the lockdown, primarily due to childcare needs \citep{myers2020unequal}. We contribute to the literature by providing evidence that the lockdown affects productivity and exacerbates gender inequity in the workplace, potentially leading to a long-term career risk for women, an unintended consequence that organizations should consider when designing their operations models and performance evaluation policies. \subsection{Telecommuting} Our work is also related to the emerging literature on organizations' telecommuting choices. Transitioning from traditional in-office work to telecommuting might affect workers' behavior and productivity through team-work and peer effects. For example, \cite{dutcher2012does} observe that workers do not indulge in free-riding behavior when a team is made up of in-office workers and telecommuters, and \cite{bloom2015does} demonstrates that telecommuting can improve productivity when it is carried out in a quiet environment. Our work adds to this stream of literature by demonstrating an unexpected social issue of fairness arising from this operating model. \section{Theory Development} A researcher's productivity can be measured as the product of the amount of time he or she can dedicate to research, \textit{Time Available for Research}, and how efficiently he or she conducts research, \textit{Research Efficiency.} This definition is consistent with the key insights from the literature that productivity is determined by two elements: (1) the capacity constraint due to physical or cognitive limitations and (2) efficiency variations with changes in operations factors in the working environment \citep{kc2020handbook}. For many researchers, the outbreak of COVID-19 has affected their productivity both in terms of time available for research and research efficiency. In response to the pandemic, most countries have closed schools and daycare centers and required that their citizens to be quarantined at home. As a result, researchers from more than 1,100 colleges and universities had to carry out both work and household duties at home \citep{shutdown2020}. We next illustrate how the disruptions change researchers' time available for research and research efficiency separately. We then argue how these changes might be unequal among female and male researchers. The pandemic changes researchers' working environment, resulting in a need to reallocate their time across research, work-related tasks (such as commuting, social interaction, and service to the academic community), and home-related tasks (such as childcare and house chores). Certain tasks have an in-person nature, such as commuting to the office, serving administrative duties, and interacting socially with colleagues. These tasks are significantly reduced during the lockdown and the time savings could be substantial; for example, workers in the US on average spend an hour commuting each work day \citep{commuting_time}. During the pandemic, researchers could use this additional capacity for research. At the same time, they might have to allocate more time to home-related tasks. Even without the pandemic, working from home constantly exposes researchers to the home environment and home duties. During the lockdown, to make matters worse, many services and amenities such as schools, day-care centers, hospitals, and restaurants have either been closed or operating at a lower capacity. Researchers might need to allocate extra time to domestic duties. For example, childcare could be particularly time-demanding since parents have diminished access to their regular childcare support network, such as professional caregivers, relatives, and friends. Consequently, researchers who are responsible for more house works and childcare are more likely to allocate additional time to domestic duties. In conclusion, a researcher could have either more or less time available due to the pandemic, which depends on the new allocation of home responsibilities. Besides the time available for research, the pandemic affects drivers of research efficiency, such as multitasking, task sequence, fatigue, and peer effects. Conducting scientific work often requires hours of interruption-free environment. When working from home, although researchers are not distracted by activities like commuting, administrative duties, and social interactions with colleagues, they are likely to be distracted by childcare and housework, resulting in excessive multitasking. Multitasking means that workers have to allocate their limited cognitive capacity across multiple tasks. The setup cost associated with switching between tasks and the difficulty of focusing on and organizing relevant information hinder efficiency \citep{kc2014multi}. Multitasking has also been shown to induce stress and frustration \citep{mark2008cost}, make people more easily distracted \citep{levitin2014organized}, and exhaust their cognitive capacity \citep{kc2014multi}. Home duties and urgency often require researchers' immediate attention, forcing them to deviate from their optimal task sequences, which would in turn reduce their research efficiency. Researchers may also encounter a heavier workload from increased housework and thus experience fatigue, which could also reduce efficiency. Last but not least, working from home makes it difficult to observe one's colleagues’ productivity and to discuss research topics with their peers, both of which reduce the positive influence of peers in motivating researchers, inspiring research ideas, and improving efficiency \citep{song2018closing,tan2019you}. In conclusion, a researcher's research efficiency could go up and down due to the pandemic, depending on the level of impact they get from multitasking, fatigue, altered task sequence, and altered peer effects. We next demonstrate how the changes in research time and efficiency can be different for women and men. Women are on average, disproportionately burdened with childcare and household responsibilities \citep{bianchi2012housework}. In the US, they are shown to spend almost twice as much time as men on housework and childcare in the US \citep{bianchi2012housework}. Moreover, there are 8.5 million more single mothers than single fathers \citep{alon2020impact}. Even in the gender-egalitarian countries of northern Europe, women are responsible for almost two-thirds of the unpaid work \citep{EUwomenunpaid}. Among heterosexual couples with female breadwinners, women still do most of the care work \citep{chesley2017signs}. The same pattern exists in academia \citep{schiebinger2010housework,andersen2020meta}. Female professors are shown to spend more time doing housework and carework than male professors across various ranks; for example, 34.1 hours per week versus 27.6 hours for lecturers, 29.6 hours per week versus 25.1 hours for assistant professors, and 37.7 hours per week versus 24.5 hours for associate professors \citep{misra2012gender}. The lockdown has caused a surge in domestic duties. The unequal distribution of domestic duties means that the pandemic might further enlarge the gap between women and men's domestic workload and thus might affect female and male researchers' productivity unequally. First, in terms of time available for research, female researchers are likely to reallocate more time to domestic duties due to the pandemic than male researchers do, leaving them with less capacity for research. Second, in terms of efficiency, female researchers are more likely to be disrupted by multitasking between research and home-related tasks and consequently deviate from their optimal task sequences. Taken these factors together, female researchers tend to suffer more from a reduced amount of time available for research and diminished efficiency compared to male researchers, which suggests a disadvantage in women's productivity during the pandemic. We therefore hypothesize that, during the pandemic, female researchers are more likely to be disproportionately affected in their productivity compared with male researchers. \section{Data and Summary Statistics} We collect data from the Social Science Research Network (SSRN), a repository of preprints with the objective of rapidly disseminating scholarly research in social science. We gather data on \emph{all} social science preprints submitted from December 2018 to May 2019 and from December 2019 to May 2020. We extract information on paper titles and the authors' names, affiliations, and addresses. We use the authors' addresses to identify their countries. The COVID-19 outbreak began at different times in different countries, so we collect each country's lockdown start date from news sources and a United Nations report.\footnote{Source:\url{https://en.unesco.org/covid19/educationresponse}, accessed June 2020.} We drop authors without addresses or with addresses in more than one country because we cannot determine when these authors were affected by the lockdown. We also drop countries with fewer than 800 submissions during our study period. The final data set consists of a total of 41,858 papers in 18 disciplines produced by 76,832 authors from 25 countries. To identify the authors' genders, we first use a database called \textit{Genderize},\footnote{Source:\url{https://genderize.io/}, accessed June 2020.} which predicts gender based on first name and provides a confidence level. About 78 percent of the authors' genders were identified with confidence levels over 80 percent. For the remaining authors, we use Amazon Mechanical Turk to manually search for their professional webpages based on names and affiliations and then infer their genders from their profile photos. Our dataset contains 21,733 female academics and 55,099 male academics. We aggregate the number of new preprints at the weekly level. We then count the number of papers uploaded by each author in each week. To measure the \emph{effective} productivity for preprints with multiple authors, when a preprint has $n$ authors,\footnote{Note that in many social science disciplines, author names are listed in alphabetical order.} each author gets a publication count of $1/n$.\footnote{Note that the validity of this measure relies on the assumption that female and male researchers' relative contributions to the paper do not change significantly after the lockdown. If female researchers have decreased their contributions to the teamwork since the lockdown, this measure would underestimate gender inequality during the pandemic. In Section~7.4, we study \textit{all-male} and \textit{all-female} preprints as an alternative measure, which minimizes potential work shifting across genders.} Finally, we aggregate the effective number of papers to the gender level: in each week, we count the total number of papers produced by male and female authors separately in each social science discipline. Figure \ref{fig:trend2020} plots the time trend of preprints in aggregation from December 3, 2019 to May 19, 2020 in the US. The vertical line represents the week of March 11, 2020, on which nationwide lockdown measures began in the US.\footnote{Most universities were closed in the week of March 11, 2020. Source: \url{https://gist.github.com/jessejanderson/09155afe313914498a32baa477584fae?from=singlemessage&isappinstalled=0}, accessed June 2020.} We can observe that male academics, on average, have submitted more preprints than female academics, and that female and male academics' research productivity evolved in parallel before the lockdown. After the lockdown started, however, male academics significantly boosted their productivity, whereas female academics' productivity did not change much, indicating an increased productivity gap. \begin{figure}[h] \caption{Time Trends of US Preprints from December 2019 to May 2020} \label{fig:trend2020} \vspace{0.05in} \centering \includegraphics[scale=0.38]{trend2020.png} \vspace{0.05in} \noindent \scriptsize This graph plots the time trend of the number of preprints for female and male academics. The vertical line represents the start of the lockdown due to COVID-19 in the US. \end{figure} To ensure that our results are not driven by seasonality, we plot the time trend of preprints during the same time window in 2019 in Appendix Figure \ref{fig:trend2019}. We observe a similar pattern before the week of March 11, 2019, but there is no significant change in the productivity gap after that week. We use authors' professional information to identify academic ranks (e.g., PhD student or assistant, associate or full professor). Specifically, we ask workers on Amazon Mechanical Turk to find each researcher's curriculum vitae or professional webpage. To study how the pandemic affects researchers with different academic ranks, we categorize researchers into \textit{students} (which includes PhD and postdoctoral students), \textit{assistant professors}, \textit{associate professors}, and \textit{full professors}, each accounting for 20.3 percent, 16.1 percent, 19.7 percent, and 44.0 percent of the population, respectively. Next, we use authors' affiliations to classify the ranking of their universities. To ascertain whether the productivity gap is intensified or weakened across top-ranked and lower-ranked research universities, we collect social science research rankings from three sources: QS University Ranking,\footnote{Source:\url{https://www.topuniversities.com/university-rankings/university-subject-rankings/2020/social-sciences-management}, accessed June 2020.} Times Higher Education,\footnote{Source:\url{https://www.timeshighereducation.com/world-university-rankings/2020/subject-ranking/social-sciences\#!/page/0/length/25/sort_by/rank/sort_order/asc/cols/stats}, accessed June 2020.} and Academic Ranking of World University.\footnote{Source:\url{http://www.shanghairanking.com/FieldSOC2016.html}, accessed June 2020.} We then use these data to rank US universities in order to study the heterogeneous effects across university rankings. Table~\ref{table:statistics} reports the summary statistics for the weekly number of preprints by gender and discipline from December 3, 2019 to May 19, 2020, spanning 24 weeks, as well as split-sample statistics prior to or after the lockdown. This sample includes 9,943 preprints produced by 15,494 authors in the US and 21,065 preprints produced by 37,997 authors across all countries. The average number of submissions per week is 444.6 in the US and 877.7 across all 25 countries. Notably, while research productivity in the US increased by 35 percent after the lockdown, male authors seem to be the main contributors to this increase. About 78 percent of the preprints fall under multiple disciplines.\footnote{Authors self-classify their own preprints into disciplines when they upload their papers. SSRN reviews and approves these classifications.} Note that when computing the total preprints, we count the paper only once when aggregating across disciplines to avoid multiple counting. When computing the number of preprints in each discipline, we separately count all of the papers classified under each one. We observe substantial variations across disciplines. Among the 18 disciplines, Political Science, Economics, and Law received the most submissions, whereas Geography, Criminal Justice and Education the fewest. While there was a large increase in productivity in several disciplines, such as Economics, Political Science, Finance, Health Economics, and Sustainability, after the COVID-19 outbreak, other disciplines showed no obvious increase. A few disciplines, such as Anthropology, Cognitive, and Information Systems, even experienced a decline. \begin{table}[h]\centering \scriptsize \caption{Summary Statistics} \label{table:statistics} \begin{threeparttable} \begin{tabular}{C{1.4cm} l*{9}{S[table-format=4.2, table-number-alignment=center]}} \toprule & & \multicolumn{5}{c}{All observations} & \multicolumn{2}{c}{Before lockdown} & \multicolumn{2}{c}{After lockdown} \\ \cmidrule(lr){3-7} \cmidrule(lr){8-9} \cmidrule(lr){10-11} Level & \centering{Weekly No. of Preprints} & {Mean} & {Std. dev} & {Max} & {Min} & {Total} & {Mean} & {Std. dev} & {Mean} & {Std. dev} \\ \midrule \multirow{3}{1.4cm}{\centering All Disciplines (US only)} & All & 444.6 & 109.4 & 617 & 224 & {9,934} & 378.8 & 88.0 & 511.4 & 86.0 \\ & Female authors & 111.3 & 30.8 & 186 & 47 & {2,493} & 103.4 & 36.2 & 119.3 & 21.4 \\ & Male authors & 333.3 & 85.3 & 480 & 161 & {7,441} & 275.4 & 55.4 & 392.1 & 68.6\\ \hline \\[-1.8ex] \multirow{18}{1.4cm}{\centering By Discipline (US only)} & Accounting & 19.5 & 7.2 & 40 & 9 & {468} & 17.9 & 6.3 & 21.8 & 8.2 \\ & Anthropology & 85.0 & 21.5 & 141 & 63 & {2,040} & 93.9 & 24.0 & 72.5 & 6.9\\ & Cognitive & 11.3 & 9.2 & 31 & 1 & {271} & 14.1 & 11.1 & 7.4 & 3.2 \\ & Corporate & 14.1 & 6.5 & 27 & 3 & {339} & 12.2 & 6.5 & 16.8 & 5.8 \\ & Criminal & 15.4 & 6.7 & 27 & 4 & {370} & 12.8 & 6.7 & 19.1 & 4.9 \\ & Economics & 133.2 & 54.2 & 237 & 37 & {3,197} & 106.6 & 39.1 & 170.5 & 51.6 \\ & Education & 17.9 & 7.0 & 36 & 7 & {429} & 16.9 & 7.4 & 19.2 & 6.7 \\ & Entrepreneurship & 9.9 & 5.3 & 22 & 2 & {238} & 10.2 & 4.9 & 9.5 & 5.9 \\ & Finance & 91.7 & 34.5 & 139 & 25 & {2,201} & 78.5 & 35.5 & 110.2 & 24.0 \\ & Geography & 8.2 & 3.3 & 17 & 3 & {196} & 7.5 & 2.7 & 9.1 & 4.0 \\ & Health Economics & 8.4 & 10.1 & 47 & 0 & {202} & 3.0 & 2.1 & 16.0 & 12.1 \\ & Information Systems & 15.6 & 7.3 & 39 & 7 & {374} & 17.4 & 8.6 & 13.1 & 4.2 \\ & Law & 98.5 & 24.3 & 142 & 44 & {2,365} & 94.1 & 26.7 & 104.7 & 20.1 \\ & Management & 33.4 & 11.4 & 56 & 12 & {802} & 33.4 & 13.3 & 33.4 & 8.6 \\ & Organization & 20.5 & 11.5 & 44 & 3 & {491} & 16.9 & 10.2 & 25.5 & 11.7 \\ & Political Science & 167.9 & 50.5 & 255 & 85 & {4,030} & 142.1 & 39.0 & 204.1 & 42.8 \\ & Sustainability & 22.8 & 11.9 & 66 & 8 & {546} & 18.1 & 5.9 & 29.3 & 15.1 \\ & Women/Gender & 18.0 & 4.7 & 28 & 10 & {431} & 17.2 & 4.4 & 19.0 & 5.2 \\ \hline \\[-1.8ex] \multirow{3}{1.4cm}{\centering All countries} & All & 877.7 & 199.3 & {1,175} & 487 & {21,065} & 779.1 & 177.5 & 1015.8 & 140.4 \\ & Female authors & 246.5 & 53.9 & {347} & 165 & {5,916} & 231.0 & 57.0 & 268.2 & 42.9 \\ & Male authors & 631.2 & 152.0 & {866} & 322 & {15,149} & 548.1 & 124.4 & 747.6 & 104.3 \\ \bottomrule \end{tabular} \noindent The table summarizes the weekly number of papers from December 2019 to May 2020. The sample includes 15,494 authors from the United States and 37,997 authors across all countries. There are 9,934 preprints produced by US authors, 2,493 of which are produced by 3,877 female researchers and 7,441 by 11,617 male researchers. We gather the country-specific lockdown time to split our sample to before and after the lockdown for each country. \end{threeparttable} \end{table} \section{Identification} Our identification exploits the lockdown in response to the COVID-19 outbreak as an exogenous shock that has caused substantial disruption to academic activities, requiring academics to teach, conduct research, and carry out household duties at home. The validity of our approach depends on the assumption that the shock is exogenous with respect to the researchers' anticipated responses. If a particular gender group of researchers anticipated and strategically prepared for the shock by accelerating the completion of their research papers, this could confound the treatment effect. In reality, this possibility is unlikely because of the rapid development of the situation. COVID-19 was regarded as a low risk and not a threat to the US in late January \citep{fauci}, and no significant actions had been taken other than travel warnings issued until late February \citep{travelban}. It quickly turned into a global pandemic after the declaration of the World Health Organization on March 11, 2020, followed by the nationwide shelter-in-place orders within a week.\footnote{Source:\url{https://www.cdc.gov/nchs/data/icd/Announcement-New-ICD-code-for-coronavirus-3-18-2020.pdf}, accessed June 2020.} We adopt the difference-in-differences (DID) methodology, a common approach used to evaluate people's or organizations' responses to natural shocks \citep[e.g.,][]{seamans2013responses,wagner2018disclosing}. We perform the DID analysis using outcome variables on two levels: the number of preprints in each discipline and the number of preprints aggregated across all disciplines.\footnote{We also perform a DID analysis with the country-level panel data. For this, we assign a lockdown dummy to each country and combine data across countries to form a country-level panel. This analysis yields consistent results.} We compare the productivity gap between female and male researchers before and after the pandemic outbreak using the following model specification with discipline-level panel data: \begin{equation}\label{eq:did_discipline} log(Preprints_{igt}) = c + Female_{g} + \beta Female_{g}\times Lockdown_{t} + \gamma_t + \delta_i + \epsilon_{igt}, \end{equation} where $i$ denotes discipline, $g$ denotes the gender group, $t$ denotes the week, $log(Preprints_{igt})$ represents the logged number of preprints uploaded for discipline $i$ for gender $g$ during week $t$, $\gamma_t$ is the time fixed effect, $\delta_i$ is the discipline fixed effect that captures the time-invariant characteristics of discipline $i$, and $\epsilon_{igt}$ is the error term. The time fixed effect $\gamma_t$ includes weekly time dummies that control for time trends. The dummy variable $Female_g$ equals 1 if gender $g$ is female, and 0 otherwise. The dummy variable $Lockdown_{t}$ equals 1 if week $t$ occurs after the lockdown measure was adopted (that is, the week of March 11, 2020), and 0 otherwise. Its main effect is absorbed by the time fixed effects. The coefficient $\beta$ estimates the effect of the lockdown on female academics' research productivity relative to male academics’ productivity. We also use aggregate-level data to estimate the effect with the following DID specification: \begin{equation}\label{eq:did} log(Preprints_{gt}) = c + Female_{g} + \beta Female_{g} \times Lockdown_{t} + \gamma_t + \epsilon_{gt}, \end{equation} where $g$ denotes the gender group, $t$ denotes the week, $log(Preprints_{gt})$ represents the logged number of preprints uploaded for gender $g$ during week $t$, and $\epsilon_{t}$ is the error term. As before, we include the time fixed effect $\gamma_t$. \section{Empirical Results} In this section, we report the effect of the COVID-19 outbreak on research productivity. We first show the average effect of the pandemic on gender inequality. We then show the heterogeneous effects across academic disciplines, faculty ranks, university rankings, and countries. \subsection{Main Results} Table~\ref{table:did_discipline} reports the estimates with the discipline fixed effect using Equation~(\ref{eq:did_discipline}). Table~\ref{table:did_aggregated} reports the estimated effect of the pandemic shock on research productivity at the aggregate level using Equation~(\ref{eq:did}). In each analysis, we use 14 weeks before the lockdown as the pre-treatment period and 6 to 10 weeks after the lockdown as the post-treatment periods. The analyses yield consistent results. First, in line with our summary statistics, the results show that fewer preprints are produced by female academics than by male academics in general. Second, since the lockdown began, there has been a significant reduction in female academics' productivity relative to that of their male colleagues, indicating an exacerbated productivity gap in gender. The coefficient of the interaction term in Column (5) suggests a 13.2-percent reduction in females' productivity over the 10-week period after the lockdown relative to the males'.\footnote{Because the outcome variable is logged, the percentage change in the outcome variable is computed as $e^{\text{coefficient}}-1$.} \renewcommand{\arraystretch}{1.1} \begin{table}[h] \centering \scriptsize \vspace{-0.1in} \caption{Impact of Lockdown on Gender Inequality with the Discipline Fixed Effect} \label{table:did_discipline} \begin{threeparttable} \begin{tabular}{ L{4cm} @{}c*{5}{S[table-format=-1.3,table-space-text-post=***,table-column-width=1.8cm]}@{}} \toprule & \multicolumn{5}{c}{Dependent variable: No. of Preprints (in logarithm) by discipline} \\ & {6 weeks} & {7 weeks} & {8 weeks} & {9 weeks} & {10 weeks} \\ {Variables} & {(1)} & {(2)} & {(3)} & {(4)} & {(5)} \\ \hline \\[-1.8ex] {$Female$} & $-$0.791*** & -0.791*** & -0.791*** & -0.791*** & -0.791*** \\ & {(0.042)} & {(0.042)} & {(0.042)} & {(0.042)} & {(0.042)} \\ {$Female \times Lockdown$} &$-$0.140* & -0.148** & -0.162** & -0.157** & -0.142** \\ & {(0.076)} & {(0.072)} & {(0.068)} & {(0.065)} & {(0.063)} \\ Discipline fixed effects & {Yes} & {Yes} & {Yes} & {Yes} & {Yes} \\ Time fixed effects & {Yes} & {Yes} & {Yes} & {Yes} & {Yes} \\ Observations & {720} & {756} & {792} & {828} & {864} \\ $R^{2}$ & 0.837 & 0.836 & 0.839 & 0.841 & 0.841 \\ \bottomrule \end{tabular} \noindent This table reports the estimated coefficients and robust standard errors (in parentheses) in Equation~\eqref{eq:did_discipline} with the discipline fixed effect. The coefficients for 6, 7, 8, 9, and 10 weeks since the lockdown are presented in Columns (1)--(5), respectively. Significance at $^{*}p<0.1$; $^{**}p<0.05$; $^{***}p < 0.01$. \end{threeparttable} \end{table} \renewcommand{\arraystretch}{1.1} \begin{table}[h] \centering \scriptsize \vspace{-0.1in} \caption{Impact of Lockdown on Gender Inequality in Aggregation} \label{table:did_aggregated} \begin{threeparttable} \begin{tabular}{L{4cm} @{}c*{5}{S[table-format=-1.3,table-space-text-post=***,table-column-width=1.8cm]}@{}} \toprule & \multicolumn{5}{c}{Dependent variable: No. of Preprints (in logarithm) in aggregation} \\ & {6 weeks} & {7 weeks} & {8 weeks} & {9 weeks} & {10 weeks} \\ {Variables} & {(1)} & {(2)} & {(3)} & {(4)} & {(5)} \\ \hline \\[-1.8ex] {$Female$} & $-$1.013*** & -1.013*** & -1.013*** & -1.013*** & -1.013*** \\ & {(0.054)} & {(0.054)} & {(0.053)} & {(0.053)} & {(0.053)} \\ {$Female \times Lockdown$} & $-$0.197** & -0.199*** & -0.173** & -0.159** & -0.150** \\ & {(0.068)} & {(0.064)} & {(0.067)} & {(0.066)} & {(0.064)} \\ {Time fixed effects} & {Yes} & {Yes} & {Yes} & {Yes} & {Yes} \\ Observations & {40} & {42} & {44} & {46} & {48} \\ $R^{2}$ & 0.981 & 0.982 & 0.982 & 0.982 & 0.983 \\ \bottomrule \end{tabular} \noindent This table reports the estimated coefficients and robust standard errors (in parentheses) in Equation~\eqref{eq:did} at the aggregation level. The coefficients for 6, 7, 8, 9, and 10 weeks since the lockdown are presented in Columns (1)--(5), respectively. Significance at $^{*}p<0.1$; $^{**}p<0.05$; $^{***}p < 0.01$. \end{threeparttable} \end{table} \subsection{Heterogeneous Effects} In this section, we study the heterogeneous effects across faculty ranks, university rankings, disciplines, and countries. \subsubsection{Effects across academic rank.} We study how the pandemic affects researchers with different academic ranks (such as PhD student, or assistant, associate or full professor). Because assistant professors often face more pressure than senior professors to publish papers in order to get tenure, they are more motivated to devote as much time as possible to research. They are also at a stage at which many have young children. As a result, the pandemic's effect on the productivity gap is likely to be more pronounced for this group. We repeat the DID analysis for each academic rank and report results based on Equations~\eqref{eq:did_discipline} and~\eqref{eq:did} in Table~\ref{table:rank_discipline} and Table~\ref{table:rank_aggregated}, respectively. The two tables show consistent results. Table~\ref{table:rank_discipline} shows that female assistant professors experienced the most significant drop in research productivity (compared to male junior faculty) since the lockdown. \renewcommand{\arraystretch}{1.1} \begin{table}[h] \centering \scriptsize \vspace{-0.1in} \caption{Impact of Lockdown on Gender Inequality by Academic Ranks} \label{table:rank_discipline} \begin{threeparttable} \begin{tabular}{ @{}l*{5}{S[table-format=-1.3,table-space-text-post=***,table-column-width=1.9cm]}@{}} \toprule & \multicolumn{5}{c}{Dependent variable: No. of Preprints (in logarithm) by discipline} \\ & {6 weeks} & {7 weeks} & {8 weeks} & {9 weeks} & {10 weeks} \\ {Academic rank} & {(1)} & {(2)} & {(3)} & {(4)} & {(5)} \\ \hline \\[-1.8ex] Student & -0.002 & -0.016 & -0.014 & -0.038 & -0.071 \\ Assistant professor & -0.529*** & -0.419*** & -0.448*** & -0.419*** & -0.441*** \\ Associate professor & 0.038 & -0.026 & 0.004 & -0.044 & -0.034 \\ Full professor & -0.181 & -0.163 & -0.063 & -0.044 & -0.064 \\ Observations & {720} & {756} & {792} & {828} & {864} \\ \bottomrule \end{tabular} \noindent This table reports the estimated coefficients based on Equation~\eqref{eq:did_discipline} with the discipline fixed effect for academics within each rank. The coefficients for 6, 7, 8, 9, and 10 weeks since the lockdown are presented in Columns (1)--(5), respectively. Time and discipline fixed effects at the weekly level are included in each regression. Standard errors and estimates of other variables are omitted for brevity. Significance at $^{*}p<0.1$; $^{**}p<0.05$; $^{***}p < 0.01$. \end{threeparttable} \end{table} \subsubsection{Effects across university ranking.} Table~\ref{table:ranking} replicates the DID analysis using Equation~(\ref{eq:did_discipline}) for a subset of academics based on the rankings of their universities.\footnote{For authors affiliated with more than one academic institutions, we use the highest-ranked institution.} Due to our focus on social science, we use the 2020 QS World University Ranking for social sciences and management for the main analysis. We separately analyze academics in universities ranked in the top 10, 20,..., and 100. The results show that the COVID-19 effect is more pronounced in top-tier universities and that this effect in general decreases and becomes less significant as we include more lower-ranked universities. We find similar results when using the two other rankings, as shown in Appendix Table~\ref{table:rankingrobust}. \renewcommand{\arraystretch}{1.1} \begin{table}[h] \centering \scriptsize \vspace{-0.1in} \caption{Impact of Lockdown on Gender Inequality by University Ranking} \label{table:ranking} \begin{threeparttable} \begin{tabular}{ @{}l*{5}{S[table-format=-1.3,table-space-text-post=***,table-column-width=1.8cm]}@{}} \toprule & \multicolumn{5}{c}{Dependent variable: No. of Preprints (in logarithm) by discipline} \\ {Universities} & {6 weeks} & {7 weeks} & {8 weeks} & {9 weeks} & {10 weeks} \\ {by QS Ranking} & {(1)} & {(2)} & {(3)} & {(4)} & {(5)} \\ \hline \\[-1.8ex] Top 10 & -0.169** & -0.199*** & -0.158** & -0.153** & -0.165** \\ Top 20 & -0.181** & -0.215*** & -0.183** & -0.179*** & -0.183*** \\ Top 30 & -0.189** & -0.210** & -0.167** & -0.168** & -0.170** \\ Top 40 & -0.218*** & -0.238*** & -0.200*** & -0.191*** & -0.194*** \\ Top 50 & -0.197** & -0.214*** & -0.180*** & -0.179*** & -0.182*** \\ Top 60 & -0.138* & -0.163* & -0.145* & -0.143** & -0.155** \\ Top 70 & -0.142* & -0.155* & -0.132* & -0.122* & -0.127* \\ Top 80 & -0.139* & -0.149** & -0.130* & -0.123* & -0.126* \\ Top 90 & -0.118 & -0.124* & -0.101 & -0.097 & -0.097 \\ Top 100 & -0.100 & -0.102 & -0.083 & -0.082 & -0.090 \\ Observations & {720} & {756} & {792} & {828} & {864} \\ \bottomrule \end{tabular} \noindent This table reports the estimated coefficients based on Equation~\eqref{eq:did} at the aggregate level for universities within each rank group. The coefficients for 6, 7, 8, 9, and 10 weeks since the lockdown are presented in Columns (1)--(5), respectively. Time fixed effects at the weekly level are included in each regression. Standard errors and estimates of other variables are omitted for brevity. Significance at $^{*}p<0.1$; $^{**}p<0.05$; $^{***}p < 0.01$. \end{threeparttable} \end{table} As junior faculty, researchers in higher-ranked universities often face more pressure to publish papers in order to get tenure and therefore devote more time to research. The constraint caused by the pandemic therefore has a bigger impact on researchers from top-tier universities, resulting in a greater gender inequality among them. \begin{comment} \subsubsection{Effects across disciplines.} We repeat the analysis using Equation~\eqref{eq:did} for each discipline separately. Table~\ref{table:discipline} reports the coefficients of the interacted term, $Female_{g} \times Lockdown_{t}$, for each discipline. We find that the gender differences significantly intensified in several disciplines; namely, Criminal, Economics, Finance, Health Economics, Political Science, and Sustainability. We conjecture that one of the drivers of inequality variations across disciplines could be the different levels of tenure pressure faced by professors in each discipline. \renewcommand{\arraystretch}{1.1} \begin{table}[h] \centering \scriptsize \vspace{-0.1in} \caption{Impact of Lockdown on Gender Inequality in Each Discipline} \label{table:discipline} \begin{threeparttable} \begin{tabular}{ @{}l*{5}{S[table-format=-1.3,table-space-text-post=***,table-column-width=1.8cm]}@{}} \toprule & \multicolumn{5}{c}{Dependent variable: No. of Preprints (in logarithm) by discipline} \\ & {6 weeks} & {7 weeks} & {8 weeks} & {9 weeks} & {10 weeks} \\ {Discipline} & {(1)} & {(2)} & {(3)} & {(4)} & {(5)} \\ \hline \\[-1.8ex] Accounting & -0.282 & -0.311* & -0.248 & -0.213 & -0.192 \\ Anthropology & -0.015 & 0.049 & 0.123 & 0.112 & 0.127 \\ Cognitive & -0.184 & -0.091 & -0.166 & -0.200 & -0.131 \\ Corporate & -0.021 & -0.091 & -0.285 & -0.380 & -0.324 \\ Criminal & -0.395** & -0.350* & -0.417** & -0.295 & -0.296 \\ Economics & -0.248*** & -0.248*** & -0.212** & -0.208** & -0.181** \\ Education & -0.146 & -0.088 & -0.102 & -0.010 & 0.082 \\ Entrepreneurship & -0.138 & -0.085 & -0.108 & -0.105 & -0.136 \\ Finance & -0.401* & -0.404** & -0.391** & -0.391** & -0.387** \\ Geography & -0.266 & -0.246 & -0.298 & -0.314 & -0.189 \\ Health Economics & -0.767** & -0.784*** & -0.890*** & -0.870*** & -0.786*** \\ Information Systems & 0.033 & 0.042 & 0.070 & 0.070 & 0.060 \\ Law & 0.081 & 0.088 & 0.097 & 0.140 & 0.149 \\ Management & -0.056 & -0.011 & -0.075 & -0.013 & -0.019 \\ Organization & 0.069 & 0.169 & 0.157 & 0.148 & 0.115 \\ Political Science & -0.262*** & -0.252*** & -0.233*** & -0.232*** & -0.221*** \\ Sustainability & -0.687** & -0.673*** & -0.644*** & -0.637*** & -0.589*** \\ Women/Gender & -0.238 & -0.090 & -0.139 & -0.103 & -0.072 \\ Observations & {40} & {42} & {44} & {46} & {48}\\ \bottomrule \end{tabular} \noindent This table reports the estimated coefficients based on Equation~\eqref{eq:did} for each discipline. The coefficients for 6, 7, 8, 9, and 10 weeks since the lockdown are presented in Columns (1)--(5), respectively. Time fixed effects at the weekly level are included in all regressions. Standard errors and estimates of other variables are omitted for brevity. Significance at $^{*}p<0.1$; $^{**}p<0.05$; $^{***}p < 0.01$. \end{threeparttable} \end{table} \end{comment} \begin{comment} We next try to analyze what might be driving the inequality variations across disciplines. One key factor could be that in some disciplines, there are more potential COVID-related research topics by nature, and therefore, scholars in those disciplines might be able to explore these research opportunities. Female researchers, because of their disproportionately affected productivity, could not exploit these new COVID-related research topics as extensively as their male colleagues. Therefore, the gender gap in productivity will likely to be larger for disciplines that have more COVID-related research opportunities. To illustrate whether COVID-related research could explain inequality variations across disciplines, we repeat our sub-sample analysis with only COVID-related preprints using Equation~\eqref{eq:did} for each discipline. We report the coefficients of gender inequality (i.e., column (5) of Table~\ref{table:discipline}) in the first column of Table~\ref{table:discipline_COVID} and the coefficients of gender inequality in COVID-related preprints in the second column of Table~\ref{table:discipline_COVID}. We define a dummy variable that represents whether gender inequality in the first column is statistically significant or not, and we then test the correlation between this variable and the COVID-related gender inequality in the second column. We find a significantly negative correlation (p-value $= 0.002$), suggesting that COVID-related research opportunities could explain variations of gender inequality across disciplines. \end{comment} \subsubsection{Effects across countries.} Finally, we examine how the estimated gender inequality varies across countries by replicating the analysis for academics in each country. Figure~\ref{fig:countries} illustrates the impact on the productivity gap graphically by plotting the estimates of the interacted term with 90-percent and 95-percent confidence intervals; a negative value represents a drop in female academics' research productivity relative to that of male academics. We can observe that most countries---21 out of 25 countries---have experienced a decline in female researchers' productivity. In addition to the US, six countries have shown statistically significant declines: Japan, China, Australia, Italy, the Netherlands, and the United Kingdom. Note that because SSRN is primarily used by US researchers, its preprints for other countries might be limited, which might weaken our ability to detect changes. \begin{figure}[h] \caption{Impact of Lockdown on Gender Inequality across Countries} \label{fig:countries} \vspace{0.05in} \centering \includegraphics[scale=0.36]{country_impact.png} \vspace{0.05in} \noindent \scriptsize This graph plots the estimates of the interacted term with 90-percent and 95-percent confidence intervals in each country. The negative values represent female academics' research productivity drop relative to that of male academics. \end{figure} \section{Robustness Checks} In this section, we report the results of several robustness tests. Specifically, we check the parallel trends assumption and conduct falsification tests to ensure that our estimated effects are not idiosyncratic. We also test gender inequality in research quality, examine the co-authorship issue, and rule out the data censoring concern. \begin{comment} \noindent \textbf{Exogenous shock}. The validity of our empirical approach resides in the assumption that the shock is exogenous with respect to the researchers' anticipated responses. If a particular gender group of researchers anticipated and strategically prepared for the shock by accelerating the wrap-up of their current research papers, among others, this could confound the treatment effect. In reality, this possibility is unlikely because of the rapid development of the situation from a small number of cases into a global pandemic. In fact, COVID-19 was regarded as low risk and not a threat to the US in late January \citep{fauci} and no significant actions had been taken other than travel warnings issued for four countries until late February \citep{travelban}. It quickly turned into a global pandemic after the declaration of the World Health Organization on March 11, 2020 followed by the nationwide shelter-in-place orders within a week.\footnote{Available at \url{https://www.cdc.gov/nchs/data/icd/Announcement-New-ICD-code-for-coronavirus-3-18-2020.pdf}, accessed June 2020} Therefore, the pandemic outbreak and the lockdown measure exerted influence on female and male academics simultaneously. \end{comment} \subsection{Parallel trends} The key identification assumption for the DID estimation is the parallel trends assumption; namely, that before the COVID-19 shock, female and male researchers' productivity would follow the same time trend. In Appendix Figure~\ref{fig:trend2019}, which presents the time trends of preprints in 2019, visual inspection shows the two genders' parallel evolution before the shock. We then test this assumption by performing an analysis similar to that of \cite{seamans2013responses} and \cite{wagner2018disclosing}, in which we expand Equation~\eqref{eq:did_discipline} to estimate the treatment effect week by week before the shock. Specifically, we replace $Lockdown_{t}$ in Equation~\eqref{eq:did} with the dummy variable $Time^{t}_{\tau}$, where $\tau\in\{-14,-13,...,-2,-1,0\}$ and $Time^{t}_{\tau}=1$ if $\tau=t$ and 0 otherwise, indicating the relative $\tau$th week of the outbreak, \begin{equation}\label{eq:did_parallel} log(Preprint_{igt}) = c + Female_{g} + \sum^{-1}_{\tau=-14} Time^t_{\tau} + \sum^{-1}_{\tau=-14} \beta_{\tau} Female_{g}\times Time^t_{\tau} + \delta_i + \epsilon_{igt}. \end{equation} The benchmark group is the week of the pandemic outbreak. The coefficients $\beta_{-14}$ to $\beta_{-1}$ identify any week-by-week pre-treatment difference between the female and male researchers, which we expect to be insignificant. We then repeat the same analysis with our aggregate-level data. Appendix Table \ref{table:trend} presents the estimation results. They show no pre-treatment differences in the research productivity trends of female and male academics, which supports the parallel trends assumption. \subsection{Falsification test} To show that our estimate effects are not an artifact of seasonality, we test whether such a decline in female productivity also occurred in 2019. Appendix Table~\ref{table:statistics2} reports the summary statistics in 2019. We repeat the same analysis specified in Equation~(\ref{eq:did}) using data in 2019 for the same time window used in 2020. If our results simply capture seasonality, we would be able to find significant effects in 2019. Appendix Table \ref{table:falsification} reports the falsification test results. The placebo-treated average treatment effects are insignificant, implying that women's productivity did not decline significantly in the previous year. \subsection{Research Quality} So far, we study the research quantity--- using \textit{Number of Preprints} as the dependent variable. One might question whether the difference in productivity is because, since the lockdown began, male researchers increased the volume of their production at the expense of quality. If this is true, the relative quality of female researchers' preprints should have increased since the lockdown. We test this possibility using data on how many times the abstract has been viewed and the preprint has been downloaded for each preprint, the two primary quality indicators used by SSRN to rank preprints. Appendix Table~\ref{table:statistics_downloads_views} reports the summary statistics of these two variables. We compare the average number of abstract views per preprint and the average number of downloads per preprint for preprints from male and female researchers prior to and after the pandemic outbreak using the same specification as in Equation~(\ref{eq:did_discipline}) with the discipline fixed effect: \begin{equation}\label{eq:did_view_download} log(Abstract\ Views_{gt}~or~Downloads_{gt}) = c + Female_{g} + \beta Female_{g}\times Lockdown_{t} + \gamma_t + \delta_i + \epsilon_{igt}. \end{equation} \renewcommand{\arraystretch}{1.1} \begin{table}[h] \centering \scriptsize \vspace{-0.1in} \caption{Impact of Lockdown on Abstract Views} \label{table:views_displine} \begin{threeparttable} \begin{tabular}{L{4cm} @{}l*{5}{S[table-format=-1.3,table-space-text-post=***,table-column-width=2cm]}@{}} \toprule & \multicolumn{5}{c}{Dependent variable: No. of Abstract Views (in logarithm) by discipline} \\ & {6 weeks} & {7 weeks} & {8 weeks} & {9 weeks} & {10 weeks} \\ {Variables} & {(1)} & {(2)} & {(3)} & {(4)} & {(5)} \\ \hline \\[-1.8ex] {$Female$} & -0.083* & -0.083* & -0.083* & -0.083* & -0.083* \\ & {(0.047)} & {(0.047)} & {(0.048)} & {(0.048)} & {(0.049)} \\ {$Female \times Lockdown$} & 0.103 & 0.112 & 0.090 & 0.087 & 0.050 \\ & {(0.085)} & {(0.079)} & {(0.074)} & {(0.070)} & {(0.068)} \\ {Time fixed effects} & {Yes} & {Yes} & {Yes} & {Yes} & {Yes} \\ {Discipline fixed effects} & {Yes} & {Yes} & {Yes} & {Yes} & {Yes} \\ Observations & {720} & {756} & {792} & {828} & {864} \\ $R^{2}$ & 0.828 & 0.829 & 0.830 & 0.831 & 0.834 \\ \bottomrule \end{tabular} \noindent This table reports the estimated coefficients and robust standard errors (in parentheses) in Equation~\eqref{eq:did_view_download} using the discipline fixed effect, with $log(abstract\ views)$ as the dependent variable. The coefficients for 6, 7, 8, 9, and 10 weeks since the lockdown are presented in Columns (1)--(5), respectively. Significance at $^{*}p<0.1$; $^{**}p<0.05$; $^{***}p < 0.01$. \end{threeparttable} \end{table} \renewcommand{\arraystretch}{1.1} \begin{table}[h] \centering \scriptsize \vspace{-0.1in} \caption{Impact of Lockdown on Downloads} \label{table:downloads_displine} \begin{threeparttable} \begin{tabular}{L{4cm} @{}l*{5}{S[table-format=-1.3,table-space-text-post=***,table-column-width=2cm]}@{}} \toprule & \multicolumn{5}{c}{Dependent variable: No. of Downloads (in logarithm) by discipline} \\ & {6 weeks} & {7 weeks} & {8 weeks} & {9 weeks} & {10 weeks} \\ {Variables} & {(1)} & {(2)} & {(3)} & {(4)} & {(5)} \\ \hline \\[-1.8ex] {$Female$} & -0.049 & -0.049 & -0.049 & -0.049 & -0.044 \\ & {(0.042)} & {(0.043)} & {(0.043)} & {(0.043)} & {(0.067)} \\ {$Female \times Lockdown$} & -0.077 & -0.101 & -0.111 & -0.128* & -0.131* \\ & {(0.085)} & {(0.077)} & {(0.072)} & {(0.068} & {(0.065)} \\ {Time fixed effects} & {Yes} & {Yes} & {Yes} & {Yes} & {Yes} \\ Observations & {720} & {756} & {792} & {828} & {864} \\ $R^{2}$ & 0.853 & 0.855 & 0.855 & 0.858 & 0.861 \\ \bottomrule \end{tabular} \noindent This table reports the estimated coefficients and robust standard errors (in parentheses) in Equation~\eqref{eq:did_view_download} using the discipline level fixed effect, with $log(downloads)$ as the dependent variable. The coefficients for 6, 7, 8, 9, and 10 weeks since the lockdown are presented in Columns (1)--(5), respectively. Significance at $^{*}p<0.1$; $^{**}p<0.05$; $^{***}p < 0.01$. \end{threeparttable} \end{table} Tables~\ref{table:views_displine} and~\ref{table:downloads_displine} report the the effect of the lockdown on the number of abstract views and the number of downloads, respectively. In general, the average treatment effects are insignificant, suggesting that after the lockdown, female and male researchers' research quality did not change significantly, and that our findings are unlikely to be driven by shifts in research quality. In addition, column (4) and (5) of Table~\ref{table:downloads_displine} suggest that female researchers' research quality in terms of the number of downloads per preprint decreased compared to male researchers' after the lockdown. We repeat our analysis using Equation~\ref{eq:did} and find consistent results. The estimation results are reported in Appendix Tables~\ref{table:did_views} and \ref{table:did_downloads}. \subsection{Coauthorship} We next study how coauthorship across genders affects our results. Recall that we measure the \textit{effective} productivity for preprints with $n$ authors by allocating $1/n$ preprint to each coauthor. That is, our measure implicitly assumes equal productivity across female and male authors. To alleviate the concern that this assumption may not hold, we conduct a sub-sample analysis focusing on preprints that have either \textit{all-male} or \textit{all-female} authors, excluding preprints that have both male and female authors. We repeat our DID analysis for this sub-sample using Equations~\eqref{eq:did_discipline} and~\eqref{eq:did} to compare the productivity gap between all-male and all-female preprints. Table~\ref{table:did_allmf_bycat} reports the estimation results with the discipline fixed effect using Equation~\eqref{eq:did_discipline}. The results show that the number of all-female preprints has significantly dropped since the lockdown, compared to all-male preprints. Note that the coefficients of $Female \times Lockdown$ in Table~\ref{table:did_allmf_bycat} are more significant and larger than those in Table~\ref{table:did_discipline}, suggesting that gender inequality is more pronounced when a research team has only female authors. Intuitively, an all-female research team's capacity is more severely constrained, resulting in a lower productivity. Table~\ref{table:did_allmf_all} reports the results at the aggregate-level and the results are consistent. \renewcommand{\arraystretch}{1.1} \begin{table}[h] \centering \scriptsize \vspace{-0.1in} \caption{Impact of Lockdown on Gender Inequality among All-male and All-female Preprints } \label{table:did_allmf_bycat} \begin{threeparttable} \begin{tabular}{ L{4cm} @{}c*{5}{S[table-format=-1.3,table-space-text-post=***,table-column-width=1.8cm]}@{}} \toprule & \multicolumn{5}{c}{Dependent variable: No. of Preprints (in logarithm) by discipline} \\ & {6 weeks} & {7 weeks} & {8 weeks} & {9 weeks} & {10 weeks} \\ {Variables} & {(1)} & {(2)} & {(3)} & {(4)} & {(5)} \\ \hline \\[-1.8ex] {$Female$} & $-$1.002*** & -1.002*** & -1.002*** & -1.002*** & -1.002*** \\ & {(0.047)} & {(0.047)} & {(0.047)} & {(0.047)} & {(0.047)} \\ {$Female \times Lockdown$} &$-$0.233*** & -0.263*** & -0.267*** & -0.255*** & -0.232*** \\ & {(0.088)} & {(0.084)} & {(0.079)} & {(0.076)} & {(0.074)} \\ Discipline fixed effects & {Yes} & {Yes} & {Yes} & {Yes} & {Yes} \\ Time fixed effects & {Yes} & {Yes} & {Yes} & {Yes} & {Yes} \\ Observations & {720} & {756} & {792} & {828} & {864} \\ $R^{2}$ & 0.810 & 0.810 & 0.812 & 0.813 & 0.814 \\ \bottomrule \end{tabular} \noindent This table reports the estimated coefficients and robust standard errors (in parentheses) in Equation~\eqref{eq:did_discipline} with the discipline level fixed effect. We restrict our sample to preprints that have either all-male authors, or all-female authors. The coefficients for 6, 7, 8, 9, and 10 weeks since the lockdown are presented in Columns (1)--(5), respectively. Significance at $^{*}p<0.1$; $^{**}p<0.05$; $^{***}p < 0.01$. \end{threeparttable} \end{table} \subsection{Data Censoring} One might be concerned that because research takes time, many researchers only post one preprint during our sample period. As a result, our data sample before and after the lockdown may contain a different set of authors. To address this concern, we perform two analyses. First, we collect additional data on US authors, extending the time window of our main analysis to 40 weeks. By adding 16 weeks to the post-treatment period, we capture more researchers in our sample, especially those who were not able to post preprints within 10 weeks of the lockdown. We repeat the DID analysis and find consistent results. Second, we construct a balanced panel by including only authors who posted preprints before the lockdown to compare the productivity of the same group of authors before and after the lockdown. This approach ensures an apple-to-apple comparison and helps us rule out potential biases introduced by different author samples in the pre-treatment and post-treatment periods. Table~\ref{table:balanced_aggregated} reports the estimated results using the balanced panel. The findings are consistent with our main results: within the same group of authors, female researchers' productivity dropped significantly after the lockdown compared to male researchers' productivity. \renewcommand{\arraystretch}{1.1} \begin{table}[h] \centering \scriptsize \vspace{-0.1in} \caption{Impact of Lockdown on Gender Inequality Using the Balanced Panel} \label{table:balanced_aggregated} \begin{threeparttable} \begin{tabular}{ L{4cm} @{}c*{5}{S[table-format=-1.3,table-space-text-post=***,table-column-width=1.8cm]}@{}} \toprule & \multicolumn{5}{c}{Dependent variable: No. of Preprints (in logarithm) in aggregation} \\ & {6 weeks} & {7 weeks} & {8 weeks} & {9 weeks} & {10 weeks} \\ {Variables} & {(1)} & {(2)} & {(3)} & {(4)} & {(5)} \\ \hline \\[-1.8ex] {$Female$} & $-$0.920*** & -0.920*** & -0.920*** & -0.920*** & -0.920*** \\ & {(0.065)} & {(0.065)} & {(0.065)} & {(0.065)} & {(0.065)} \\ {$Female \times Lockdown$} &$-$0.518*** & -0.638*** & -0.589*** & -0.556*** & -0.641*** \\ & {(0.138)} & {(0.170)} & {(0.159)} & {(0.148)} & {(0.159)} \\ Discipline fixed effects & {Yes} & {Yes} & {Yes} & {Yes} & {Yes} \\ Time fixed effects & {Yes} & {Yes} & {Yes} & {Yes} & {Yes} \\ Observations & {40} & {42} & {44} & {46} & {48} \\ $R^{2}$ & 0.991 & 0.988 & 0.988 & 0.988 & 0.985 \\ \bottomrule \end{tabular} \noindent This table reports the estimated coefficients and robust standard errors (in parentheses) in Equation~\eqref{eq:did} at the aggregate level. The coefficients for 6, 7, 8, 9, and 10 weeks since the lockdown are presented in Columns (1)--(5), respectively. Significance at $^{*}p<0.1$; $^{**}p<0.05$; $^{***}p < 0.01$. \end{threeparttable} \end{table} \section{Conclusions} Our paper adds to the long-standing literature on gender equality, an important topic in social science. For example, the literature has shown evidence of fairness in parental leaves \citep{lundquist2012parental} and inequality in tenure evaluation \citep{sarsons2017recognition,antecol2018equal}, recognition \citep{ghiasi2015compliance}, and compensation \citep{pierce2020peer}. Researchers have also investigated business innovations to help empower women \citep{l2020alleviating}. The COVID-19 crisis brings to the forefront a long existing issue: the inequities faced by women who often do more of the childcare and housework. We contribute to the literature by providing direct tests of the impact of the pandemic shock on gender inequality in academia. We show that in the US, since the lockdown began, women have produced 13.2--13.9-percent fewer social science research papers than men. We also find that the effect is especially significant for junior faculty and for researchers at top-ranked universities. Finally, we find that the increase in productivity inequality is significant in seven countries. The results are robust when we repeat our analysis over papers with same-gender authors, a balanced sample with the same group of authors before and after the lockdown, and an extended data sample. Our findings indicate that, if the lockdown is kept in place for too long, female academics in junior positions and at top-ranked universities are likely to be significantly disadvantaged---a fairness issue that may expose women to a higher unemployment or career risk in the future. We hope our findings increase awareness of this issue. Actions could be taken to balance domestic responsibilities among spouses. Recently, many universities have taken actions such as granting tenure clock extensions to both female and male faculty. Recall that our paper finds an overall 35-percent increase in productivity and a 13-percent increase in gender gap among social science researchers. Therefore, our findings do not provoke a concern for overall productivity but rather for gender inequality. As a result, universities could consider providing additional support, such as childcare support, to female researchers whose productivity has been disproportionately affected. Universities and letter writers should keep this inequality in mind when evaluating professors for promotion. We also hope our work will inspire researchers to explore other forms of inequality arising from the COVID-19 pandemic. Our findings also suggest that telecommuting may have unintended consequences for gender inequality. As the COVID-19 outbreak accelerates the trend toward telecommuting, institutions and firms should take gender equality into consideration when designing and implementing telecommuting policies. We hope that our work could serve as a stepping stone to stimulate more research on the synergy between operations and social issues. Our study has a few limitations. First, since it focuses on social science disciplines, and thus the findings may not be generalizable to other disciplines. Second, we have limited information about the researchers in our dataset. Future research could collect additional data---such as parental status, whether they are allocating more or less time to research than they did before the pandemic, whether they multitask at home, and who performs household duties---to pinpoint the exact mechanism underlying the observed empirical patterns. \newpage \bibliographystyle{ormsv080} \addcontentsline{toc}{section}{\refname}
{'timestamp': '2021-02-23T02:29:52', 'yymm': '2006', 'arxiv_id': '2006.10194', 'language': 'en', 'url': 'https://arxiv.org/abs/2006.10194'}
arxiv
\section{Introduction} \vspace{-5pt} With development and popularity of VR/AR devices recently, there is an increasing demand to work with these devices intuitively. Gestures are the most natural form for humans to interact with such type of devices, in which hand gestures can be conveniently captured by cameras integrated in the devices in first person view. This motivates accurate recognition of meaningful gestures from such egocentric gesture videos. Video recognition systems for such VR/AR applications in the real world should ideally be designed in a way to support incremental update and customization of gestures. Different communicative gestures should be customized for different VR games~\cite{yang2019gesture}. Traditional machine learning/deep learning approaches require training data of all classes accessed at the same time, which is hardly achievable in such real-world situations. For instance, when a new gesture should be added to a system, the model needs to be retrained by incorporating the gesture video samples of previous and new classes, which requires significant memory for storing all previous class videos and increasing computational cost over time. A system with capability of lifelong learning would therefore be very beneficial for such scenarios, in which incremental learning makes use of memory efficiently, enables fast learning for new class samples and does not forget the previous class samples. In this work, we demonstrate a c(\textbf{C})la(\textbf{a})ss increment(\textbf{t})al net(\textbf{Net})works (CatNet) for an open-set problem rather than a close-set problem, which learns new classes i.e., the class variants larger than instance variants. Hand-crafted features are commonly adopted in traditional video gesture recognition~\cite{liu2013learning,ohn2014hand,wan2016chalearn}. With more large-scale datasets being released and development of deep neural networks (DNNs), DNNs are playing a more and more important role in this field~\cite{kopuklu2019real,cao2017egocentric}. Different from image recognition, temporal information along each frame needs to be considered for video understanding. The 3D convolutional network (ConvNet) becomes a popular architecture for learning spatiotemporal features from video clips. Benefiting from large-scale video datasets being released~\cite{kay2017kinetics,caba2015activitynet,abu2016youtube}, deep 3D ConvNets have achieved striking results in video action recognition tasks~\cite{hara2018can,carreira2017quo,diba2017temporal}. Compared to current popular video action datasets e.g., UCF-101~\cite{soomro2012ucf101}, Kinetics~\cite{kay2017kinetics}, egocentric gesture video is in first person view, in which two modalities RGB and depth can be captured at the same time. This indicates more information can be used to train the models for the egocentric gesture video recognition. Two-stream 3D ConvNets~\cite{simonyan2014two} is proposed for video action recognition by using optical flow~\cite{dosovitskiy2015flownet} in addition to RGB frames but optical flow is difficult to compute and to use for large-scale datasets~\cite{diba2017temporal}. We evaluate our models on a recently released large-scale egocentric gesture video dataset named EgoGesture~\cite{zhang2018egogesture}, in which RGB and depth modalities are provided. Benefiting from RGB-D video, we propose a two-stream architecture that deploys RGB and depth as two streams for egocentric gesture video recognition in this work, which deals the inconsistent quality of RGB and depth frames (see Figure~\ref{fig:frame_viz}) across different scenes (6 different scenes are included in the dataset) during the recording. Figure~\ref{fig:frame_viz} shows two gesture examples in two scenes respectively i.e., in a walking state with a dynamic background on the left and in a stationary state facing a window with drastically changing sunlight on the right. It can be noticed that the quality of the RGB input and the depth input are not consistent i.e., walking and outdoor capture can result in poor depth data, while illumination changes from changing sunlight can affect distribution of RGB pixels. Fusing features produced by a two-stream architecture can mitigate this issue, which results in a better overall performance. Previous work has shown that the frame-based approaches (e.g., VGG-16) are ineffective for the EgoGesture video recognition~\cite{zhang2018egogesture} because such methods do not take account into temporal information. Video-based approaches are required for accurate recognition in this scenario. \begin{figure}[!ht] \centering \includegraphics[width=.105\textwidth]{sub1_s6_rgb1_575} \includegraphics[width=.105\textwidth]{sub1_s6_D1_575} \hspace{10pt} \includegraphics[width=.105\textwidth]{sub4_s3_rgb8_203} \includegraphics[width=.105\textwidth]{sub4_s3_D8_203} \caption{Visualization of gestures in different scenes. Left: The participant in a walking state with a dynamic background. Right: The participant in a stationary state facing a window with drastically changing sunlight.} \label{fig:frame_viz} \end{figure} Significant advances have been made recently in computer vision and deep learning tasks including object recognition, detection, segmentation, etc. However, most of the models can only be trained in a batch setting, in which training data of all object classes is required for training the model in a roll. Lifelong learning~\cite{parisi2019continual} is a strategy to enable training the model continuously. To overcome the issue addressed earlier in the context of egocentric video recognition, in which the system should be able to learn new gestures incrementally, we introduce a lifelong learning framework -- c(\textbf{C})la(\textbf{a})ss increment(\textbf{t})al net(\textbf{Net})works (CatNet), which is specifically designed for lifelong egocentric gesture video recognition based on 3D convolutional networks (ConvNets). Importantly, we propose a two-stream CatNet using RGB and depth input as separate streams, which achieves the best performance in the class incremental learning task. To summarize, our contribution are three-fold: \begin{itemize} \item To the best of our knowledge, we are the first to address the class incremental issues in the area of egocentric gesture video recognition and introduce the lifelong learning approaches to this area. \item We propose a two-stream CatNet for egocentric gesture video recognition, which treats RGB and depth as two separate streams and this type of CatNet is shown to perform best in the class incremental task. \item Our results show that CatNets can learn many classes incrementally over a long period of time i.e., the highest mean accuracy of presented CatNet has achieved 0.884. \end{itemize} \section{Related Work} We introduce some recent literature with respect to video action recognition, EgoGesture video recognition and lifelong learning in this section. \subsection{Video Action Recognition}\label{sec:video-action-recognition} The success of convolutional networks (ConvNets) in object detection~\cite{redmon2016you}, object recognition~\cite{krizhevsky2012imagenet}, panoptic segmentation~\cite{long2015fully} tasks etc. has attracted growing interest for deploying them to other areas of computer vision. Video understanding has became a very popular research area recently, which is driven by several released large-scale datasets such as Kinetics~\cite{kay2017kinetics}, YouTube-8M~\cite{abu2016youtube}, ActivityNet~\cite{caba2015activitynet} and Sports-1M~\cite{karpathy2014large}. Unlike image tasks, video tasks require not only spatial information for each frame but also temporal information for neighboring frames, which poses a challenge for traditional methods performing on image tasks. Video understanding for untrimmed video datasets e.g., ActivityNet is still very challenging today because it requires to consider the possibility of accomplishing additional tasks such as untrimmed action classification and detection. Work discussed in this paper only considers the trimmed video scenario. Many methods have been proposed for video action recognition by introducing temporal information to the model. 3D convolution has been firstly introduced in~\cite{ji20123d}, which enables 3D convolutional networks (3D ConvNets) to extract features from both spatial and temporal dimensions. With the success in learning spatiotemporal information from consecutive frames by using 3D convolutional modules, several 3D types of architectures have been proposed in this field e.g., I3D~\cite{carreira2017quo}, P3D~\cite{qiu2017learning}, T3D~\cite{diba2017temporal} and R3D~\cite{hara2018can}. The work in \cite{hara2018can} addresses that it is important to use a pretrained model that is trained on a large-scale video dataset for a specific video task, which is able to avoid issues such as overfitting, difficult to converge and long time for training. The authors also demonstrate the efficacy of using R3D (use ResNet block as backbone for 3D convolution) for video action recognition, providing good performance and flexible architectures. By using more than one modality for video action recognition, multimodal representation has achieved remarkable results~\cite{wang2016exploring,simonyan2014two,carreira2017quo,feichtenhofer2016convolutional,wang2016temporal}. A typical architecture is the two-stream ConvNet~\cite{simonyan2014two,carreira2017quo}, which uses RGB frames and optical flow~\cite{dosovitskiy2015flownet} for training two separate networks. However, the computation of optical flow is very expensive, which limits its deployment in practice~\cite{diba2017temporal}. There are lots of depth cameras available on the market with acceptable price e.g., RealSense Camera SR300, which makes RGB frames and depth maps conveniently accessible for the egocentric-like datasets e.g., EgoGesture. In this work, we apply a two-stream 3D ConvNet by using RGB frames and depth frames, where the R3D is used as the backbone for our 3D ConvNet. \subsection{Egocentric Gesture Video Recognition} Datasets Like EgoGesture \cite{cao2017egocentric, zhang2018egogesture}, GreenScreen \cite{tejo2018} pave the wave for end-to-end learnable DNN architectures to address large-scale egocentric gesture recognition problems. Cao \etal \cite{cao2017egocentric} propose a neural network architecture by using a 3D ConvNet in tandem with spatiotemporal transformer modules and a LSTM for recognizing egocentric gestures from trimmed egocentric videos. In their network design, conceptually 3D ConvNets calculate the motion features and STTMs compensate for the ego motion. Shi \etal \cite{she2019openloris} improve on this approach by replacing spatiotemporal transformer modules with spatiotemporal deformable modules to overcome the issue of non-availability of local geometric transformations. Chalasani and Smolic \cite{tejo2019} propose a different network architecture that extracts embeddings specific to ego hands which are calculated as output from their encoder and decoder based architecture, which simultaneously computes hand segmentation. The embeddings thus generated for each trimmed video are then used in LSTMs to discern the gesture present in the video. In a different approach, Abavisani \etal \cite{abavisani2019improving} propose a training strategy to use knowledge from multi-modal data to get better performance on unimodal 3D ConvNets. Unlike Cao \etal \cite{cao2017egocentric}, they train a separate network for each available modality and use a new spatiotemporal semantic alignment loss function, which they propose to share the knowledge among all the trained networks. The scope for application of recognizing gestures from trimmed videos is limited. To address this issue, K{\"o}p{\"u}kl{\"u} \etal \cite{kopuklu2019real} introduce a network architecture that could enable offline working CNN based networks to work online using a sliding window approach. However, the idea of lifelong learning for egogesture recognition has not been explored in any of the mentioned papers. Given a new gesture, the entire network has to be trained with all the gestures starting the training process from the beginning, which becomes cumbersome as the number of gestures increases incrementally. \subsection{Lifelong Learning} Current state-of-the-art DNNs have achieved impressive performance on a variety of individual tasks. However, it still remains a substantial challenge for deep learning, which is learning multiple tasks continuously. When training DNNs on a new task, a standard DNN forgets most of the information related to previously learned tasks. This phenomenon is known as ``catastrophic forgetting''~\cite{mccloskey1989catastrophic}. There are three scenarios in the area of lifelong learning~\cite{van2019three}: (1) Task incremental learning, where the task ID is provided during testing; (2) Domain incremental learning, where the task ID is not provided during testing and the model does not have to infer the task ID; and (3) Class incremental learning, the task ID is not provided during testing and the model has to infer the task ID. The first scenario is the easiest one and the model is always informed about which task is going to be performed. In this case, the model can be trained with task-specific components. A typical network for such a scenario can have a ``multi-headed'' output layer for each task and the rest of the model can be shared across tasks~\cite{van2019three}. A typical example for the second scenario is that the environment is changing e.g., image background changes but the objects remain the same for an object recognition task. The model has to solve the task but does not infer how the environment changes~\cite{feng2019challenges}. The last scenario is the most challenging one which requires the model to infer each task. For example, the model has to learn new classes of objects incrementally in an object recognition task. In this work, we focus on the most challenging scenario -- class incremental learning, where we address the importance for learning gesture classes incrementally regarding the egocentric gesture video recognition. Catastrophic forgetting appears when the new instance is significantly different from previous observed examples. Current strategies such as replay of old samples~\cite{gepperth2016bio,rebuffi2017icarl} and regularization~\cite{benna2016computational,fusi2005cascade} can be deployed to mitigate this problem. FearNet was proposed in~\cite{kemker2017fearnet}, where a generative neural network~\cite{parisi2019continual,wang2019generative,wang2019neuroscore,wang2020use} is used to create pseudo-samples that are intermixed with recently observed examples stored in its hippocampal network. PathNet~\cite{fernando2017pathnet} was proposed as an ensemble method, where a generic algorithm is used to find the optimal path through a neural network of fixed size for replication and mutation. Ideally, the lifelong learning should be triggered by the availability of short videos of single objects and performed online on the hardware with fine-grained updates, while the mainstream of methods we study are limited with much lower temporal precision as our previous sequential learning models~\cite{she2018reduced,she2019neural}. In~\cite{rebuffi2017icarl}, iCaRL was proposed to cache the most representative samples from previous classes by using representation learning, which demonstrates good performance on class incremental learning. It is also easy to be extended to any type of network architectures. Benefiting from these advantages, we incorporate iCaRL into our CatNet to realize a lifelong learning system for egocentric gesture video recognition. \section{Methodology} In this section, we first elaborate on the type of 3D ConvNets investigated in this work, which is known as R3D. Then we present a two-stream 3D ConvNet for egocentric gesture video recognition (EgoGesture dataset is used in this work). Finally we introduce a CatNet, which incorporates the class incremental learning strategy with 3D ConvNets. Two evaluation metrics are presented at the end of this section. \subsection{Architectures} Two types of R3D architectures are investigated in this work, which use ResNet and ResNeXt respectively as the block unit. The difference between ResNet and ResNeXt is refered in~\cite{hara2018can}. Three models are studied, which are ResNet-50 using 16 frames as an input (ResNet-50-16f), ResNeXt-101 using 16 frames as an input (ResNeXt-101-16f), and ResNeXt-101 using 32 frames as an input (ResNeXt-101-32f)~\cite{hara2018can,kopuklu2019real}. As mentioned earlier in the paper, temporal information is important for video understanding. 3D convolution has became a popular operation to preserve the temporal properties of a video. Figure~\ref{fig:3D-convolutional-operation} illustrates the difference between the 3D convolutional operation and the 2D convolutional operation. 2D ConvNets lose track of temporal information of the input after every convolutional operation while 3D ConvNets are able to output a video clip by feeding a video clip, which preserves the temporal information. Figure~\ref{fig:previous-3D-net} illustrates previous popular architectures for video action recognition. Previous two-stream architectures learn the temporal information by using 3D convolution and optical flow~\cite{simonyan2014two,feichtenhofer2016convolutional,carreira2017quo,dosovitskiy2015flownet}. Optical flow represents the motion over time can be calculated from every two neighboring frames. Traditional two-stream architectures all use RGB frames and optical flow as two streams. However, the computation of optical flow is very complex i.e., computing over each individual frame, which is difficult in real-world applications~\cite{diba2017temporal}. We propose the use of depth frames as another stream with RGB frames for the EgoGesture dataset. It should be noticed that, differing from optical flow, the objective of the depth stream is not to extract temporal information. It aims to provide the depth level, in which different backgrounds e.g., brightness, indoor and outdoor in EgoGesture may drive different effects on RGB frames. The temporal information can be preserved by using 3D convolution. Figure~\ref{fig:two-stream-model} shows the two-stream architecture deployed in this work. Two 3D ConvNets are trained independently by using RGB and depth videos (see the training flow in Figure~\ref{fig:two-stream-model}) and the second last layer features of two networks are concatenated with each other (see the testing flow in Figure~\ref{fig:two-stream-model}), which is used for clustering during testing (we will explain this in the next section). \begin{figure*} \begin{minipage}{0.65\linewidth} \subfigure[Comparison between 2D and 3D convolutional operations. Left: 2D convolution on an image, in which the output is an image. Middle: 2D convolution on a video clip, in which the output is an image. Right: 3D convolution on a video clip, in which the output is also a video clip. Figure from~\cite{tran2015learning}.]{\includegraphics[width=0.55\textwidth]{3D_convolution_operation}\label{fig:3D-convolutional-operation}} \hspace{5pt} \subfigure[Previous two-stream video architectures in the literature. K stands for the total number of frames in a video while N stands for a subset of neighboring frames of the video. Figure from~\cite{carreira2017quo}.]{\includegraphics[width=0.55\textwidth]{previous_3D_net}\label{fig:previous-3D-net}} \end{minipage} \hspace{-.8cm} \begin{minipage}{0.5\linewidth} \centering \subfigure[Two-stream 3D ConvNet used in this work. ]{\includegraphics[width=0.5\textwidth]{two_stream_model}\label{fig:two-stream-model}} \end{minipage} \caption{Illustration of 3D ConvNets and the two-stream 3D ConvNet used in this work.} \label{fig:Illustration-3D-convolutional-networks} \end{figure*} \subsection{CatNet} We incorporate iCaRL~\cite{rebuffi2017icarl} with 3D ConvNets for class incremental EgoGesture video recognition in this work and we call this framework CatNet. The whole training process for a CatNet is summarized in Algorithm~\ref{al:icarl} and Algorithm~\ref{al:icarl-cache-sample} and is visualized in Figure~\ref{fig:testing_schematic}. The core part of CatNet is to cache some previous class samples that are the most representative of the old class i.e., see the green block in Figure~\ref{fig:testing_schematic}. The memory caches the selected video samples and their corresponding predictions for previous class samples, which is achieved by learning the \textbf{feature representation} (Algorithm~\ref{al:icarl-cache-sample}). The feature representation is computed by the mean value of features (i.e., the second last layer output of the 3D ConvNet) corresponding to one class (see the feature mean matrix in Figure~\ref{fig:testing_schematic}). We then cache the first $k$ samples in which features of those samples are the closest to the representation (feature mean). The cached samples play two roles during the class incremental learning. First, the cached samples are used to compute the representation for each class, which is used for inference (see the nearest mean classifier in Figure~\ref{fig:testing_schematic}). Second, the prediction is used to compute the distillation loss during the training in Algorithm~\ref{al:icarl}. The inference procedure is summarized in Algorithm~\ref{al:icarl-inference} and the yellow block Figure~\ref{fig:testing_schematic}. The feature is extracted from a testing video, which is to be compared with the cached feature mean matrix. The class minimizing the $L_2$ distance is assigned as the predicted class. \textit{All features mentioned in this work are $L_2$-normalized}. \begin{algorithm}[!ht] \caption{Training a CatNet for EgoGesture} \label{al:icarl} \begin{algorithmic}[1] \item[\textbf{Input:}] \begin{itemize} \Statex \item $m$ \Comment \textit{Number of added new classes} \Statex \item $\mathbf{X} \in \mathbb{R}^{N \times C \times L \times H \times W}$, $\mathbf{Y} \in \mathbb{R}^{N \times m}$ \Comment \textit{New- class video clips and labels, $N$ number of clips, $C$ number of channels, $L$ clip length, $H$ frame height, $W$ frame width} \Statex \item $K$ cached samples for each previous class \Comment \textit{$\mathbf{X}_{cached} \in \mathbb{R}^{P \times C \times L \times H \times W}$ where $P = K \times n$, $n$ is number of learned classes} \end{itemize} \item[\textbf{Require:}] \begin{itemize} \Statex \item Current model $\mathcal{M}$ and weights $\mathbf{\Theta}$ \Comment \textit{We denote the first layer weight until the last layer weight as $\Theta_1, \Theta_2, \ldots, \Theta_t$} \end{itemize} \item[\textbf{Training starts:}] \Statex $q = \mathcal{M}(\mathbf{X}_{cached}, \Theta_{1\sim t})$ \Comment \textit{Softmax prediction for previous samples} \Statex Optimizing (e.g., BackProp) with loss function below: \Statex $\mathcal{L} = $ \Statex $-\sum_{x_i\in X, y_i\in Y}\sum_{j=1}^m y_{i,j}\log(\mathcal{M}(x_i, \Theta_{1\sim t}))- $ \Statex $\sum_{x_i\in X_{cached}, q_i\in q}\sum_{j=1}^P q_{i,j}\log(\mathcal{M}(x_i, \Theta_{1\sim t}))$ \Comment \textit{This contains the new-class cross entropy loss and the old-class distillation loss.} \item[\textbf{Training finishes}] \end{algorithmic} \end{algorithm} \begin{algorithm}[!ht] \caption{Learning the Feature Representation} \label{al:icarl-cache-sample} \begin{algorithmic}[1] \item[\textbf{Input:}] \begin{itemize} \Statex \item $\mathbf{X} \in \mathbb{R}^{N \times C \times L \times H \times W}$ \Comment \textit{New-class video clips} \end{itemize} \item[\textbf{Repeat for $m$ classes:}] \Statex $\mathbf{X}_i \in \mathbf{X}$ \Comment \textit{Samples of one new class} \Statex $\mathcal{F} = \mathcal{M}(\mathbf{X}_i, \Theta_{1\sim t-1})$ \Comment \textit{Extract the second last layer feature for one new-class samples} \Statex $\mu \gets \frac{1}{|\mathcal{F}|}\sum_{\mathcal{F}_i\in \mathcal{F}} \mathcal{F}_i$ \skipnumber[3]{\For{$k = 1:K$} \State $p_k \gets \mathrm{argmin}_{x \in X_i} \| \mu-\frac{1}{k}(\mathcal{M}(x, \Theta_{1\sim t-1})+\sum_{j=1}^{k-1}\mathcal{M}(p_j, \Theta_{1\sim t-1}) \|$ \EndFor} \Statex $\mathbf{X}_{cached} \gets (p_1, p_2, \ldots, p_K)$ \item[\textbf{Output:}] \Statex $\mathbf{X}_{cached}$ \end{algorithmic} \end{algorithm} \begin{algorithm}[!ht] \caption{Inference} \label{al:icarl-inference} \begin{algorithmic}[1] \item[\textbf{Input:}] \begin{itemize} \Statex \item $x \in \mathbb{R}^{C \times L \times H \times W}$ \Comment \textit{Testing video clips} \end{itemize} \item[\textbf{Require:}] \Statex Trained model $\mathcal{M}$ and weights $\Theta_{1\sim t-1}$ \Statex $P=K\times n$ cached image set for all $n$ classes $\mathbf{X}=\left\{\mathbf{x}_1, \ldots, \mathbf{x}_n \right\}$, $\mathbf{x}_n \in \mathbb{R}^{K \times C \times L \times H \times W}$ \Comment \textit{Cached exemplar set} \item[\textbf{Compute exemplar feature means:}] \For{$k = 1:n$} \State $\mu_k \gets \frac{1}{K}\sum_{x_i\in \mathbf{x}_k} \mathcal{M}(x_i, \Theta_{1\sim t-1})$ \EndFor \item[\textbf{Output:}] \Statex $y \gets \text{argmin}_{k=1,\ldots, n} \|\mathcal{M}(x, \Theta_{1\sim t-1}) - \mu_k \|$ \end{algorithmic} \end{algorithm} \begin{figure}[!ht] \centering \includegraphics[width=0.45\textwidth]{testing_schematic3.png} \caption{Schematic of a two-stream CatNet for EgoGesture video recognition.} \label{fig:testing_schematic} \end{figure} Two evaluation metrics are used to validate the performance for each model during class incremental learning, which are mean accuracy and backward transfer (BWT)~\cite{she2019openloris}. Table~\ref{tab:train-test-matrix} shows an accuracy matrix $R$, which is able to observe the performance of a trained model changing over time. The row represents the model $\mathcal{M}_i$ trained on task $i$. The column represents the testing data from task $i$. The gray part is the BWT score, which measures the accuracy over previously encountered tasks (average of gray elements in Table~\ref{tab:train-test-matrix}). BWT indicates the performance related to the memorization capability. The mean accuracy, average of last row elements in Table~\ref{tab:train-test-matrix}, demonstrates the overall performance on each task for the final model. \begin{table}[!ht] \centering \caption{Accuracy matrix $R$ during lifelong training, where $\mathcal{M}_i$ is the model trained using training data $Tr_i$ in task $T_i$, $Te_i$ is the testing data in task $T_i$, and $R_{ij} = $ classification accuracy of the model $\mathcal{M}_i$ training on $Tr_{i}$ and testing on $Te_{j}$. The number of tasks is $N$. Gray color represents the BWT score.} \begin{tabular}{c|cccc} \toprule $R$ & $Te_{1}$ & $Te_{2}$ & $\cdots$ & $Te_{N}$ \\ \hline $\mathcal{M}_{1}$ & $R_{11}$ & $R_{12}$ & $\cdots$ & $R_{1N}$ \\ $\mathcal{M}_{2}$ & \cellcolor{Gray}$R_{21}$ & $R_{22}$ & $\cdots$ & $R_{2N}$ \\ $\cdots$ & \cellcolor{Gray}$\cdots$ & \cellcolor{Gray}$\cdots$ & $\cdots$ & $\cdots$ \\ $\mathcal{M}_{N}$ & \cellcolor{Gray} $R_{N1}$ & \cellcolor{Gray}$R_{N2}$ & \cellcolor{Gray}$\cdots$ & $R_{NN}$ \\ \bottomrule \end{tabular} \label{tab:train-test-matrix} \end{table} \section{Experiments} In this section, we describe experimental evaluation in this work. All models are tested on a public egocentric gesture dataset -- EgoGesture. Details of network settings are provided in the Appendix. \subsection{EgoGesture Dataset} EgoGesture is a recent multimodal large-scale video dataset for egocentric hand gesture recognition~\cite{zhang2018egogesture}. There are 83 classes of static and dynamic gestures collected from 6 diverse indoor and outdoor scenes. There are 24,161 video gesture samples and 2,953,224 frames, which are collected in RGB and depth modalities from 50 distinct participants. We follow the previous work~\cite{zhang2018egogesture,kopuklu2019real} to process the data, in which data was split by participants into training (60\%), validation (20\%) and testing (20\%). Participant IDs 2, 9, 11, 14, 18, 19, 28, 31, 41, 47 were used for testing and 1, 7, 12, 13, 24, 29, 33, 34, 35, 37 were used for validation. The rest of data was used for training. Similar to~\cite{kopuklu2019real}, we also included validation data during training. \subsection{Class Incremental Learning} We focus on one of the lifelong learning scenarios in this study -- class incremental learning. Every time we extended the model, we added 5 new classes. In order to get good generalization for our model on class incremental learning, we firstly trained our model using the first 40 classes (we will refer this initial task as task 0 in the later part of this paper). We then trained our model using 5 new classes (41 -- 45) as task 1. We repeated this procedure until task 9, in which data of classes 81 -- 85 was used. As a result, we have 10 tasks (including the initial training on the first 40 classes) over the class incremental learning process. \subsection{Implementation Details} Three models were investigated in this work, which are ResNeXt-101-32f, ResNeXt-101-16f, ResNet-50-16f. Each model was tested by using 4 feature representations, which are depth input, RGB input, RGB and depth input (RGB-D) and two-stream. All models were first pretrained on Kinetics~\cite{kay2017kinetics,hara2018can}. Following previous work~\cite{kopuklu2019real}, we used the following methods to pre-process the data during training: (1) Each frame was firstly spatially resized to 112 $\times$ 112 pixels; (2) Each frame was scaled randomly with one of $\{1, \frac{1}{2^{1/4}}, \frac{1}{2^{3/4}}, \frac{1}{2}\}$ scales and then randomly cropped to size 112 $\times$ 112; (3) Spatial elastic displacement~\cite{simard2003best} with $\alpha = 1$ and $\sigma = 2$ was applied to cropped and scaled frames; (4) A fixed length clip (16-frame and 32-frame used in this work) was generated around the selected temporal position. If the video is shorter than the fixed length, we looped it as many times as possible; (5) We performed mean subtraction for each input channel, where mean values of ActivityNet~\cite{caba2015activitynet} were used. Finally we get the following types of inputs to our model: (1) Depth input, which has the size of 1 channel $\times$ 16/32 frames $\times$ 112 pixels $\times$ 112 pixels; (2) RGB input, which has the size of 3 channels $\times$ 16/32 frames $\times$ 112 pixels $\times$ 112 pixels; (3) RGB-D input, which has the size of 4 channels $\times$ 16/32 frames $\times$ 112 pixels $\times$ 112 pixels. Stochastic gradient descent was carried out to optimize the model when using backpropagation, which has a weight decay of $0.001$ and 0.9 for momentum. For task 0 training (first 40 classes), the learning rate was started from $0.001$ and divided by 10 at the 25th epoch. Training was completed after 50 epochs. For class incremental learning, the learning rate was started from $0.001$ and divided by 10 at the 6th epoch. Training was completed after 12 epochs. Batch size was set to 64 in the experiment. During the testing session, testing frames were first scaled to the size of 112 $\times$ 112 and then cropped around a central position at scale 1. A testing video clip (with length 16 or 32) was generated at the central temporal position of a whole video. If the testing video clip was shorter than the required length, we looped it as many times as necessary. All testing frames were mean centered the same way those used for training. \section{Results} The presentation of results is divided into two parts. The first part compares the performance of different feature representations i.e., depth, RGB, RGB-D and two-stream. The second part compares the performance of different 3D ConvNets i.e., ResNeXt-101-32f, ResNeXt-101-16f and ResNet-50-16f. We use the joint training model as an upper bound comparison, which is trained by using the data of all classes. Mean accuracy and memorization capability are utilized to measure the performance. \subsection{Comparison of Feature Representations} \subsubsection{Final Model Accuracy for All Tasks} Table~\ref{tab:inputs-compare} shows the mean accuracy across different tasks using different feature representations. It can be noticed that the two-stream approach achieves the highest accuracy for both joint training and class incremental training for all three different architectures, which indicates that two independent feature extractors for depth and RGB inputs should be beneficial for both joint training and lifelong learning. Previous work~\cite{abavisani2019improving,cao2017egocentric,zhang2018egogesture} has demonstrated that using RGB-D can outperform those only using one modality input in terms of joint training. However, it seems that the RGB-D feature representation is not beneficial to lifelong learning as it can be noticed that the depth feature representation performs better than the RGB-D feature representation for ResNext-101-16f and ResNet-50-16f during training the CatNet. \begin{table}[!htbp] \centering \caption{Mean accuracy for different feature representations. Bold text indicates the highest accuracy} \begin{tabular}{c|c|c|c} \toprule \multicolumn{2}{c|}{Method} & {Joint training} & {CatNet}\\ \hline \multirow{4}{*}{ResNeXt-101-32f}& {Depth} & {0.909} & {0.845}\\ &{RGB} & {0.905} & {0.859}\\ &{RGB-D} & {0.922} & {0.861}\\ &{Two-stream} & {\textbf{0.932}} & {\textbf{0.884}}\\ \hline \multirow{4}{*}{ResNeXt-101-16f}& {Depth} & {0.883} & {0.840}\\ &{RGB} & {0.850} & {0.826}\\ &{RGB-D} & {0.891} & {0.834}\\ &{Two-stream} & {\textbf{0.907}} & {\textbf{0.865}}\\ \hline \multirow{4}{*}{ResNet-50-16f}& {Depth} & {0.870} & {0.843}\\ &{RGB} & {0.865} & {0.792}\\ &{RGB-D} & {0.867} & {0.830}\\ &{Two-stream} & {\textbf{0.900}} & {\textbf{0.854}}\\ \bottomrule \end{tabular} \label{tab:inputs-compare} \end{table} \subsubsection{Memorization Capability} BWT is carried out in this work for measuring the memorization capability. Table~\ref{tab:inputs-BWT} summarizes that BWT in Figure~\ref{fig-CM} (left). Compared to other feature representation approaches, the two-stream feature representation shows that the model produces lighter color in the matrix over time, which indicates a better memorization capability. Similar to the mean accuracy, the RGB-D feature representation performs worse than the depth feature representation for ResNeXt-101-16f and ResNet-50-16f. These results indicate that the one-stream CatNet is not able to fully make use of RGB-D information when only concatenating RGB and depth as an input to the model with respect to EgoGesture video recognition. Thus we provide such a two-stream strategy which shows good performance for both joint training and lifelong learning. \begin{figure*}[!ht] \begin{minipage}{.72\textwidth} \subfigure[Depth]{\includegraphics[width=.21\textwidth]{CM_resnet101_32_D.png} } \subfigure[RGB]{\includegraphics[width=.21\textwidth]{CM_resnet101_32_RGB.png} } \subfigure[RGB-D]{\includegraphics[width=.21\textwidth]{CM_resnet101_32_RGB_D.png} } \subfigure[Two-stream]{\includegraphics[width=.21\textwidth]{CM_resnet101_32_RGB_D-fusion.png}} \end{minipage} \vspace{-75pt} \begin{minipage}{.72\textwidth} \subfigure[Depth]{\includegraphics[width=.21\textwidth]{CM_resnet101_16_D.png} } \subfigure[RGB]{\includegraphics[width=.21\textwidth]{CM_resnet101_16_RGB.png} } \subfigure[RGB-D]{\includegraphics[width=.21\textwidth]{CM_resnet101_16_RGB_D.png} } \subfigure[Two-stream]{\includegraphics[width=.21\textwidth]{CM_resnet101_16_RGB_D-fusion.png} } \end{minipage} \vspace{-75pt} \hspace{-45pt} \begin{minipage}{.35\textwidth} \captionof{table}{Memorization capability across different feature representations. Bold text indicates the highest accuracy.} \label{tab:inputs-BWT} \begin{tabular}{c|c|c} \toprule \multicolumn{2}{c|}{Model} & {BWT}\\ \hline \multirow{4}{*}{ResNeXt-101-32f}& {Depth} & {0.873}\\ &{RGB} & {0.880}\\ &{RGB-D}& {0.882}\\ &{Two-stream} & {\textbf{0.900}}\\ \hline \multirow{4}{*}{ResNeXt-101-16f}& {Depth}& {0.865}\\ &{RGB} & {0.849}\\ &{RGB-D} & {0.856}\\ &{Two-stream} & {\textbf{0.887}}\\ \hline \multirow{4}{*}{ResNet-50-16f}& {Depth} & {0.863}\\ &{RGB} & {0.823}\\ &{RGB-D} & {0.853}\\ &{Two-stream}& {\textbf{0.880}}\\ \bottomrule \end{tabular} \end{minipage} \begin{minipage}{.72\textwidth} \subfigure[Depth]{\includegraphics[width=.21\textwidth]{CM_resnet50_16_D.png} } \subfigure[RGB]{\includegraphics[width=.21\textwidth]{CM_resnet50_16_RGB.png} } \subfigure[RGB-D]{\includegraphics[width=.2\textwidth]{CM_resnet50_16_RGB_D.png} } \subfigure[Two-stream]{\includegraphics[width=.21\textwidth]{CM_resnet50_16_RGB_D-fusion.png} } \end{minipage} \caption{Left: Classification accuracy matrix $R$ for three architectures i.e., ResNext-101-32f (top), ResNext-101-16f (middle) and ResNet-50-16f (bottom). The vertical axis is the model $\mathcal{M}_i$ trained on the task $T_i$. The horizontal axis is the task $T_i$ data. Lighter color indicates better performance. Right: Table summary of the figure on the left.} \label{fig-CM} \end{figure*} \subsection{Comparison of Architectures} \subsubsection{Final Model Accuracy for All Tasks} Table~\ref{tab:architecture-compare} shows the mean accuracy of joint training and class incremental training across different architectures. It can be noticed that ResNeXt-101-32f achieves the best performance for both joint training and lifelong learning across different feature representations. ResNeXt-101-32f has the same depth as ResNeXt-101-16f, but a longer temporal frame length is used for the input clip when using ResNeXt-101-32f, which is able to preserve more temporal information from videos. \begin{table}[!htbp] \caption{Comparison between architectures using mean accuracy. Bold text indicates the best performance.} \centering \begin{tabular}{c|c|c|c} \toprule \multicolumn{2}{c|}{Method} & {Joint training} & {CatNet}\\ \hline \multirow{3}{*}{Depth}& {ResNeXt-101-32f} & {\textbf{0.909}} & {\textbf{0.845}}\\ &{ResNeXt-101-16f} & {0.883} & {0.840} \\ &{ResNet-50-16f} & {0.870} & {0.843}\\ \hline \multirow{3}{*}{RGB}& {ResNeXt-101-32f} & {\textbf{0.905}} & {\textbf{0.859}}\\ &{ResNeXt-101-16f} & {0.850} & {0.826}\\ &{ResNet-50-16f} & {0.865} & {0.792}\\ \hline \multirow{3}{*}{RGB-D}& {ResNeXt-101-32f} & {\textbf{0.922}} & {\textbf{0.861}}\\ &{ResNeXt-101-16f} & {0.891} & {0.834}\\ &{ResNet-50-16f} & {0.867} & {0.830}\\ \hline \multirow{3}{*}{Two-stream}& {ResNeXt-101-32f} & {\textbf{0.932}} & {\textbf{0.884}}\\ &{ResNeXt-101-16f} & {0.907} & {0.865}\\ &{ResNet-50-16f} & {0.900} & {0.854}\\ \bottomrule \end{tabular} \label{tab:architecture-compare} \end{table} \subsubsection{Memorization Capability} Table~\ref{tab:architecture-BWT} shows BWT across three different architectures for each feature representation. The rank of BWT for each feature representation is the same, which is ResNeXt-101-32f, ResNeXt-101-16f and ResNet-50-16f from high to low. Because BWT can also be affected by the initial performance of the model i.e., initial classification performance for the first 40 classes in our case, we also test the initial classification accuracy for the first 40 classes for each model as seen in Table~\ref{tab:architecture-BWT}. The initial accuracy has exactly the same order as BWT in terms of ranking the three architectures for each representation i.e., ResNeXt-101-32f, ResNeXt-101-16f and ResNet-50-16f. This indicates that a deeper model is able to improve the initial performance on the initial task (task 0) but can not benefit the memorization capability on a lifelong learning task. \begin{table}[!htbp] \caption{Comparison between different architectures for memorization capability. Bold text indicates the best performance.} \centering \begin{tabular}{c|c|c|c} \toprule \multicolumn{2}{c|}{Model} & {BWT} & {Initial accuracy}\\ \hline \multirow{4}{*}{Depth}& {ResNeXt-101-32f} & {\textbf{0.873}} & {\textbf{0.956}}\\ &{ResNeXt-101-16f} & {0.865} & {0.928}\\ &{ResNet-50-16f} & {0.863} & {0.894}\\ \hline \multirow{4}{*}{RGB}& {ResNeXt-101-32f}& {\textbf{0.880}} & {\textbf{0.951}}\\ &{ResNeXt-101-16f} & {0.849} & {0.919}\\ &{ResNet-50-16f} & {0.823} & {0.878}\\ \hline \multirow{4}{*}{RGB-D}& {ResNeXt-101-32f}& {\textbf{0.882}} & {\textbf{0.942}}\\ &{ResNeXt-101-16f} & {0.856} & {0.939}\\ &{ResNet-50-16f} & {0.853} & {0.910}\\ \hline \multirow{4}{*}{Two-stream}& {ResNeXt-101-32f} & {\textbf{0.900}} & {\textbf{0.964}}\\ &{ResNeXt-101-16f} & {0.887} & {0.945}\\ &{ResNet-50-16f}& {0.880} & {0.915}\\ \bottomrule \end{tabular} \label{tab:architecture-BWT} \end{table} \section{Discussion} Figure~\ref{fig:feature_viz} shows the features produced by a feature mean matrix according to the depth input and the RGB input respectively for all 83 classes (horizontal represents different classes). Given a feature mean matrix $\mathcal{S} \in \mathbb{R}^{m \times c}$, where $m$ is the number of features and $c$ is the number of classes, it is not easy to visualize because of the large feature number. We average $\mathcal{S}$ over the feature dimension, which is derived as $\frac{1}{m}\sum^{m}_i \mathcal{S}_i$, for visualization. It can be seen that the depth feature representation and the RGB feature representation are quite different from each other. Because our model uses the mean exemplar set as a reference for classification, the two-stream approach, which fuses depth features and RGB features from the second last layer, can be beneficial for this case. \begin{figure}[!ht] \centering \includegraphics[width=.4\textwidth]{feature_representation} \caption{Visualization of features extracted by the two-stream CatNet.} \label{fig:feature_viz} \end{figure} \vspace{-20pt} \section{Conclusion} In this paper, we investigate class incremental learning in the context of egocentric gesture video recognition, in which we address the issue in such scenarios for real-wold applications is that may easily become necessary to add new gestures to the system. A 3D convolution based framework named CatNet is introduced and we demonstrate the efficacy of CatNets on the EgoGesture dataset, in which the performance on the class incremental task does not drop significantly compared to joint training. Importantly, we propose the use of a two-stream architecture for the CatNet, in which two 3D ConvNets are trained independently by feeding RGB and depth inputs. Results demonstrate that the two-stream CatNet performs better than 3 other one-stream CatNets both on the mean accuracy and the memorization capability. Results also demonstrate that CatNet exhibits some forgetting of knowledge, which can be further investigated in the future. {\small \bibliographystyle{ieee_fullname} \section{Introduction} \vspace{-5pt} With development and popularity of VR/AR devices recently, there is an increasing demand to work with these devices intuitively. Gestures are the most natural form for humans to interact with such type of devices, in which hand gestures can be conveniently captured by cameras integrated in the devices in first person view. This motivates accurate recognition of meaningful gestures from such egocentric gesture videos. Video recognition systems for such VR/AR applications in the real world should ideally be designed in a way to support incremental update and customization of gestures. Different communicative gestures should be customized for different VR games~\cite{yang2019gesture}. Traditional machine learning/deep learning approaches require training data of all classes accessed at the same time, which is hardly achievable in such real-world situations. For instance, when a new gesture should be added to a system, the model needs to be retrained by incorporating the gesture video samples of previous and new classes, which requires significant memory for storing all previous class videos and increasing computational cost over time. A system with capability of lifelong learning would therefore be very beneficial for such scenarios, in which incremental learning makes use of memory efficiently, enables fast learning for new class samples and does not forget the previous class samples. In this work, we demonstrate a c(\textbf{C})la(\textbf{a})ss increment(\textbf{t})al net(\textbf{Net})works (CatNet) for an open-set problem rather than a close-set problem, which learns new classes i.e., the class variants larger than instance variants. Hand-crafted features are commonly adopted in traditional video gesture recognition~\cite{liu2013learning,ohn2014hand,wan2016chalearn}. With more large-scale datasets being released and development of deep neural networks (DNNs), DNNs are playing a more and more important role in this field~\cite{kopuklu2019real,cao2017egocentric}. Different from image recognition, temporal information along each frame needs to be considered for video understanding. The 3D convolutional network (ConvNet) becomes a popular architecture for learning spatiotemporal features from video clips. Benefiting from large-scale video datasets being released~\cite{kay2017kinetics,caba2015activitynet,abu2016youtube}, deep 3D ConvNets have achieved striking results in video action recognition tasks~\cite{hara2018can,carreira2017quo,diba2017temporal}. Compared to current popular video action datasets e.g., UCF-101~\cite{soomro2012ucf101}, Kinetics~\cite{kay2017kinetics}, egocentric gesture video is in first person view, in which two modalities RGB and depth can be captured at the same time. This indicates more information can be used to train the models for the egocentric gesture video recognition. Two-stream 3D ConvNets~\cite{simonyan2014two} is proposed for video action recognition by using optical flow~\cite{dosovitskiy2015flownet} in addition to RGB frames but optical flow is difficult to compute and to use for large-scale datasets~\cite{diba2017temporal}. We evaluate our models on a recently released large-scale egocentric gesture video dataset named EgoGesture~\cite{zhang2018egogesture}, in which RGB and depth modalities are provided. Benefiting from RGB-D video, we propose a two-stream architecture that deploys RGB and depth as two streams for egocentric gesture video recognition in this work, which deals the inconsistent quality of RGB and depth frames (see Figure~\ref{fig:frame_viz}) across different scenes (6 different scenes are included in the dataset) during the recording. Figure~\ref{fig:frame_viz} shows two gesture examples in two scenes respectively i.e., in a walking state with a dynamic background on the left and in a stationary state facing a window with drastically changing sunlight on the right. It can be noticed that the quality of the RGB input and the depth input are not consistent i.e., walking and outdoor capture can result in poor depth data, while illumination changes from changing sunlight can affect distribution of RGB pixels. Fusing features produced by a two-stream architecture can mitigate this issue, which results in a better overall performance. Previous work has shown that the frame-based approaches (e.g., VGG-16) are ineffective for the EgoGesture video recognition~\cite{zhang2018egogesture} because such methods do not take account into temporal information. Video-based approaches are required for accurate recognition in this scenario. \begin{figure}[!ht] \centering \includegraphics[width=.105\textwidth]{sub1_s6_rgb1_575} \includegraphics[width=.105\textwidth]{sub1_s6_D1_575} \hspace{10pt} \includegraphics[width=.105\textwidth]{sub4_s3_rgb8_203} \includegraphics[width=.105\textwidth]{sub4_s3_D8_203} \caption{Visualization of gestures in different scenes. Left: The participant in a walking state with a dynamic background. Right: The participant in a stationary state facing a window with drastically changing sunlight.} \label{fig:frame_viz} \end{figure} Significant advances have been made recently in computer vision and deep learning tasks including object recognition, detection, segmentation, etc. However, most of the models can only be trained in a batch setting, in which training data of all object classes is required for training the model in a roll. Lifelong learning~\cite{parisi2019continual} is a strategy to enable training the model continuously. To overcome the issue addressed earlier in the context of egocentric video recognition, in which the system should be able to learn new gestures incrementally, we introduce a lifelong learning framework -- c(\textbf{C})la(\textbf{a})ss increment(\textbf{t})al net(\textbf{Net})works (CatNet), which is specifically designed for lifelong egocentric gesture video recognition based on 3D convolutional networks (ConvNets). Importantly, we propose a two-stream CatNet using RGB and depth input as separate streams, which achieves the best performance in the class incremental learning task. To summarize, our contribution are three-fold: \begin{itemize} \item To the best of our knowledge, we are the first to address the class incremental issues in the area of egocentric gesture video recognition and introduce the lifelong learning approaches to this area. \item We propose a two-stream CatNet for egocentric gesture video recognition, which treats RGB and depth as two separate streams and this type of CatNet is shown to perform best in the class incremental task. \item Our results show that CatNets can learn many classes incrementally over a long period of time i.e., the highest mean accuracy of presented CatNet has achieved 0.884. \end{itemize} \section{Related Work} We introduce some recent literature with respect to video action recognition, EgoGesture video recognition and lifelong learning in this section. \subsection{Video Action Recognition}\label{sec:video-action-recognition} The success of convolutional networks (ConvNets) in object detection~\cite{redmon2016you}, object recognition~\cite{krizhevsky2012imagenet}, panoptic segmentation~\cite{long2015fully} tasks etc. has attracted growing interest for deploying them to other areas of computer vision. Video understanding has became a very popular research area recently, which is driven by several released large-scale datasets such as Kinetics~\cite{kay2017kinetics}, YouTube-8M~\cite{abu2016youtube}, ActivityNet~\cite{caba2015activitynet} and Sports-1M~\cite{karpathy2014large}. Unlike image tasks, video tasks require not only spatial information for each frame but also temporal information for neighboring frames, which poses a challenge for traditional methods performing on image tasks. Video understanding for untrimmed video datasets e.g., ActivityNet is still very challenging today because it requires to consider the possibility of accomplishing additional tasks such as untrimmed action classification and detection. Work discussed in this paper only considers the trimmed video scenario. Many methods have been proposed for video action recognition by introducing temporal information to the model. 3D convolution has been firstly introduced in~\cite{ji20123d}, which enables 3D convolutional networks (3D ConvNets) to extract features from both spatial and temporal dimensions. With the success in learning spatiotemporal information from consecutive frames by using 3D convolutional modules, several 3D types of architectures have been proposed in this field e.g., I3D~\cite{carreira2017quo}, P3D~\cite{qiu2017learning}, T3D~\cite{diba2017temporal} and R3D~\cite{hara2018can}. The work in \cite{hara2018can} addresses that it is important to use a pretrained model that is trained on a large-scale video dataset for a specific video task, which is able to avoid issues such as overfitting, difficult to converge and long time for training. The authors also demonstrate the efficacy of using R3D (use ResNet block as backbone for 3D convolution) for video action recognition, providing good performance and flexible architectures. By using more than one modality for video action recognition, multimodal representation has achieved remarkable results~\cite{wang2016exploring,simonyan2014two,carreira2017quo,feichtenhofer2016convolutional,wang2016temporal}. A typical architecture is the two-stream ConvNet~\cite{simonyan2014two,carreira2017quo}, which uses RGB frames and optical flow~\cite{dosovitskiy2015flownet} for training two separate networks. However, the computation of optical flow is very expensive, which limits its deployment in practice~\cite{diba2017temporal}. There are lots of depth cameras available on the market with acceptable price e.g., RealSense Camera SR300, which makes RGB frames and depth maps conveniently accessible for the egocentric-like datasets e.g., EgoGesture. In this work, we apply a two-stream 3D ConvNet by using RGB frames and depth frames, where the R3D is used as the backbone for our 3D ConvNet. \subsection{Egocentric Gesture Video Recognition} Datasets Like EgoGesture \cite{cao2017egocentric, zhang2018egogesture}, GreenScreen \cite{tejo2018} pave the wave for end-to-end learnable DNN architectures to address large-scale egocentric gesture recognition problems. Cao \etal \cite{cao2017egocentric} propose a neural network architecture by using a 3D ConvNet in tandem with spatiotemporal transformer modules and a LSTM for recognizing egocentric gestures from trimmed egocentric videos. In their network design, conceptually 3D ConvNets calculate the motion features and STTMs compensate for the ego motion. Shi \etal \cite{she2019openloris} improve on this approach by replacing spatiotemporal transformer modules with spatiotemporal deformable modules to overcome the issue of non-availability of local geometric transformations. Chalasani and Smolic \cite{tejo2019} propose a different network architecture that extracts embeddings specific to ego hands which are calculated as output from their encoder and decoder based architecture, which simultaneously computes hand segmentation. The embeddings thus generated for each trimmed video are then used in LSTMs to discern the gesture present in the video. In a different approach, Abavisani \etal \cite{abavisani2019improving} propose a training strategy to use knowledge from multi-modal data to get better performance on unimodal 3D ConvNets. Unlike Cao \etal \cite{cao2017egocentric}, they train a separate network for each available modality and use a new spatiotemporal semantic alignment loss function, which they propose to share the knowledge among all the trained networks. The scope for application of recognizing gestures from trimmed videos is limited. To address this issue, K{\"o}p{\"u}kl{\"u} \etal \cite{kopuklu2019real} introduce a network architecture that could enable offline working CNN based networks to work online using a sliding window approach. However, the idea of lifelong learning for egogesture recognition has not been explored in any of the mentioned papers. Given a new gesture, the entire network has to be trained with all the gestures starting the training process from the beginning, which becomes cumbersome as the number of gestures increases incrementally. \subsection{Lifelong Learning} Current state-of-the-art DNNs have achieved impressive performance on a variety of individual tasks. However, it still remains a substantial challenge for deep learning, which is learning multiple tasks continuously. When training DNNs on a new task, a standard DNN forgets most of the information related to previously learned tasks. This phenomenon is known as ``catastrophic forgetting''~\cite{mccloskey1989catastrophic}. There are three scenarios in the area of lifelong learning~\cite{van2019three}: (1) Task incremental learning, where the task ID is provided during testing; (2) Domain incremental learning, where the task ID is not provided during testing and the model does not have to infer the task ID; and (3) Class incremental learning, the task ID is not provided during testing and the model has to infer the task ID. The first scenario is the easiest one and the model is always informed about which task is going to be performed. In this case, the model can be trained with task-specific components. A typical network for such a scenario can have a ``multi-headed'' output layer for each task and the rest of the model can be shared across tasks~\cite{van2019three}. A typical example for the second scenario is that the environment is changing e.g., image background changes but the objects remain the same for an object recognition task. The model has to solve the task but does not infer how the environment changes~\cite{feng2019challenges}. The last scenario is the most challenging one which requires the model to infer each task. For example, the model has to learn new classes of objects incrementally in an object recognition task. In this work, we focus on the most challenging scenario -- class incremental learning, where we address the importance for learning gesture classes incrementally regarding the egocentric gesture video recognition. Catastrophic forgetting appears when the new instance is significantly different from previous observed examples. Current strategies such as replay of old samples~\cite{gepperth2016bio,rebuffi2017icarl} and regularization~\cite{benna2016computational,fusi2005cascade} can be deployed to mitigate this problem. FearNet was proposed in~\cite{kemker2017fearnet}, where a generative neural network~\cite{parisi2019continual,wang2019generative,wang2019neuroscore,wang2020use} is used to create pseudo-samples that are intermixed with recently observed examples stored in its hippocampal network. PathNet~\cite{fernando2017pathnet} was proposed as an ensemble method, where a generic algorithm is used to find the optimal path through a neural network of fixed size for replication and mutation. Ideally, the lifelong learning should be triggered by the availability of short videos of single objects and performed online on the hardware with fine-grained updates, while the mainstream of methods we study are limited with much lower temporal precision as our previous sequential learning models~\cite{she2018reduced,she2019neural}. In~\cite{rebuffi2017icarl}, iCaRL was proposed to cache the most representative samples from previous classes by using representation learning, which demonstrates good performance on class incremental learning. It is also easy to be extended to any type of network architectures. Benefiting from these advantages, we incorporate iCaRL into our CatNet to realize a lifelong learning system for egocentric gesture video recognition. \section{Methodology} In this section, we first elaborate on the type of 3D ConvNets investigated in this work, which is known as R3D. Then we present a two-stream 3D ConvNet for egocentric gesture video recognition (EgoGesture dataset is used in this work). Finally we introduce a CatNet, which incorporates the class incremental learning strategy with 3D ConvNets. Two evaluation metrics are presented at the end of this section. \subsection{Architectures} Two types of R3D architectures are investigated in this work, which use ResNet and ResNeXt respectively as the block unit. The difference between ResNet and ResNeXt is refered in~\cite{hara2018can}. Three models are studied, which are ResNet-50 using 16 frames as an input (ResNet-50-16f), ResNeXt-101 using 16 frames as an input (ResNeXt-101-16f), and ResNeXt-101 using 32 frames as an input (ResNeXt-101-32f)~\cite{hara2018can,kopuklu2019real}. As mentioned earlier in the paper, temporal information is important for video understanding. 3D convolution has became a popular operation to preserve the temporal properties of a video. Figure~\ref{fig:3D-convolutional-operation} illustrates the difference between the 3D convolutional operation and the 2D convolutional operation. 2D ConvNets lose track of temporal information of the input after every convolutional operation while 3D ConvNets are able to output a video clip by feeding a video clip, which preserves the temporal information. Figure~\ref{fig:previous-3D-net} illustrates previous popular architectures for video action recognition. Previous two-stream architectures learn the temporal information by using 3D convolution and optical flow~\cite{simonyan2014two,feichtenhofer2016convolutional,carreira2017quo,dosovitskiy2015flownet}. Optical flow represents the motion over time can be calculated from every two neighboring frames. Traditional two-stream architectures all use RGB frames and optical flow as two streams. However, the computation of optical flow is very complex i.e., computing over each individual frame, which is difficult in real-world applications~\cite{diba2017temporal}. We propose the use of depth frames as another stream with RGB frames for the EgoGesture dataset. It should be noticed that, differing from optical flow, the objective of the depth stream is not to extract temporal information. It aims to provide the depth level, in which different backgrounds e.g., brightness, indoor and outdoor in EgoGesture may drive different effects on RGB frames. The temporal information can be preserved by using 3D convolution. Figure~\ref{fig:two-stream-model} shows the two-stream architecture deployed in this work. Two 3D ConvNets are trained independently by using RGB and depth videos (see the training flow in Figure~\ref{fig:two-stream-model}) and the second last layer features of two networks are concatenated with each other (see the testing flow in Figure~\ref{fig:two-stream-model}), which is used for clustering during testing (we will explain this in the next section). \begin{figure*} \begin{minipage}{0.65\linewidth} \subfigure[Comparison between 2D and 3D convolutional operations. Left: 2D convolution on an image, in which the output is an image. Middle: 2D convolution on a video clip, in which the output is an image. Right: 3D convolution on a video clip, in which the output is also a video clip. Figure from~\cite{tran2015learning}.]{\includegraphics[width=0.55\textwidth]{3D_convolution_operation}\label{fig:3D-convolutional-operation}} \hspace{5pt} \subfigure[Previous two-stream video architectures in the literature. K stands for the total number of frames in a video while N stands for a subset of neighboring frames of the video. Figure from~\cite{carreira2017quo}.]{\includegraphics[width=0.55\textwidth]{previous_3D_net}\label{fig:previous-3D-net}} \end{minipage} \hspace{-.8cm} \begin{minipage}{0.5\linewidth} \centering \subfigure[Two-stream 3D ConvNet used in this work. ]{\includegraphics[width=0.5\textwidth]{two_stream_model}\label{fig:two-stream-model}} \end{minipage} \caption{Illustration of 3D ConvNets and the two-stream 3D ConvNet used in this work.} \label{fig:Illustration-3D-convolutional-networks} \end{figure*} \subsection{CatNet} We incorporate iCaRL~\cite{rebuffi2017icarl} with 3D ConvNets for class incremental EgoGesture video recognition in this work and we call this framework CatNet. The whole training process for a CatNet is summarized in Algorithm~\ref{al:icarl} and Algorithm~\ref{al:icarl-cache-sample} and is visualized in Figure~\ref{fig:testing_schematic}. The core part of CatNet is to cache some previous class samples that are the most representative of the old class i.e., see the green block in Figure~\ref{fig:testing_schematic}. The memory caches the selected video samples and their corresponding predictions for previous class samples, which is achieved by learning the \textbf{feature representation} (Algorithm~\ref{al:icarl-cache-sample}). The feature representation is computed by the mean value of features (i.e., the second last layer output of the 3D ConvNet) corresponding to one class (see the feature mean matrix in Figure~\ref{fig:testing_schematic}). We then cache the first $k$ samples in which features of those samples are the closest to the representation (feature mean). The cached samples play two roles during the class incremental learning. First, the cached samples are used to compute the representation for each class, which is used for inference (see the nearest mean classifier in Figure~\ref{fig:testing_schematic}). Second, the prediction is used to compute the distillation loss during the training in Algorithm~\ref{al:icarl}. The inference procedure is summarized in Algorithm~\ref{al:icarl-inference} and the yellow block Figure~\ref{fig:testing_schematic}. The feature is extracted from a testing video, which is to be compared with the cached feature mean matrix. The class minimizing the $L_2$ distance is assigned as the predicted class. \textit{All features mentioned in this work are $L_2$-normalized}. \begin{algorithm}[!ht] \caption{Training a CatNet for EgoGesture} \label{al:icarl} \begin{algorithmic}[1] \item[\textbf{Input:}] \begin{itemize} \Statex \item $m$ \Comment \textit{Number of added new classes} \Statex \item $\mathbf{X} \in \mathbb{R}^{N \times C \times L \times H \times W}$, $\mathbf{Y} \in \mathbb{R}^{N \times m}$ \Comment \textit{New- class video clips and labels, $N$ number of clips, $C$ number of channels, $L$ clip length, $H$ frame height, $W$ frame width} \Statex \item $K$ cached samples for each previous class \Comment \textit{$\mathbf{X}_{cached} \in \mathbb{R}^{P \times C \times L \times H \times W}$ where $P = K \times n$, $n$ is number of learned classes} \end{itemize} \item[\textbf{Require:}] \begin{itemize} \Statex \item Current model $\mathcal{M}$ and weights $\mathbf{\Theta}$ \Comment \textit{We denote the first layer weight until the last layer weight as $\Theta_1, \Theta_2, \ldots, \Theta_t$} \end{itemize} \item[\textbf{Training starts:}] \Statex $q = \mathcal{M}(\mathbf{X}_{cached}, \Theta_{1\sim t})$ \Comment \textit{Softmax prediction for previous samples} \Statex Optimizing (e.g., BackProp) with loss function below: \Statex $\mathcal{L} = $ \Statex $-\sum_{x_i\in X, y_i\in Y}\sum_{j=1}^m y_{i,j}\log(\mathcal{M}(x_i, \Theta_{1\sim t}))- $ \Statex $\sum_{x_i\in X_{cached}, q_i\in q}\sum_{j=1}^P q_{i,j}\log(\mathcal{M}(x_i, \Theta_{1\sim t}))$ \Comment \textit{This contains the new-class cross entropy loss and the old-class distillation loss.} \item[\textbf{Training finishes}] \end{algorithmic} \end{algorithm} \begin{algorithm}[!ht] \caption{Learning the Feature Representation} \label{al:icarl-cache-sample} \begin{algorithmic}[1] \item[\textbf{Input:}] \begin{itemize} \Statex \item $\mathbf{X} \in \mathbb{R}^{N \times C \times L \times H \times W}$ \Comment \textit{New-class video clips} \end{itemize} \item[\textbf{Repeat for $m$ classes:}] \Statex $\mathbf{X}_i \in \mathbf{X}$ \Comment \textit{Samples of one new class} \Statex $\mathcal{F} = \mathcal{M}(\mathbf{X}_i, \Theta_{1\sim t-1})$ \Comment \textit{Extract the second last layer feature for one new-class samples} \Statex $\mu \gets \frac{1}{|\mathcal{F}|}\sum_{\mathcal{F}_i\in \mathcal{F}} \mathcal{F}_i$ \skipnumber[3]{\For{$k = 1:K$} \State $p_k \gets \mathrm{argmin}_{x \in X_i} \| \mu-\frac{1}{k}(\mathcal{M}(x, \Theta_{1\sim t-1})+\sum_{j=1}^{k-1}\mathcal{M}(p_j, \Theta_{1\sim t-1}) \|$ \EndFor} \Statex $\mathbf{X}_{cached} \gets (p_1, p_2, \ldots, p_K)$ \item[\textbf{Output:}] \Statex $\mathbf{X}_{cached}$ \end{algorithmic} \end{algorithm} \begin{algorithm}[!ht] \caption{Inference} \label{al:icarl-inference} \begin{algorithmic}[1] \item[\textbf{Input:}] \begin{itemize} \Statex \item $x \in \mathbb{R}^{C \times L \times H \times W}$ \Comment \textit{Testing video clips} \end{itemize} \item[\textbf{Require:}] \Statex Trained model $\mathcal{M}$ and weights $\Theta_{1\sim t-1}$ \Statex $P=K\times n$ cached image set for all $n$ classes $\mathbf{X}=\left\{\mathbf{x}_1, \ldots, \mathbf{x}_n \right\}$, $\mathbf{x}_n \in \mathbb{R}^{K \times C \times L \times H \times W}$ \Comment \textit{Cached exemplar set} \item[\textbf{Compute exemplar feature means:}] \For{$k = 1:n$} \State $\mu_k \gets \frac{1}{K}\sum_{x_i\in \mathbf{x}_k} \mathcal{M}(x_i, \Theta_{1\sim t-1})$ \EndFor \item[\textbf{Output:}] \Statex $y \gets \text{argmin}_{k=1,\ldots, n} \|\mathcal{M}(x, \Theta_{1\sim t-1}) - \mu_k \|$ \end{algorithmic} \end{algorithm} \begin{figure}[!ht] \centering \includegraphics[width=0.45\textwidth]{testing_schematic3.png} \caption{Schematic of a two-stream CatNet for EgoGesture video recognition.} \label{fig:testing_schematic} \end{figure} Two evaluation metrics are used to validate the performance for each model during class incremental learning, which are mean accuracy and backward transfer (BWT)~\cite{she2019openloris}. Table~\ref{tab:train-test-matrix} shows an accuracy matrix $R$, which is able to observe the performance of a trained model changing over time. The row represents the model $\mathcal{M}_i$ trained on task $i$. The column represents the testing data from task $i$. The gray part is the BWT score, which measures the accuracy over previously encountered tasks (average of gray elements in Table~\ref{tab:train-test-matrix}). BWT indicates the performance related to the memorization capability. The mean accuracy, average of last row elements in Table~\ref{tab:train-test-matrix}, demonstrates the overall performance on each task for the final model. \begin{table}[!ht] \centering \caption{Accuracy matrix $R$ during lifelong training, where $\mathcal{M}_i$ is the model trained using training data $Tr_i$ in task $T_i$, $Te_i$ is the testing data in task $T_i$, and $R_{ij} = $ classification accuracy of the model $\mathcal{M}_i$ training on $Tr_{i}$ and testing on $Te_{j}$. The number of tasks is $N$. Gray color represents the BWT score.} \begin{tabular}{c|cccc} \toprule $R$ & $Te_{1}$ & $Te_{2}$ & $\cdots$ & $Te_{N}$ \\ \hline $\mathcal{M}_{1}$ & $R_{11}$ & $R_{12}$ & $\cdots$ & $R_{1N}$ \\ $\mathcal{M}_{2}$ & \cellcolor{Gray}$R_{21}$ & $R_{22}$ & $\cdots$ & $R_{2N}$ \\ $\cdots$ & \cellcolor{Gray}$\cdots$ & \cellcolor{Gray}$\cdots$ & $\cdots$ & $\cdots$ \\ $\mathcal{M}_{N}$ & \cellcolor{Gray} $R_{N1}$ & \cellcolor{Gray}$R_{N2}$ & \cellcolor{Gray}$\cdots$ & $R_{NN}$ \\ \bottomrule \end{tabular} \label{tab:train-test-matrix} \end{table} \section{Experiments} In this section, we describe experimental evaluation in this work. All models are tested on a public egocentric gesture dataset -- EgoGesture. Details of network settings are provided in the Appendix. \subsection{EgoGesture Dataset} EgoGesture is a recent multimodal large-scale video dataset for egocentric hand gesture recognition~\cite{zhang2018egogesture}. There are 83 classes of static and dynamic gestures collected from 6 diverse indoor and outdoor scenes. There are 24,161 video gesture samples and 2,953,224 frames, which are collected in RGB and depth modalities from 50 distinct participants. We follow the previous work~\cite{zhang2018egogesture,kopuklu2019real} to process the data, in which data was split by participants into training (60\%), validation (20\%) and testing (20\%). Participant IDs 2, 9, 11, 14, 18, 19, 28, 31, 41, 47 were used for testing and 1, 7, 12, 13, 24, 29, 33, 34, 35, 37 were used for validation. The rest of data was used for training. Similar to~\cite{kopuklu2019real}, we also included validation data during training. \subsection{Class Incremental Learning} We focus on one of the lifelong learning scenarios in this study -- class incremental learning. Every time we extended the model, we added 5 new classes. In order to get good generalization for our model on class incremental learning, we firstly trained our model using the first 40 classes (we will refer this initial task as task 0 in the later part of this paper). We then trained our model using 5 new classes (41 -- 45) as task 1. We repeated this procedure until task 9, in which data of classes 81 -- 85 was used. As a result, we have 10 tasks (including the initial training on the first 40 classes) over the class incremental learning process. \subsection{Implementation Details} Three models were investigated in this work, which are ResNeXt-101-32f, ResNeXt-101-16f, ResNet-50-16f. Each model was tested by using 4 feature representations, which are depth input, RGB input, RGB and depth input (RGB-D) and two-stream. All models were first pretrained on Kinetics~\cite{kay2017kinetics,hara2018can}. Following previous work~\cite{kopuklu2019real}, we used the following methods to pre-process the data during training: (1) Each frame was firstly spatially resized to 112 $\times$ 112 pixels; (2) Each frame was scaled randomly with one of $\{1, \frac{1}{2^{1/4}}, \frac{1}{2^{3/4}}, \frac{1}{2}\}$ scales and then randomly cropped to size 112 $\times$ 112; (3) Spatial elastic displacement~\cite{simard2003best} with $\alpha = 1$ and $\sigma = 2$ was applied to cropped and scaled frames; (4) A fixed length clip (16-frame and 32-frame used in this work) was generated around the selected temporal position. If the video is shorter than the fixed length, we looped it as many times as possible; (5) We performed mean subtraction for each input channel, where mean values of ActivityNet~\cite{caba2015activitynet} were used. Finally we get the following types of inputs to our model: (1) Depth input, which has the size of 1 channel $\times$ 16/32 frames $\times$ 112 pixels $\times$ 112 pixels; (2) RGB input, which has the size of 3 channels $\times$ 16/32 frames $\times$ 112 pixels $\times$ 112 pixels; (3) RGB-D input, which has the size of 4 channels $\times$ 16/32 frames $\times$ 112 pixels $\times$ 112 pixels. Stochastic gradient descent was carried out to optimize the model when using backpropagation, which has a weight decay of $0.001$ and 0.9 for momentum. For task 0 training (first 40 classes), the learning rate was started from $0.001$ and divided by 10 at the 25th epoch. Training was completed after 50 epochs. For class incremental learning, the learning rate was started from $0.001$ and divided by 10 at the 6th epoch. Training was completed after 12 epochs. Batch size was set to 64 in the experiment. During the testing session, testing frames were first scaled to the size of 112 $\times$ 112 and then cropped around a central position at scale 1. A testing video clip (with length 16 or 32) was generated at the central temporal position of a whole video. If the testing video clip was shorter than the required length, we looped it as many times as necessary. All testing frames were mean centered the same way those used for training. \section{Results} The presentation of results is divided into two parts. The first part compares the performance of different feature representations i.e., depth, RGB, RGB-D and two-stream. The second part compares the performance of different 3D ConvNets i.e., ResNeXt-101-32f, ResNeXt-101-16f and ResNet-50-16f. We use the joint training model as an upper bound comparison, which is trained by using the data of all classes. Mean accuracy and memorization capability are utilized to measure the performance. \subsection{Comparison of Feature Representations} \subsubsection{Final Model Accuracy for All Tasks} Table~\ref{tab:inputs-compare} shows the mean accuracy across different tasks using different feature representations. It can be noticed that the two-stream approach achieves the highest accuracy for both joint training and class incremental training for all three different architectures, which indicates that two independent feature extractors for depth and RGB inputs should be beneficial for both joint training and lifelong learning. Previous work~\cite{abavisani2019improving,cao2017egocentric,zhang2018egogesture} has demonstrated that using RGB-D can outperform those only using one modality input in terms of joint training. However, it seems that the RGB-D feature representation is not beneficial to lifelong learning as it can be noticed that the depth feature representation performs better than the RGB-D feature representation for ResNext-101-16f and ResNet-50-16f during training the CatNet. \begin{table}[!htbp] \centering \caption{Mean accuracy for different feature representations. Bold text indicates the highest accuracy} \begin{tabular}{c|c|c|c} \toprule \multicolumn{2}{c|}{Method} & {Joint training} & {CatNet}\\ \hline \multirow{4}{*}{ResNeXt-101-32f}& {Depth} & {0.909} & {0.845}\\ &{RGB} & {0.905} & {0.859}\\ &{RGB-D} & {0.922} & {0.861}\\ &{Two-stream} & {\textbf{0.932}} & {\textbf{0.884}}\\ \hline \multirow{4}{*}{ResNeXt-101-16f}& {Depth} & {0.883} & {0.840}\\ &{RGB} & {0.850} & {0.826}\\ &{RGB-D} & {0.891} & {0.834}\\ &{Two-stream} & {\textbf{0.907}} & {\textbf{0.865}}\\ \hline \multirow{4}{*}{ResNet-50-16f}& {Depth} & {0.870} & {0.843}\\ &{RGB} & {0.865} & {0.792}\\ &{RGB-D} & {0.867} & {0.830}\\ &{Two-stream} & {\textbf{0.900}} & {\textbf{0.854}}\\ \bottomrule \end{tabular} \label{tab:inputs-compare} \end{table} \subsubsection{Memorization Capability} BWT is carried out in this work for measuring the memorization capability. Table~\ref{tab:inputs-BWT} summarizes that BWT in Figure~\ref{fig-CM} (left). Compared to other feature representation approaches, the two-stream feature representation shows that the model produces lighter color in the matrix over time, which indicates a better memorization capability. Similar to the mean accuracy, the RGB-D feature representation performs worse than the depth feature representation for ResNeXt-101-16f and ResNet-50-16f. These results indicate that the one-stream CatNet is not able to fully make use of RGB-D information when only concatenating RGB and depth as an input to the model with respect to EgoGesture video recognition. Thus we provide such a two-stream strategy which shows good performance for both joint training and lifelong learning. \begin{figure*}[!ht] \begin{minipage}{.72\textwidth} \subfigure[Depth]{\includegraphics[width=.21\textwidth]{CM_resnet101_32_D.png} } \subfigure[RGB]{\includegraphics[width=.21\textwidth]{CM_resnet101_32_RGB.png} } \subfigure[RGB-D]{\includegraphics[width=.21\textwidth]{CM_resnet101_32_RGB_D.png} } \subfigure[Two-stream]{\includegraphics[width=.21\textwidth]{CM_resnet101_32_RGB_D-fusion.png}} \end{minipage} \vspace{-75pt} \begin{minipage}{.72\textwidth} \subfigure[Depth]{\includegraphics[width=.21\textwidth]{CM_resnet101_16_D.png} } \subfigure[RGB]{\includegraphics[width=.21\textwidth]{CM_resnet101_16_RGB.png} } \subfigure[RGB-D]{\includegraphics[width=.21\textwidth]{CM_resnet101_16_RGB_D.png} } \subfigure[Two-stream]{\includegraphics[width=.21\textwidth]{CM_resnet101_16_RGB_D-fusion.png} } \end{minipage} \vspace{-75pt} \hspace{-45pt} \begin{minipage}{.35\textwidth} \captionof{table}{Memorization capability across different feature representations. Bold text indicates the highest accuracy.} \label{tab:inputs-BWT} \begin{tabular}{c|c|c} \toprule \multicolumn{2}{c|}{Model} & {BWT}\\ \hline \multirow{4}{*}{ResNeXt-101-32f}& {Depth} & {0.873}\\ &{RGB} & {0.880}\\ &{RGB-D}& {0.882}\\ &{Two-stream} & {\textbf{0.900}}\\ \hline \multirow{4}{*}{ResNeXt-101-16f}& {Depth}& {0.865}\\ &{RGB} & {0.849}\\ &{RGB-D} & {0.856}\\ &{Two-stream} & {\textbf{0.887}}\\ \hline \multirow{4}{*}{ResNet-50-16f}& {Depth} & {0.863}\\ &{RGB} & {0.823}\\ &{RGB-D} & {0.853}\\ &{Two-stream}& {\textbf{0.880}}\\ \bottomrule \end{tabular} \end{minipage} \begin{minipage}{.72\textwidth} \subfigure[Depth]{\includegraphics[width=.21\textwidth]{CM_resnet50_16_D.png} } \subfigure[RGB]{\includegraphics[width=.21\textwidth]{CM_resnet50_16_RGB.png} } \subfigure[RGB-D]{\includegraphics[width=.2\textwidth]{CM_resnet50_16_RGB_D.png} } \subfigure[Two-stream]{\includegraphics[width=.21\textwidth]{CM_resnet50_16_RGB_D-fusion.png} } \end{minipage} \caption{Left: Classification accuracy matrix $R$ for three architectures i.e., ResNext-101-32f (top), ResNext-101-16f (middle) and ResNet-50-16f (bottom). The vertical axis is the model $\mathcal{M}_i$ trained on the task $T_i$. The horizontal axis is the task $T_i$ data. Lighter color indicates better performance. Right: Table summary of the figure on the left.} \label{fig-CM} \end{figure*} \subsection{Comparison of Architectures} \subsubsection{Final Model Accuracy for All Tasks} Table~\ref{tab:architecture-compare} shows the mean accuracy of joint training and class incremental training across different architectures. It can be noticed that ResNeXt-101-32f achieves the best performance for both joint training and lifelong learning across different feature representations. ResNeXt-101-32f has the same depth as ResNeXt-101-16f, but a longer temporal frame length is used for the input clip when using ResNeXt-101-32f, which is able to preserve more temporal information from videos. \begin{table}[!htbp] \caption{Comparison between architectures using mean accuracy. Bold text indicates the best performance.} \centering \begin{tabular}{c|c|c|c} \toprule \multicolumn{2}{c|}{Method} & {Joint training} & {CatNet}\\ \hline \multirow{3}{*}{Depth}& {ResNeXt-101-32f} & {\textbf{0.909}} & {\textbf{0.845}}\\ &{ResNeXt-101-16f} & {0.883} & {0.840} \\ &{ResNet-50-16f} & {0.870} & {0.843}\\ \hline \multirow{3}{*}{RGB}& {ResNeXt-101-32f} & {\textbf{0.905}} & {\textbf{0.859}}\\ &{ResNeXt-101-16f} & {0.850} & {0.826}\\ &{ResNet-50-16f} & {0.865} & {0.792}\\ \hline \multirow{3}{*}{RGB-D}& {ResNeXt-101-32f} & {\textbf{0.922}} & {\textbf{0.861}}\\ &{ResNeXt-101-16f} & {0.891} & {0.834}\\ &{ResNet-50-16f} & {0.867} & {0.830}\\ \hline \multirow{3}{*}{Two-stream}& {ResNeXt-101-32f} & {\textbf{0.932}} & {\textbf{0.884}}\\ &{ResNeXt-101-16f} & {0.907} & {0.865}\\ &{ResNet-50-16f} & {0.900} & {0.854}\\ \bottomrule \end{tabular} \label{tab:architecture-compare} \end{table} \subsubsection{Memorization Capability} Table~\ref{tab:architecture-BWT} shows BWT across three different architectures for each feature representation. The rank of BWT for each feature representation is the same, which is ResNeXt-101-32f, ResNeXt-101-16f and ResNet-50-16f from high to low. Because BWT can also be affected by the initial performance of the model i.e., initial classification performance for the first 40 classes in our case, we also test the initial classification accuracy for the first 40 classes for each model as seen in Table~\ref{tab:architecture-BWT}. The initial accuracy has exactly the same order as BWT in terms of ranking the three architectures for each representation i.e., ResNeXt-101-32f, ResNeXt-101-16f and ResNet-50-16f. This indicates that a deeper model is able to improve the initial performance on the initial task (task 0) but can not benefit the memorization capability on a lifelong learning task. \begin{table}[!htbp] \caption{Comparison between different architectures for memorization capability. Bold text indicates the best performance.} \centering \begin{tabular}{c|c|c|c} \toprule \multicolumn{2}{c|}{Model} & {BWT} & {Initial accuracy}\\ \hline \multirow{4}{*}{Depth}& {ResNeXt-101-32f} & {\textbf{0.873}} & {\textbf{0.956}}\\ &{ResNeXt-101-16f} & {0.865} & {0.928}\\ &{ResNet-50-16f} & {0.863} & {0.894}\\ \hline \multirow{4}{*}{RGB}& {ResNeXt-101-32f}& {\textbf{0.880}} & {\textbf{0.951}}\\ &{ResNeXt-101-16f} & {0.849} & {0.919}\\ &{ResNet-50-16f} & {0.823} & {0.878}\\ \hline \multirow{4}{*}{RGB-D}& {ResNeXt-101-32f}& {\textbf{0.882}} & {\textbf{0.942}}\\ &{ResNeXt-101-16f} & {0.856} & {0.939}\\ &{ResNet-50-16f} & {0.853} & {0.910}\\ \hline \multirow{4}{*}{Two-stream}& {ResNeXt-101-32f} & {\textbf{0.900}} & {\textbf{0.964}}\\ &{ResNeXt-101-16f} & {0.887} & {0.945}\\ &{ResNet-50-16f}& {0.880} & {0.915}\\ \bottomrule \end{tabular} \label{tab:architecture-BWT} \end{table} \section{Discussion} Figure~\ref{fig:feature_viz} shows the features produced by a feature mean matrix according to the depth input and the RGB input respectively for all 83 classes (horizontal represents different classes). Given a feature mean matrix $\mathcal{S} \in \mathbb{R}^{m \times c}$, where $m$ is the number of features and $c$ is the number of classes, it is not easy to visualize because of the large feature number. We average $\mathcal{S}$ over the feature dimension, which is derived as $\frac{1}{m}\sum^{m}_i \mathcal{S}_i$, for visualization. It can be seen that the depth feature representation and the RGB feature representation are quite different from each other. Because our model uses the mean exemplar set as a reference for classification, the two-stream approach, which fuses depth features and RGB features from the second last layer, can be beneficial for this case. \begin{figure}[!ht] \centering \includegraphics[width=.4\textwidth]{feature_representation} \caption{Visualization of features extracted by the two-stream CatNet.} \label{fig:feature_viz} \end{figure} \vspace{-20pt} \section{Conclusion} In this paper, we investigate class incremental learning in the context of egocentric gesture video recognition, in which we address the issue in such scenarios for real-wold applications is that may easily become necessary to add new gestures to the system. A 3D convolution based framework named CatNet is introduced and we demonstrate the efficacy of CatNets on the EgoGesture dataset, in which the performance on the class incremental task does not drop significantly compared to joint training. Importantly, we propose the use of a two-stream architecture for the CatNet, in which two 3D ConvNets are trained independently by feeding RGB and depth inputs. Results demonstrate that the two-stream CatNet performs better than 3 other one-stream CatNets both on the mean accuracy and the memorization capability. Results also demonstrate that CatNet exhibits some forgetting of knowledge, which can be further investigated in the future. {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2020-04-21T02:25:35', 'yymm': '2004', 'arxiv_id': '2004.09215', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09215'}
arxiv
\section{Introduction} Strong cryptographic algorithms rely on sensitive data that must be kept hidden and confidential. Nowadays, the most practical attacks against data encryption programs, full disk encryption layers (FDEs), authentication protocols, or secure communication channels are based on memory disclosure techniques that extract keys, hidden configurations, or unencrypted data directly from the RAM memory cells of the running systems. Consider, for an example, the (in)famous OpenSSL's Heartbleed vulnerability \cite{heartbleed} that in 2014 allowed a remote attacker to extract secret keys of X.509 certificates used for SSL/TLS secure network protocols. Even worse, also properly implemented cryptographic programs are usually vulnerable to the class of \emph{Cold Boot attacks} \cite{coldboothot}. Basically, cryptographic programs rely on memory protection mechanisms implemented by the operating system kernel to hide the sensitive data from any unauthorized user or process in the system. The underlying assumptions, however, are that (1) overriding the operating system control implies rebooting the system, and (2) rebooting the system implies disrupting the contents of all RAM cells. While assumption (1) is correct if the operating system is bug-free, unfortunately assumption (2) does not generally hold. Modern RAM technologies, such as dynamic RAM (DRAM) and static RAM (SRAM), are based on electric charges stored in small capacitors that could retain the charge for several seconds, or even minutes, after power off. The typical Cold Boot attack, therefore, consists of power cycling the system using the reset button and quickly rebooting from a removable device into a program that extracts the RAM contents \cite{coldboot}. Cold Boot attacks are so effective that they are nowadays adopted even in digital forensic activities \cite{carbone11,vomel2012}. Many possible mitigations of Cold Boot attacks have been proposed in the past few years, however there still does not exist a full, practical solution. In fact, some proposals are based on cryptographic hardware circuits integrated in the system, which are still not widely adopted \cite{amdmet,inteltme,IntelSGX}. Other proposals are bound to specific hardware architectures \cite{tresor,armored,henson2013beyond,softme}. Moreover, many solutions are not completely transparent to the applications \cite{exzess,sugartaste,softme}. Finally, almost all proposed solutions require changes to the operating system kernel \cite{chen,cryptkeeper,ramcrypt,Huber,huber2019}. In this work we introduce \emph{MemShield}, a framework based on a general-purpose Graphic Processing Unit (GPU) that encrypts the system memory so as to mitigate the effects of Cold Boot attacks. GPUs benefits of widespread adoption and their massive parallelism may satisfy real-time demands of transparent encryption systems, providing that communication overheads are reasonable. MemShield\ is designed so as to overcome most limitations of the previous proposals. In particular, MemShield\space \begin{enumerate*}[label={(\roman*)}] \item relies on a vanilla Linux kernel and does not require kernel patches; \item it is not bound to a specific hardware architecture; \item it does not require specific cryptographic hardware, and uses widely adopted GPUs as secure encryption key store and cryptographic processor; \item it can run on legacy systems; \item it stores encrypted data in system RAM, thus not limiting the amount of protected pages; \item it allows users to select the applications to be protected; \item it does not require source code changes in the protected applications; \item it exploits dynamic linking and does not require program recompilation; \item it achieves transparent memory accesses without code instrumentation; \item it uses a modular software architecture for the cryptographic components, thus permitting to easily change, enhance, or upgrade the encryption cipher; \item it is an open-source project, available at: {\small \url{https://gitlab.com/memshield/memshield/}}. \end{enumerate*} We developed a prototype based on the GNU/Linux operating system and CUDA GPUs. It provides transparent memory encryption in user mode by using the userfaultfd Linux kernel framework. This prototype is a proof-of-concept aimed at testing the validity of MemShield's design, as well as assessing both security aspects and performances. As far as we know, MemShield\ is the first framework that achieves system memory encryption by using a GPU. Moreover, while it relies on a vanilla Linux kernel, it does not require patches to the kernel: this is also a novelty for this kind of frameworks. The article is organized as follows: in section~\ref{s:relwork} we compare MemShield\ with other solutions proposed in literature. In sections~\ref{s:design} and~\ref{s:implem} we describe design and implementation of MemShield. In section~\ref{s:san} we discuss a security analysis, while in section~\ref{s:perf} we illustrate how MemShield\ impairs the overall performances of the protected applications. Finally, in section~\ref{s:conc}, we draw some conclusions. \section{Related works} \label{s:relwork} Memory disclosure attacks, and in particular Cold Boot attacks \cite{coldboot,bauer2016,coldboothot}, are nowadays a real menace that might expose sensible information and precious data to unauthorized use or abuse. Therefore, many researchers have proposed technical solutions to mitigate the effects of this kind of attacks. Some proposals are based on the assumption that the attacker might be interested in a small portion of sensitive data, like the FDE master key used for encrypting a physical disk partition, or the private key of an open SSL connection. In these cases, an effective solution might be storing these data outside RAM, that is, in volatile hardware registers. For example, an AES encryption key could be stored in special CPU registers, such as x86\_64 SSE registers (paranoix \cite{paranoix}, AESSE \cite{aesse}), debug registers (TRESOR \cite{tresor}), profiling registers (Loop-Amnesia \cite{simmons11}), or ARM NEON registers (ARMORED \cite{armored}). Another approach is storing sensitive data in locked-down static-RAM caches or hardware transactional memories \cite{chaos2010,copker,guan2019}. However, storing sensitive data outside system RAM does not scale up, so this solution is unfeasible when the data to be protected have size larger than the storage provided by the available volatile hardware registers. An easy-to-implement mitigation for Cold Boot attacks aimed at large portions of sensitive data might be based on the power-on firmware of the system. For instance, during the initialization sequence the firmware might ask for a user password, or it might erase the contents of all RAM cells \cite{tcg}. However, these protections can be overridden, because it is generally possible to change the firmware settings by resetting them to a default configuration, for instance by inserting a jumper on the board or removing the CMOS battery \cite{gruhn2016}. Even more crucially, the Cold Boot attack might be executed by transplanting the memory chips in a suitable system with a custom firmware \cite{vomel2011,vomel2012}. It has been shown \cite{gruhn2016} that cooling down the memory chips to approximately 5~Celsius degree before transplanting them allows an attacker to recover about 99\% of the original bits. Thus, even if Cold Boot attacks can be mitigated, they cannot completely ruled out: if resourceful attackers gains access to the physical RAM chips of a running system, they are able to access the system memory contents. Therefore, the most effective protection against Cold Boot attacks is based on \emph{memory encryption}, where the contents of some (or, possibly, all) memory cells are encrypted by using one or more random keys stored in volatile hardware registers outside of the RAM chips. In order to get meaningful information from the memory dump, the attacker must either recover the encryption key(s) from the volatile hardware registers, or break the encryption cipher. Henson et al.~\cite{Henson} present a survey of hardware enhancements to support memory encryption at memory controller, bus, and caches level, protecting data transfers against eavesdropping. Ideally, memory encryption could be implemented at hardware level so as to be completely transparent to user mode applications and, in some cases, even to the operating system kernel. Nowadays, major chip manufacturers design processors with MMU-based memory encryption. For instance, Intel Software Guard Extensions (SGX) \cite{IntelSGX} allows user applications to create an encrypted memory area, called \emph{enclave}, for both code and data. Encrypted pages are stored in a page cache of limited size. Confidentiality and integrity are guaranteed even when the OS kernel is compromised. However, SGX is not designed for full memory encryption and legacy applications cannot use it without source code changes. In 2017 Intel announced Total Memory Encryption (TME)~\cite{inteltme}, a hardware extension to encrypt all RAM cells with either a global key or multiple keys; in any case, the encryption key cannot be retrieved by software. TME is currently under development. AMD's proposed solution is named Secure Memory Encryption (SME)~\cite{amdmet}: it encrypts and decrypts pages of memory if a specific flag in the page table entries is set. The encryption key is randomly generated by the hardware and loaded at boot time into the memory controller. An extension called TSME allows the hardware to perform memory encryption transparently to the OS and the user software. Mofrad et al.~\cite{sgxvssme} analyze features, security attacks, and performances of both Intel SGX and AMD SME solutions. While there is a raising interest to add support for MMU-based memory encryption solutions in the operating system kernels \cite{linuxmeapi}, these systems are still not widespread, because this technology is rather expensive and operating system support is scarce. Thus, in the past years several researchers have proposed to encrypt the memory by using frameworks exploiting either common-of-the-shelf (COTS) hardware components or custom devices. Because the MMUs lack circuits aimed at encryption, all these solutions must rely on procedures included in hypervisors or operating system kernels, so they can be collectively named \emph{software-assisted memory encryption} frameworks. In this work we propose MemShield, an innovative software solution based on COTS hardware. In software-assisted memory encryption, a typical access to a protected page triggers a chain of events like the following: \begin{enumerate*}[label={(\roman*)}] \item the ordinary MMU circuits generate a hardware event (e.g., a missing page fault); \item the user application that made the access is suspended and an OS kernel/hypervisor handler schedules the execution of a cryptographic procedure (either on a CPU, or on some custom device like a FPGA or a GPU); \item the cryptographic procedure encrypts or decrypts the data in the accessed page; \item the OS kernel/hypervisor resumes the execution of the user application.\end{enumerate*} A crucial point of this mechanism is that the encryption keys used by cryptographic ciphers must not be stored ``in clear'' on the system memory, otherwise an attacker might retrieve them and decrypt all RAM contents. Hence, software-assisted memory encryption proposals generally include, as a component, one of the already mentioned solutions for storing a limited amount of sensitive data outside of system RAM \cite{tresor,simmons11,paranoix,chaos2010,copker,guan2019}. We can reasonably expect that the performances of software-assisted memory encryption are significantly worse than those of MMU-based memory encryption. However, software-assisted memory encryption has potentially several advantages over MMU-based memory encryption: \begin{enumerate*}[label={(\roman*)}] \item it can be used on legacy systems, as well as in low-level and mid-level modern systems without dedicated circuits in the MMU; \item it might be less expensive, because CPU/MMU circuits without cryptographic support are smaller and simpler; \item it is much easier to scrutiny its design and implementation in order to look for vulnerabilities and trapdoors; \item it is much easier to fix vulnerabilities and trapdoors, or to enhance the cryptographic procedures if the need arises. \end{enumerate*} One of the first proposal for software-assisted memory encryption, although motivated by avoiding bus snooping rather than Cold Boot attacks, is in Chen et al.\@ \cite{chen}: this framework uses locked-down static cache areas or special scratchpad memories (usually found in embedded hardware) as a reserved area for encrypted data. This solution requires changes in the operating system kernel to support memory access detection and to avoid that data in the static cache are leaked into system RAM. The authors, however, do not discuss how to protect the memory encryption key from disclosure. A similar idea was explored in \cite{exzess}: the authors describe a FPGA prototype named Exzess that implements a PCIe board acting as a transparent memory proxy aimed at encryption. The encrypted data are stored on the Exzess device itself: device memory is mapped on the address space of a process, so that read and write accesses on those pages trigger decryption and encryption operations on the device, respectively. A drawback of this approach is that the size of the ``encrypted RAM'' is limited in practice by the capacity of the FPGA board. MemShield\ is quite different than these solutions because it stores the encrypted data on the system RAM. CryptKeeper \cite{cryptkeeper} is a closed-source extension to the Linux kernel swapping mechanism: user pages can be flagged as ``encrypted'' and, when their number in RAM raises above a given threshold, removed from RAM and stored in encrypted form in a swap area. However, CryptKeeper is fragile versus Cold Boot attacks because it stores the encryption key in RAM. A related idea is in Huber et al.~\cite{Huber}: the authors suggest to perform encryption of user space processes memory at suspend time, using the same key used for Full Disk Encryption (FDE). Yet another variant of this idea is presented in \cite{huber2019}, where the system memory of portable devices, like notebooks and smartphones, is encrypted by means of the ``freezer'' infrastructure of the Linux kernel. MemShield\ is aimed at protecting against Cold Boot attacks possibly performed when the system is up and running, so it has a rather different design. Henson and Taylor \cite{henson2013beyond} describe a solution based on ARM architecture that implements a microkernel exploiting a cryptographic microprocessor to handle encrypted data either in a scratchpad memory or in the system RAM. An improvement of this idea is in \cite{softme}, where the ARM TrustZone ensures that unencrypted data never leak to system RAM. The authors use the ARM Trusted Execution Environment to execute a microkernel that loads encrypted program from RAM, decrypt them, and run them safely. The framework requires patches to the general-purpose OS kernel, Linux, that handles the non-trusted programs. RamCrypt~\cite{ramcrypt} is an open-source Linux kernel extension aimed at encrypting memory at page-level granularity. It is transparent to the user applications because the decryption is automatically triggered by the page fault handler whenever an user access is attempted. RamCrypt protects anonymous pages and non-shared mapped pages of the applications. In order to ensure acceptable performances, a small number of the last recently accessed pages is kept in clear in a ``sliding window'' data structure. RamCrypt also takes care to avoid key leaks in RAM by using a slightly modified AES implementation from TRESOR~\cite{tresor}. Even if TRESOR has been shown to be vulnerable to some classes of attacks \cite{tresorhunt}, RamCrypt is still an effective mitigation against Cold Boot attacks. MemShield\ adopts some ideas from RamCrypt, mainly the encryption at page level triggered by page faults and the sliding window mechanism; however, MemShield\ does not require patches to operating system kernel, and it makes use of a GPU as a safe store and processor for the cryptographic operations. HyperCrypt \cite{hypercrypt} is similar to RamCrypt, however memory encryption is handled by a hypervisor (BitVisor) rather than a kernel program; this allows HyperCrypt to also protect kernel pages. Like RamCrypt, HyperCrypt is based on TRESOR \cite{tresor}. TransCrypt \cite{transcrypt} is similar to HyperCrypt, yet it relies on ARM Virtualization Extensions to implement a tiny encryption hypervisor. Papadopoulos et al. \cite{sugartaste} proposed a framework for software-assisted memory encryption that can protect either part of, or the whole system memory; the master key is kept in CPU debug registers, like in \cite{tresor}. The framework relies on code instrumentation to intercept load/store instructions that access memory, and it requires some patches to the operating system kernel. Finally, EncExec \cite{encexec} makes use of static caches as storage units for encryption keys and unencrypted data. Whenever a user application accesses an encrypted page, EncExec decrypts the data and locks them in the static cache so that the application can transparently get the unencrypted data. EncExec adopts an interesting approach, however it requires patches to the operating system kernel. Concerning the usage of the GPU for safely executing cryptographic routines, the seminal work is PixelVault~\cite{pixelvault}, which implements AES and RSA algorithms on the GPU by carefully storing the cryptographic keys inside the GPU registers. The main goal of that work is to implement a more secure version of the OpenSSL library in order to mitigate memory disclosure attacks. PixelVault is based on a GPU kernel that runs forever waiting for crypto operation requests submitted via a memory regions shared between CPU and GPU. As discussed in \cite{Zhu}, PixelVault is actually vulnerable to unprivileged attackers, however several authors suggested ways to enhance its approach. For instance, the authors in \cite{wang2018} propose to run CUDA cryptographic applications inside guest VMs by using a virtualized GPU; no privileged attacker on guest VMs is able to retrieve the encryption keys, because they are never stored in the guest VM memory. In \cite{graviton} the authors suggest to modify the GPU hardware to prevent the device driver from directly accessing GPU critical internal resources. In \cite{jang2019} the authors propose to use a custom interface between GPU and CPU and to extend the Intel SGX technology to execute the GPU device driver in a trusted environment that a privileged attacker cannot access. MemShield{} mitigates Cold Boot attacks, so it assumes that privileged users are trusted (consider that a privileged user might easily get a full memory dump without a Cold Boot attack). Therefore, MemShield\ just ensures that unprivileged users cannot access the GPU, thus avoiding the original PixelVault vulnerabilities. \section{Design overview} \label{s:design} MemShield\ is designed to mitigate Cold Boot attacks perpetrated by malicious actors with physical access to the machine. We assume trusted privileged users and processes, as well as safe operating system and base programs. The rationale behind MemShield{}'s design was to provide memory encryption services to multiple concurrent users logged on the same machine, using a COTS GPU as secure key store and cryptographic processor. Thus, MemShield\ does not rely on custom cryptographic circuits or specific hardware architectures. GPUs are massively parallel accelerators consisting in thousand of cores typically grouped in several \emph{compute units}. Cores in the same compute unit can communicate via \emph{shared memory}, typically implemented as a fast user programmable cache memory. Different compute units can communicate each other via \emph{global memory}, that is, the GPU's RAM. In GPU programming terminology, CPU and system RAM are referred as \emph{host}, while GPU and its RAM are referred as \emph{device}. Device code is written in special functions called \emph{kernels}. Those functions, once invoked from the host, can trigger multiple parallel executions of the same kernel function over the input, depending on how the kernel is launched. MemShield{} transparently encrypts user-space memory at page granularity and decrypts them on-demand whenever an access is attempted. There is no need to change or rebuild the source code of the protected applications. Moreover, users may select the programs to be protected, so that applications that do not handle sensitive data do not suffer any slowdown. By design, for each process and at any time, MemShield{} enforces a bounded number of pages in clear, while keeping most of them encrypted. This mechanism is based on a \emph{sliding window} and it is an effective solution against Cold Boot attacks, as already proved in \cite{ramcrypt}. Encrypted data are stored in system RAM, hence there is virtually no limit on the amount of pages that can be protected. MemShield{}'s core is a daemon that is in charge of encrypting and decrypting memory on behalf of clients. We define as \emph{client} any process interested in memory encryption services. Because GPU programming is supported by user mode tools and libraries, MemShield{} daemon runs in user mode. To support transparent memory encryption, the client that attempts to access an encrypted page must be suspended and decrypted contents for that page must be provided. In order to achieve transparent memory encryption, MemShield{} must be able to detect clients' attempts to access encrypted memory and provide decrypted contents. As a matter of fact, detection of memory accesses represents one of the most challenging aspects of the project. We chose to address this issue by using userfaultfd \cite{KERNuserfaultfd}, a framework recently added to the Linux kernel aimed at efficient page fault handling in user space. Thanks to userfaultfd, no changes are required to the operating system kernel. Currently userfaultfd is used by applications that implement memory checkpoint/restore functionality~\cite{criu} and live migration of both containers~\cite{stoyanov} and virtual machines~\cite{suetake}. MemShield\ is the first project that uses userfaultfd for memory encryption, as far as we know. In systems with a Memory Management Unit (MMU), the \emph{logical addresses} appearing in CPU instructions must be translated in \emph{physical addresses} to be used for RAM's chips programming. Translations are described by means of the \emph{page tables}, usually a per-process data structure kept by the OS kernel. Each page table entry contains a page's virtual-to-physical mapping and attributes such as protection bits (Read, Write, eXecute). A \emph{page fault} is generated by the MMU hardware if a translation is not found (\emph{missing fault}) or the wrong access type is attempted (\emph{protection fault}). This mechanism is actually used by operating systems to isolate process address spaces. In all POSIX-compliant systems there exists an established technique to detect memory accesses in user space: it consists of changing the page permissions so as to forbid any access, then executing a custom handler for the SIGSEGV signal sent by the kernel to the process at any access attempt \cite{edelson1992,cesati2015}. However, this mechanism may significantly impair the performances of the clients compared to userfaultfd. A crucial design goal of MemShield\ is transparency with respect to its clients: no change to the source code of the clients is required, and no recompilation is needed. In order to achieve this goal, we assume that clients are dynamically linked to the C library (\emph{libc}); in practice, this is almost always true. The idea is to intercept calls to the memory management functions typically provided by the \emph{libc} implementation, in order to register the client's memory areas to userfaultfd. The custom handlers of the memory management functions are collected in a user-mode library called \mbox{\emph{libMemShield}}. This library can be loaded in the client's process before the C library using the \texttt{LD\_PRELOAD} technique, so that the custom handlers override the original library symbols. Because MemShield\ must handle several concurrent clients with a single GPU, userfaultfd works in non-cooperative mode: a single user-mode process is notified of any page fault events occurring in registered clients. We call this process the MemShield's \emph{server}. The server does not perform cryptographic operations directly, because it cannot access the encryption keys stored in the GPU registers. The most straightforward way to implement this mechanism is to launch on the GPU an always-running kernel that implements a safe cipher. \subsection{Design limitations} By design, MemShield\ handles only private anonymous memory: it is not concerned with memory areas backed by files or shared among different processes. It is also based on userfaultfd, which has some constraints of its own: mainly, it cannot protect the memory area handled by \texttt{brk()} or \texttt{sbrk()}. However, MemShield\ can handle the client's stack, any memory area obtained by \texttt{malloc()}, \texttt{calloc()}, \texttt{realloc()}, as well as the anonymous memory obtained by \texttt{mmap()} and \texttt{remap()}: typically, sensitive data end up being stored in such pages. \section{Implementation details} \label{s:implem} The main activities performed by MemShield\ are: \begin{enumerate*}[label={(\roman*)}] \item memory area registration to userfaultfd, \item page fault handling, \item sliding window management, and \item GPU cryptographic operations. \end{enumerate*} \subsection{Memory area registration} When a client allocates a memory area to be protected, MemShield\ must register the corresponding set of virtual addresses to userfaultfd. In order to achieve this, libMemShield\ overrides some C library functions. For allocations performed by anonymous memory mapping (\texttt{mmap()} and analog functions), the custom wrapper just performs the original procedure and registers the obtained virtual address to userfaultfd. On the other hand, handling memory areas obtained by \texttt{malloc()} and similar functions is more demanding, because the C library might use the \texttt{brk()}/\texttt{sbrk()} system calls to perform the allocation. MemShield\ forces the C library to always use anonymous memory mapping when allocating memory by means of the \texttt{mallopt()} tuning function. The userfaultfd framework does not handle stack pages. To overcome this problem, libMemShield{} replaces original stack pages with memory allocated with \texttt{mmap()} using \texttt{sigaltstack()}. Since stack encryption could have a significant impact on overall performances of MemShield{}, encrypting stack pages can be selectively enabled or disabled by means of an environment variable. libMemShield\ also overrides the \texttt{free()} and \texttt{munmap()} functions, because it ensures that any page is filled with zeros before releasing it to the system. Of course, this is crucial to avoid leaking sensitive data in RAM. \subsection{Page fault handling} At the core of MemShield\ there is the virtual address space mechanism implemented by the operating system. Any client is allowed to access a given number of anonymous pages ``in clear'', that is, in unencrypted form. These pages belong to the address space of the client and the corresponding physical page frames are referenced in the page tables. On the other hand, the page table entries associated with encrypted pages denote missing physical pages. The physical pages storing the encrypted data belong to the server's address space, and are referenced in a per-client red-black tree sorted by virtual addresses. When a client accesses an encrypted page, the MMU raises a page fault because of the missing physical page in the client's page table. Since the corresponding virtual address has been registered to userfaultfd, the server is notified about the event. As a consequence, the server looks for the virtual address of the missing page in the client's red-black tree and retrieves the physical page containing the encrypted data. Then, the server sends the encrypted data to the GPU, which performs the decryption operation. Subsequently, the server relies on userfaultfd to resolve the client's page fault by providing a physical page containing the decrypted data. If the server does not find a virtual address in a client's red-black tree, the page is missing because it has never been accessed earlier. Therefore, the server allocates a new red-black tree node and resolves the client's page fault by providing a physical page containing all zeros. \subsection{Sliding window management} The server keeps a per-client data structure called sliding window, which is a list of virtual addresses corresponding to unencrypted anonymous pages of the client. The sliding window maximum size is configurable. When the server is going to resolve a page fault, it adds the corresponding virtual address to the sliding window. It also checks whether its size has become greater than a preconfigured maximum. In this case, it takes away the oldest unencrypted page in the sliding window, which is thus removed from the client's page tables. The server cannot operate on the address space of the client. Therefore, libMemShield\ creates at initialization time a thread called \emph{data thread}, which acts on the client's address space on behalf of the server. Correspondingly, a thread is created in the server to handle the requests of the client concurrently with those of the other clients. Server and data thread\ exchange information by means of a Unix socket and a shared memory area. The Unix socket is used only to transmit open file descriptors and control messages. MemShield\ does not send sensitive data with this socket, because the Linux implementation makes use of a kernel memory buffer which could be vulnerable to Cold Boot attacks. The shared memory area, instead, is safe, because it is composed by a single page frame in RAM, which is explicitly filled with zeros by the server as soon as a transfer is completed. When the server must drop a page from a sliding window, it sends the corresponding virtual address to the data thread. The latter provides the contents of the page, that is, the unencrypted data, to the server; then, it clears the physical pages and invokes the \texttt{MADV\_DONTNEED} command of the \texttt{madvise()} system call to remove the physical page from the page tables. The server encrypts the data by means of the GPU, and adds the encrypted page to the client's red-black tree. \subsection{GPU encryption} MemShield{} cryptographic module services the requests coming from the server using the GPU both as a secure key store and a secure processor. Any cryptographic procedure operates on a single page of 4096 bytes. The data are encrypted by using the cipher ChaCha~\cite{chacha}. This choice was motivated by the need for a cipher that is, at the same time, \begin{enumerate*}[label={(\roman*)}] \item secure, \item suitable for GPU computation, and \item simple enough so that the computation can be performed completely in GPU registers.\end{enumerate*} MemShield{} implements the strongest variant ChaCha20, which can be regarded as cryptographically safe \cite{maitra2016chosen,dey2017improved,choudhuri2016differential}. The actual encryption/decryption of a 4096-byte page is performed by \texttt{XOR}ing the data with several keystream blocks. ChaCha20 computes a 512-bit block of keystream starting from a 384-bit seed composed by a 256-bit key and a 128-bit value. In MemShield\ the 256-bit key is unique and it is generated by a cryptographically secure pseudo-random number generator provided by the operating system. This key is sent to the GPU and stored only in GPU registers, afterwards it is purged out of the server memory. The 128-bit value of the seed, which can be used both as a counter in stream ciphering and as a predefined nonce, is composed by the virtual address of the page, the process identifier (PID) of the client, and a counter ranging from 0 to 63 that corresponds to the index of the 512-bit block inside the page. Observe that the keystream blocks could be generated and \texttt{XOR}ed independently with the plaintext blocks. The ciphertext construction is thus embarrassingly parallel, which is a highly desirable feature in a GPU implementation. Another useful property is that encryption and decryption are performed with the same operations, hence the GPU kernel can use the same function for both. MemShield{} cryptographic module makes use of a NVIDIA GPU programmed by means of the CUDA toolchain \cite{CUDA2008,cudatk}. The GPU is reserved to MemShield, which means that unprivileged users cannot access the device. In practice, because the communication channel between user space and the CUDA driver is based on device files, the permissions of these device files are changed so that access is only allowed to privileged users. The GPU kernel consists of several CUDA blocks; each block acts as a \emph{worker} whose job is to extract pages from a queue and process them using 32 CUDA threads (one \emph{warp}). Each CUDA thread generates two ChaCha20 keystream blocks (128 bytes), which are then \texttt{XOR}ed with the same amount of plaintext. The number of CUDA blocks in the GPU kernel is dynamically computed at run time according to the features of the GPU board. Using more than one block allows the server to submit requests for several concurrent clients. Because the 256-bit encryption key is created at initialization time and stored inside the GPU registers, the GPU kernel cannot be terminated, otherwise the key would be lost. MemShield\ uses a mapped memory between host and device to implement a shared data structure that controls the GPU operations. The data transfer between host (server) and device (GPU) is realized through a circular buffer implementing a multiple-producer, single-consumer queue: multiple host threads can submit concurrent pages to the same queue, while those will be processed by a single worker on the GPU. Each worker has its own queue, thus the workers runs independently and concurrently. An important aspect of the implementation is that the encryption key and the internal state of the cipher are never stored in GPU local memory, otherwise MemShield\ would be vulnerable to GPU memory disclosure attacks. We verified that the current implementation of the GPU kernel never does register spilling. \subsection{Prototype limitations} The current implementation of MemShield{} is a prototype, thus it has some limitations. First of all, any protected application must be single process. There is no major obstacle to enhance MemShield\ so as to overcome this limit. Protected applications must also be single thread. It would be possible to extend MemShield\ to support multi-threaded processes whenever userfaultfd becomes capable of handling write-protect page faults. Work is in progress to integrate this feature in the vanilla Linux kernel \cite{aa.git}. MemShield\ protects all private anonymous pages. In order to have better performances, it could be preferable to selectively encrypt only the subset of pages containing sensitive data. Finally, the ChaCha20 implementation is prototypal and could be improved. \section{Security Analysis} \label{s:san} MemShield\ is an effective mitigation against Cold Boot attacks. In fact, RamCrypt's authors already proved \cite{ramcrypt} that the sliding window mechanism is an effective technique that could drastically reduce the probability to find meaningful encryption keys or other sensitive data in memory dumps. Like RamCrypt, MemShield\ makes use of one sliding window per each protected application. MemShield\ is also inspired by how PixelVault \cite{pixelvault} makes use of the GPU to safely store encryption keys and run cryptographic procedures. However, PixelVault is nowadays assumed to be vulnerable \cite{Zhu,cudaleaks}. The reported attack vectors to PixelVault were based on launching malicious kernel functions on the GPU, or running a CUDA debugger on the running GPU kernels. MemShield\ avoids these vulnerabilities because it restricts access to the GPU to privileged users. Recall that, in our threat model, privileged users and privileged processes are always regarded as trusted. MemShield\ also takes care of avoiding GPU register spilling, so that Cold Boot attacks against the GPU memory would not retrieve any sensitive data of the cryptographic procedure. Memory dumps obtained by Cold Boot attacks might expose data included in the kernel buffers associated to Unix sockets, pipes, or other process communication channels. Actually, we verified that the Linux implementation of Unix sockets is vulnerable, because the kernel never erases the associated buffers. MemShield\ carefully avoids sending sensitive data by means of Unix sockets. Rather, it makes use of shared memory, whose contents can be explicitly cleared by MemShield\ at the end of the sensitive data transmission. MemShield\ does not weaken the operating system isolation guarantees at runtime, thus the confidentiality of users' data against malicious users logged on the same system is preserved. In particular, observe that a unprivileged user cannot tamper with the server daemon, because we assumed that the operating system is safe and the server is a privileged process. A malicious user could try to interfere with MemShield's communication channels. The daemon listens on a Unix socket waiting for connection requests from clients; hence, unprivileged processes must have write permissions on this socket. However, an attacker cannot replace the socket (in order to mount a man-in-the-middle attack), because the socket interface file is placed in a directory owned by root and not writable by unprivileged users. A malicious user cannot even tamper with the shared memory area used to exchange data between client and daemon: in fact, this area is created by means of file descriptors exchanged privately through the Unix socket; the area is then mapped in the address spaces of both daemon and client. MemShield\ is not designed to protect sensitive data against DMA attacks or other side channel attacks; just consider that a successful DMA attack might break the whole operating system guarantees, while in our threat model the operating system is assumed to be sound. \section{Performance Evaluation} \label{s:perf} In order to establish the performance impact of MemShield\ prototype on protected applications, we ran some benchmarks. All tests have been executed on a workstation equipped with a 3.5~GHz Intel Core i7 4771 CPU having 4 physical and 8 logical cores, 32~GiB RAM, and a GPU NVIDIA GeForce GTX 970 (compute capability 5.2) with 4~GiB of device memory. The workstation used Slackware 14.2 as Linux distribution with kernel 4.14, \emph{glibc} version 2.23, NVIDIA driver version 418.67 and CUDA 10.1. CPU power-saving was disabled. \begin{table}[b] \centering \input{result-table-s} \vskip1em \caption{% Wall-clock execution times of single-instance benchmarks, with different sliding window sizes and without MemShield{} protection (``Baseline''). Average times and standard deviations are in seconds. Sliding window sizes are in pages. MemShield\ encrypts all private anonymous pages, including the stack. } \label{t:slw} \end{table} Two benchmarks (\emph{crypt}, and \emph{qsort}) belong to the stress-ng~\cite{stressng} test suite, version 0.09.48. \emph{crypt} consists of multiple invocations of the C library \texttt{crypt\_r()} function on data placed onto the stack. The test is executed by: {\footnotesize\begin{verbatim} $ stress-ng --crypt 1 --crypt-ops 1000 \end{verbatim}} \noindent \emph{qsort} performs multiple sorts of an array of elements allocated with \texttt{calloc()}. To sort the array, the C library function \texttt{qsort()} is used: {\footnotesize\begin{verbatim} $ stress-ng --qsort 1 --qsort-size 2048 --qsort-opts 10000 \end{verbatim}} \noindent The third benchmark is \emph{aes} from \emph{OpenSSL} suite version~1.0.2s, which operates on data structures stored in pages allocated with several calls to \texttt{malloc()} interleaved with calls to \texttt{free()}. The test consists of encrypting the Linux kernel~5.0 source archive, placed in a RAM-based filesystem, using AES-256 in CBC mode: {\footnotesize\begin{verbatim} $ openssl enc -aes-256-cbc -in linux-5.0.tar.gz -out /dev/null -k pass \end{verbatim}} \noindent Finally, the fourth benchmark is \emph{sha512} from \emph{GNU Coreutils}~1.25: it invokes \texttt{malloc()} to allocate a single buffer storing file data, then it computes the digest by storing cryptographic internal state on the stack. The test was launched on the Linux kernel~5.0 source archive placed in a RAM-based filesystem: {\footnotesize\begin{verbatim} $ sha512sum linux-5.0.tar.gz \end{verbatim}} In every test run we collected the execution times by using GNU \emph{time}~1.7; each specific test has been repeated 10 times, then average values and standard deviations have been computed. \begin{figure}[t] \centering \begin{subfigure}[b]{0.49\textwidth} \includegraphics[width=\textwidth]{aes.real.slowdown.np1.pdf} \label{fig:aes:sw} \end{subfigure} \begin{subfigure}[b]{0.49\textwidth} \includegraphics[width=\textwidth]{sha512.real.slowdown.np1.pdf} \label{fig:sha512:sw} \end{subfigure} \vskip-2.5em\includegraphics[height=1.9em]{legend.pdf}\vskip-.5em \begin{subfigure}[b]{0.49\textwidth} \includegraphics[width=\textwidth]{qsort.real.slowdown.np1.pdf} \label{fig:qsort:sw} \end{subfigure} \begin{subfigure}[b]{0.49\textwidth} \includegraphics[width=\textwidth]{crypt.real.slowdown.np1.pdf} \label{fig:crypt:sw} \end{subfigure} \vskip-3em \caption{Slowdowns of a single instance of the benchmarks relative to baseline (no MemShield) varying the sliding window size. MemShield\ protects all private anonymous pages including the stack (``Stack'') or excluding it (``no Stack''). Encryption is performed by the GPU (``GPU'') or not done at all (``no GPU'').} \label{fig:sw} \end{figure} Table~\ref{t:slw} reports how MemShield\ affects the average execution times of the four benchmarks with different sliding window configurations. Figure~\ref{fig:sw} shows the slowdowns of the four benchmarks with respect to the baseline, which is the running time without MemShield\ protection. In order to better understand how the different components of MemShield\ contribute to the overhead, any plot has four lines, which correspond to the following cases: \begin{enumerate*}[label={(\roman*)}] \item encryption on GPU of all private anonymous pages, including the stack (``GPU, Stack''), \item encryption on GPU of all private anonymous pages, excluding the stack (``GPU, no Stack''), \item no encryption at all (the GPU is not involved in handling the protected pages, thus MemShield\ server stores the pages in clear), but handling of all private anonymous pages, including the stack (``no GPU, Stack''), and finally \item no encryption at all, for all private anonymous pages, excluding the stack (``no GPU, no Stack''). \end{enumerate*} Distinguishing between ``Stack'' and ``no Stack'' slowdowns is important because, when an application does not have sensitive data stored on the stack, disabling stack encryption significantly improves the performances of MemShield. Distinguishing between ``GPU'' and ``no GPU'' slowdowns is useful in order to understand how much the userfaultfd-based mechanism impairs, by itself, the performances of the protected applications. Note that, even if the GPU kernel is a component that can be easily replaced, for instance by an implementation of another, more efficient cipher, transferring the data of the protected pages between system RAM and GPU has an intrinsic cost that could not be easily reduced in the current MemShield\ implementation. \begin{table}[!b] \begin{subtable}[b]{0.49\textwidth} \input{result-table-aes-procs} \end{subtable} \begin{subtable}[b]{0.49\textwidth} \input{result-table-sha512-procs} \end{subtable} \par\vskip1em \begin{subtable}[b]{0.49\textwidth} \input{result-table-qsort-procs} \end{subtable} \begin{subtable}[b]{0.49\textwidth} \input{result-table-crypt-procs} \end{subtable} \vskip1em \caption{% Wall-clock execution times of concurrent instances of the benchmarks, without MemShield\ (``Baseline'') and with MemShield\ using a sliding window of four pages. Average times and standard deviations are in seconds. ``Inst.'' denotes the number of concurrent benchmark instances. MemShield\ encrypts all private anonymous pages, including the stack.} \label{t:insts} \end{table} The \emph{aes} benchmark has a very large slowdown for sliding window size less than 16. A typical AES implementation makes use of very large tables, which are continuously and randomly accessed. The plot shows that the accesses fall both into many \texttt{malloc()}ed pages and, to a lesser extent, into the stack. Reducing the sliding window size from eight to four significantly increases the slowdown, which means that the accesses to the encrypted pages are quite random. GPU encryption roughly doubles the slowdown values. The \emph{sha512} benchmark has negligible slowdown for sliding window sizes greater than eight. The plot shows that the overhead is due mainly to anonymous private pages not included in the stack, that is, stack handling does not contribute a lot to the slowdown. In fact, the program uses several \texttt{malloc()}ed pages as a buffer for data read from file, while it uses the stack to store a small data structure for the digest inner state. Decreasing the sliding window size from eight to four does not significantly change the slowdown, which means that the replacement policy of the sliding window is working fine: actually, the program tends to read sequentially the pages in the buffer. GPU encryption doubles the slowdown values. The \emph{qsort} benchmark has been selected so to emphasize the effects of stack encryption in some types of protected applications. The program sorts 2048 integers eventually using the C library function \texttt{qsort()}. This function avoids recursion by storing on the stack some pointers to the array partitions still to be sorted. Using a sliding window of four pages, page fault handling causes a slowdown roughly seven when the stack is protected, and the GPU encryption doubles this value. On the other hand, if stack is not included in the protected pages, the slowdown is always negligible. Similarly, the \emph{crypt} benchmark has a significant slowdown only when the stack is encrypted. In fact, the \texttt{crypt\_r()} function is invoked on data placed on the stack. The slowdown caused by GPU encryption, by itself, is roughly equal to the slowdown caused by page fault handling. The overhead of MemShield\ is quite small, for every sliding window size. \begin{figure}[t] \centering \begin{subfigure}[b]{0.49\textwidth} \includegraphics[width=\textwidth]{aes.real.slowdown.sw4.pdf} \end{subfigure} \begin{subfigure}[b]{0.49\textwidth} \includegraphics[width=\textwidth]{sha512.real.slowdown.sw4.pdf} \end{subfigure} \vskip-2em\includegraphics[height=1.9em]{legend.pdf}\vskip-.5em \begin{subfigure}[b]{0.49\textwidth} \includegraphics[width=\textwidth]{qsort.real.slowdown.sw4.pdf} \end{subfigure} \begin{subfigure}[b]{0.49\textwidth} \includegraphics[width=\textwidth]{crypt.real.slowdown.sw4.pdf} \end{subfigure} \vskip-2em \caption{Slowdowns relative to baseline (no MemShield) varying the number of benchmark instances. MemShield\ protects all private anonymous pages including the stack (``Stack'') or excluding it (``no Stack''), with a sliding window of 4 pages. Encryption is performed by the GPU (``GPU'') or not done at all (``no GPU'').} \label{f:insts} \end{figure} We also run another set of benchmarks to verify how MemShield\ scales up when the number of protected clients increases. Each benchmark launches one, two, or four instances of the program at the same time; observe that our test machine has only four physical cores. As shown in Table~\ref{t:insts}, average execution times have been collected with and without MemShield\ protection, with sliding window size equal to four pages and stack encryption enabled. Figure~\ref{f:insts} shows the slowdowns of the average execution times with respect to the baseline, that is, execution without MemShield\ protection. According to the plots, there is a limited increase of the slowdown when the number of concurrent instances grows, both for page fault handling and for GPU encryption. \section{Conclusions} \label{s:conc} Memory encryption is an effective solution against memory disclosure attacks, in which an attacker could access and dump system RAM contents, in order to extract any sort of sensitive data. In this article we presented MemShield{}, which is a novel approach to software memory encryption for user-mode applications that uses a GPU as a secure key store and crypto processor. By ensuring that the key and the internal state of the cipher are stored into GPU hardware registers, MemShield{} guarantees that this sensitive information are never leaked to system RAM; therefore, the attacker cannot get meaningful data from a system dump unless the encryption cipher is broken. Compared to all other proposals for memory encryption frameworks,\linebreak MemShield\ is implemented by a user-mode daemon and does not require patches to the operating system kernel. Moreover, user applications do not require source code changes, recompilation, or code instrumentation, hence MemShield\ can protect even applications for which only the executable code is available. Functional tests and security analysis suggest that MemShield\ is an effective mitigation of Cold Boot attacks aimed at system RAM. Performance measures on a prototype implementation show how the MemShield\ overhead heavily depends on the chosen configuration and clients' memory access patterns. Moreover, the current implementation can be significantly improved, for instance by implementing selective page encryption, by optimizing the GPU kernel implementation, or by introducing some mechanisms that start encrypting pages in the sliding window ``in background'' as the number of free slots becomes lower than a predefined threshold. \section*{Acknowledgments} We gratefully thank Emiliano Betti for his valuable suggestions, support, and encouragements. The material presented in this paper is based upon work partially supported by Epigenesys s.r.l.. Any opinions, findings, and conclusions or recommendations expressed in this publication are those of the authors and do not necessarily reflect the view of Epigenesys s.r.l..
{'timestamp': '2020-04-21T02:26:43', 'yymm': '2004', 'arxiv_id': '2004.09252', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09252'}
arxiv
\section{Introduction}\label{sec:introduction}} \IEEEPARstart{O}{ptical flow} is a visual cue defined as the appearance of spatiotemporally varying brightness patterns \cite{Gibson1950}, which can be perceived by both biological vision systems and cameras. This cue is important for the behavior of animals of varying size \cite{Feng2003}, ranging from small flying insects \cite{Borst2010} to humans \cite{Borst2015}, as it allows these animals to estimate their ego-motion and to have a better understanding of the visual scene. Optical flow is also important in computer vision and robotics applications for tasks such as object tracking \cite{Kajo2017} and autonomous navigation \cite{de2016monocular} Many algorithms have been introduced to determine optical flow, including correlation-based matching methods \cite{Anandan1989,Singh1991}, frequency-based methods \cite{Heeger1988,Fleet1992}, and differential methods \cite{Horn1981,Lucas1981}. Correlation-based matching methods try to maximize the similarity between different intensity regions across multiple frames. Finding the best match then corresponds to finding the shift which maximizes the similarity score. Frequency-based methods exploit either the amplitude or phase component of the complex valued response of a Gabor quadrature filter pair \cite{Gabor1945} convolved with an image sequence. Lastly, differential methods compute optical flow based on a Taylor expansion of the image signal, subject to the brightness constancy assumption. All these methods assume that the brightness of a moving pixel remains constant over time and, when applied locally, are subject to the \textit{aperture problem} \cite{Ullman1979}. The true motion of a one-dimensional structure cannot be estimated unambiguously; instead, only the motion component that is normal to this structure can be perceived. In functional form, this corresponds to one equation with two unknowns and thus additional constraints are required. A global smoothness constraint has been added for differential methods, which assumes that neighboring pixels undergo a similar motion \cite{Horn1981}. This has led to \emph{variational} methods that minimize a global energy function consisting of a data and a smoothness term. These methods have played a dominant role for many years due to their high performance. However, a main drawback is that the iterative minimization of the energy function leads to long computation times. Moreover, the brightness constancy assumption is a coarse approximation to reality and thus limits performance \cite{Zimmer2011}. Research has focused on extra energy terms to deal with deviations from the brightness constancy assumption and improve the robustness of global smoothness constraints, leading to slow but steady progress. As in many other computer vision areas, currently, the best-performing algorithms are trained deep neural networks. Initially, training such networks was challenging due to the lack of ground-truth optical flow data and the excessive human effort required for manual optical flow labeling. \textit{Dosovitskiy et al.} \cite{Dosovitskiy2015} were the first to successfully train deep neural networks to estimate optical flow by using a synthetically generated dataset with optical flow ground truth. Their networks, FlowNetS and FlowNetC, initially performed slightly worse than the state-of-the-art variational methods \cite{Tu2019}. However, trained deep neural networks became the new state-of-the-art method for optical flow estimation by subsequent researchers who focused on improving the architecture and training data \cite{Ilg2017,Sun2018,Hui2019}. Until now, the functioning of these networks is poorly understood. In this article we investigate \textit{how} deep neural networks perform optical flow estimation. There are two main reasons why this is important. First, it is difficult to guarantee correct behavior outside of the publicly available testsets without knowing what the network does. Second, a better understanding of what the architecture does may lead to valuable recommendations for improving the performance, for instance, by changing properties of the architecture or training data. In our analysis of deep optical flow networks, we make use of a method that has helped unveiling the workings of motion-sensitive brain areas in neuropsychology \cite{Jones1987a}. Specifically, we measure the response of neurons in the deepest layer of the contracting part of FlowNetS \cite{Dosovitskiy2015}, further referred to as the \texttt{c6} layer (see Fig. \ref{fig:archflownet}), to stimuli with varying spatiotemporal frequencies and construct a spectral response profile. The input stimuli used are translating plane waves, as this input type proved to be more selective in the frequency domain than moving bars \cite{Albrecht1980}. Based on the earlier findings of Gabor filters \cite{Gabor1945} in biological vision systems \cite{Jones1987,DeAngelis1995} and other learning-based methods \cite{VanHateren1998, Olshausen2003}, we expect to find these filters in FlowNetS as well. Therefore, we fit a Gabor function to the spectral response profile and study the residual error patterns. We find that the Gabor translational motion filter model is suitable for the majority of the filters. Additionally, we find filters sensitive to motion patterns such as dilation, rotation, and occlusion. Interestingly, neurons sensitive to these motion patterns have not been mentioned in neuropsychology. Furthermore, our analysis strongly suggests that the resolution in the temporal frequency domain can be significantly improved if more than two frames would be used as input to the neural network. Lastly, we find that the optical flow refinement process in the decoder part of the network behaves similarly in function to flow refinement in biological vision systems. The remainder of the article is structured as follows. In Section \ref{sec:rel}, related work in neuropsychology and deep-learning is discussed. In Section \ref{sec:bg}, an explanation is given of the architecture of FlowNetS (see Fig. \ref{fig:archflownet}). In Section \ref{sec:gabfit}, the responses of filters in the \texttt{c6} layer of this network to translating wave patterns are studied, and compared to translational Gabor filters. Subsequently, Section \ref{sec:dilrot} discusses the response of \texttt{c6} filters to dilating and rotating waves. In Section \ref{sec:ap}, it is studied how FlowNetS resolves the aperture problem. Finally, the results of this work are discussed in Section \ref{sec:dis}, and conclusions are drawn in Section \ref{sec:conc}. \begin{figure}[!t] \centering \includegraphics[width=0.49\textwidth]{images/architecture2.pdf} \caption{Schematic of the FlowNetS architecture \cite{Dosovitskiy2015}. The contracting part compresses spatial information through the use of strided convolutions (\texttt{c}), while the expanding part uses upconvolutions (\texttt{u}) for refinement. The predict-flow (\texttt{pf}) layers transform feature map activations into dense flow estimates (\texttt{f}). The feature map corresponding to the output of the \texttt{c6} layer (gray dashed box) is studied in Sections \ref{sec:gabfit} \& \ref{sec:dilrot}, while the flow refinement process (blue dashed box) is discussed in Section \ref{sec:ap}. } \label{fig:archflownet} \end{figure} \section{Related Work} \label{sec:rel} \subsection{Dense optical flow estimation with CNNs} Ever since the pioneering work of \textit{Horn et al.} \cite{Horn1981}, variational optical flow methods \cite{Brox2004} have played a dominant role in optical flow estimation due to their high performance. Most modern variational optical flow estimation pipelines consist of four stages: matching, filtering, interpolation, and variational refinement. Various improvements have been proposed over time to deal with issues such as long-range matching \cite{Brox2011} and occlusion \cite{Revaud2015}. Furthermore, improvements such as dense correspondence matching based on convolution response maps of the reference image with the target image \cite{Weinzaepfel2013}, and supervised data-driven interpolation of a sparse optical flow map \cite{Zweig2017} were also proposed. These last two improvements introduced elements of deep learning into the variational optical flow estimation pipeline. \textit{Dosovitskiy et al.} \cite{Dosovitskiy2015}, however, were the first to introduce a supervised end-to-end trained Convolutional Neural Network (CNN). CNNs have three major advantages when it comes to estimating optical flow. First, CNNs outperform variational optical flow estimation methods in terms of accuracy \cite{Ilg2017,Sun2018,Hui2019}. Second, the runtime of CNN-based optical flow algorithms is significantly lower than variational methods \cite{Ilg2017}. Third, CNN-based methods can learn from data and can exploit statistical patterns not realized by a human designer. This is an advantage over variational methods which require explicit, and sometimes inaccurate, assumptions on the input. However, CNNs also have three disadvantages. First, the results depend on the quality and size of the training data. Second, CNN-based methods face the risk of overfitting, which is relevant for optical flow estimation because it is difficult to obtain ground truth \cite{Tu2019}. Third, there is no guarantee that the trained models will generalize to scenarios not contained in the training dataset. Due to the \textit{black-box} nature of the solution, there is little insight into its workings and limitations. In \cite{Dosovitskiy2015}, \textit{Dosovitskiy et al.} introduced two networks based on the U-net architecture \cite{Ronneberger2015}: FlowNetS and FlowNetC. While FlowNetS is an encoder-decoder network consisting of simple convolutions, FlowNetC creates two separate processing streams and combines them in a \textit{correlation-layer}. This layer performs a multiplicative patch comparison between feature maps. Due to the explicit use of a correlation-layer, it is more straightforward to understand the workings of FlowNetC. However, not much is known about the workings of FlowNetS. Inspired by this architecture, \textit{Ranjan et al.} \cite{Ranjan2017a} introduced SpyNet, a spatial image pyramid with simple convolutional layers at each pyramid level and a warping operation between pyramid levels. They visualized the weights of the first layer of their network and claim that these filters resemble Gabor filters \cite{Gabor1945}. This provided a glimpse into the working principle of SpyNet. Finally, \textit{Teney et al.} \cite{Teney2016} built a shallow CNN-architecture by integrating domain knowledge, such as invariance to brightness and in-plane rotations. On small motion their architecture performs well, but performance declines on large motion near occlusions. They conclude good occlusion performance requires reasoning over a larger spatiotemporal extent, which their shallow architecture is not able to do. \textit{Ilg et al.} \cite{Ilg2018b} quantified the uncertainty of CNN-based methods to handle the black-box nature of deep neural networks. They used a modified FlowNetC that produces multiple hypotheses per forward pass, which are then merged to a single distributional flow output. They showed that their network produces highly uncertain flow estimates when optical flow estimation is difficult (shadows, translucency, etc.). Lastly, \textit{Ranjan et al.} \cite{Ranjan2019} highlighted another downside of deep neural networks, which is the ability of adversarial examples to fool neural networks and produce erroneous results. They showed that especially networks using an encoder-decoder architecture are affected, while networks using a spatial pyramid framework are less vulnerable. None of the works above, however, explain how their architecture estimates optical flow. \subsection{Receptive field mapping} There are two main threads of research to understand what neural networks have learned: attribution and feature visualization. Attribution methods \cite{Springenberg2014,Zeiler2014} are used to \textit{attribute} filter outputs, like optical flow, to parts of the input by visualizing the gradient. However, it is hard to see where an optical flow estimate comes from. Feature visualization is concerned with understanding what neurons, filters, or layers in a neural network are sensitive to by optimizing the input \cite{Erhan2009}. The result is usually an image with noisy and visually difficult to interpret high-frequency patterns \cite{Olah2017}. Three methods of regularization can be applied to cope with this phenomenon. First, frequency penalization discourages the forming of these patterns. The downside is that this approach also discourages the forming of legitimate high-frequency patterns which are of interest for optical flow estimation. Second, small transformations like scaling, rotation, or translation can be applied in between optimization steps \cite{Mordvintsev2015}. This approach is also not viable because transformation affects the ground truth of optical flow. Third, priors can be used which can keep the optimized input interpretable. Such approaches typically involve learning a generative model \cite{Nguyen2016a} or enforcing priors based on statistics from the training data \cite{Wei2015}. This approach is often very complex and it may be unclear what can be attributed to the prior and what can be attributed to what the network has learned. Due to these reasons, we look at the field of neuropsychology and specifically study what methods researchers have used to determine what stimuli activate neurons in mammalian vision systems and what functions best describe the neural responses. It was shown that Gabor functions \cite{Gabor1945} best modeled the spatial response of simple cells in the mammal visual cortex \cite{Jones1987}. It can be shown that Gabor filters are optimal for simultaneously localizing a signal in the spatial and frequency domain \cite{Bracewell1986}, making them ideal for motion estimation. Later, \textit{DeAngelis et al.} \cite{Deangelis1993} examined the spatiotemporal response of cells and their space-time separability. In functional form, space-time separable Gabor filters are frequency-tuned with a stationary Gaussian envelope and space-time inseparable Gabor filters are velocity-tuned with a moving Gaussian envelope \cite{Petkov2007}. In this work we only consider fitting frequency-tuned Gabor filters, due to their simplicity and the low number of input frames used by the FlowNet architectures. Two approaches to receptive field mapping in neuropsychology can be discerned: the reverse-correlation approach and the spectral response profile approach. The former presents a rapid random sequence of flashing bars at various imaging locations to the mammal. The spike train emitted by the neuron in the subject is correlated to the sequence in which the stimuli were presented. This approach allows for a rapid measurement of the receptive field profile in the spatiotemporal domain \cite{DeAngelis1995}. Instead, the spectral response profile approach presents translating plane waves to the mammal at varying orientations and spatiotemporal frequencies \cite{Palmer1981,DeAngelis1993a}. \textit{Jones et al.} used both the reverse-correlation approach to construct a spatial receptive field profile \cite{Jones1987b} and measured the response to plane waves to construct a spectral response profile \cite{Jones1987a}. Subsequently, the spatial and spectral responses were compared to the Gabor filter model in the spatial and frequency domain, and the filter parameters obtained from both methods proved to be highly correlated \cite{Jones1987}. A similar correspondence in outcome between the methods was found by \textit{Deangelis et al.} \cite{Deangelis1993,DeAngelis1993a} in the visual cortex of cats. In this work we extend the approach of \textit{Jones et al.} \cite{Jones1987} to the spatiotemporal domain and measure spectral responses of the network to translating plane waves, to which frequency-tuned spatiotemporal Gabor filters are fitted. A benefit of measuring the spatiotemporal spectral responses for optical flow is that translation is more easily described in the frequency domain \cite{Petkov2007}. \subsection{Aperture problem} Optical flow estimations methods are only able to resolve motion components normal to the orientation of an edge in the intensity pattern. This is known as the aperture problem \cite{Ullman1979}. In CNNs the size of the aperture of a neuron is referred to as the receptive field, which is defined as the region in the input which affects the activation of the neuron. In this work we show that the receptive field size is related to the aperture problem by training different versions of FlowNetS with varying receptive field sizes. In neuropsychology, \textit{Komatsu} \cite{Komatsu2006} has shown the existence of a perceptual filling-in mechanism in the mammalian visual cortex for cues such as color, brightness, texture, or motion. While the precise neural workings are still under discussion, edge structure \cite{VonDerHeydt2003} and the interaction between neighboring neurons play an important role in this process \cite{Poort2012}. In neural networks attempts have been made to implement such a mechanism as well. To allow for the interaction between neurons, a recurrent model can be used \cite{Liang2015}. \textit{Zweig et al.} \cite{Zweig2017}, however, used an unfolded feed-forward version of a recurrent network and a multi-layer loss to allow for interaction between neurons. Their CNN-based motion interpolation architecture takes a sparse flow map and edge structure as input. They showed their motion interpolation method refines motion estimates similarly to the human visual cortex by demonstrating the filling-in effect of the network on a Kanizsa illusion. FlowNetS also features a multi-layer loss, and, in Section \ref{sec:ap}, the ability of the expanding part of FlowNetS to interpolate and refine flow maps is highlighted. \section{Model details}\label{sec:bg} Fig. \ref{fig:archflownet} shows a schematic representation of the FlowNetS architecture, which takes two consecutive images as input. Multiple versions of FlowNetS exist. \textit{Dosovitskiy et al.} \cite{Dosovitskiy2015} mention the use of the ReLU activation function in their work. The release of their pre-trained models, however, uses a leakyReLU activation function\footnote{\url{https://lmb.informatik.uni-freiburg.de/resources/binaries/flownet/flownet-release-1.0.tar.gz}}. In order to facilitate interpretability of the motion filter analysis, we choose to use the ReLU version. With the same aim, we introduce two small adjustments. First, the bias terms are removed in the predict-flow \texttt{pf} layers because the flow is assumed to be zero-centered. Second, the kernel size in the \texttt{pf} layers is reduced from $3 \times 3$ to $1 \times 1$ to allow clearer location identification. The full details of our version of FlowNetS can be found in Appendix A. Regarding training, as in \cite{Dosovitskiy2015}, we use the same data augmentation \textit{on both} frames, but we do not use incremental flow and color augmentation \textit{between} frames, since the authors do not specify the parameters of these mechanisms. Furthermore, the network is trained for fewer iterations (300K iterations versus 600K iterations) due to limited availability of computational resources. Evaluation on the MPI-Sintel \cite{Butler2012} and FlyingChairs \cite{Dosovitskiy2015} datasets shows comparable performance between the slightly modified FlowNetS and the original version, as can be seen in Appendix A. The synthetic dataset FlyingChairs \cite{Dosovitskiy2015}, which was used to train the original and our slightly modified FlowNetS, consists of approximately 22k image pairs. The image pairs are composed of a varying numbers of chairs and background images from natural scenes. Between image pairs, a composition of translation, rotation, and scaling motion is applied. The size of the chairs is sampled from a Gaussian with a mean and standard deviation of 200 pixels, clamped between 50 and 640 pixels. Note that the synthetic scenes also contain occlusion. Further details about the composition of affine motion can be found in \cite{Dosovitskiy2015}. \section{Gabor spectral response profile fitting for translation}\label{sec:gabfit} We investigate what motion patterns the filters of our FlowNetS architecture are sensitive to. Instead of analyzing the selectivity of all filters, we focus our study on the \texttt{c6} layer. As shown in Fig. \ref{fig:archflownet}, the activations of the feature maps of these layers are directly transformed by two multiplicative values (i.e. \texttt{pf6}) into an initial horizontal and vertical flow estimate (i.e. \texttt{f6}), which is later used for refinement. For these reasons, we believe that the most compressed representation of what optical flow is and how to estimate it is encoded in this layer. In this section, first the theory behind Gabor filters and the spectral response fitting method is discussed, followed by the results obtained. Thereafter, we discuss the resolution in the temporal frequency domain of the fitted Gabor filters. \subsection{Methodology} As in \cite{Gabor1945,Heeger1988,Petkov2007}, the spatiotemporal frequency-tuned Gabor filter $g$ in Cartesian coordinates centered at the origin can be written as the product of a Gaussian $w$ and a translating plane wave $s$: \begin{equation} g(x, y,t)=s(x, y,t) w(x, y,t) \end{equation} The (non-normalized) Gaussian $w$ is defined by: \begin{equation} w(x,y,t) = \exp \left( - \left( \frac{x_r^2}{\sigma_x^2} + \frac{y_r^2}{\sigma_y^2} + \frac{t^2}{\sigma_t^2}\right) \right) \end{equation} \noindent where $\sigma_x$, $\sigma_y$, and $\sigma_t$ control the spread of the spatiotemporal Gaussian window. To decrease the number of parameters in the fitting process, it is assumed that the center of the Gaussian coincides with the center pixel of the receptive field. Furthermore, the subscript $r$ denotes a rotation operation which allows the Gaussian to be aligned along orientation $\theta_0$, and is defined as: \begin{equation} \label{x_r} \begin{array}{l}{x_r=x \cos (\theta_0)+y \sin (\theta_0)} \\ {y_r=-x \sin (\theta_0)+y \cos (\theta_0)}\end{array} \end{equation} \noindent where a positive value of $\theta_0$ corresponds to a clockwise rotation with respect to the positive $x$-axis. The subscript $0$ indicates the parameter value corresponding to the peak response of the Gabor filter. This orientation, which corresponds to the preferred direction of motion of the filter, is related to the spatial frequencies via $\theta_0=\tan ^{-1} \left( f_{y_{0}}/ f_{x_{0}}\right)$. A translating plane wave $s$ in the Cartesian coordinate system can be written as: \begin{equation} s(x, y,t)=\cos \left(2 \pi \left( F_{0} x_r -f_{t_{0}}t \right)+\varphi_{0}\right) \label{eq:trans} \end{equation} \noindent where the spatial frequency magnitude $F_0$ is related to the spatial frequencies via $F_0=(f_{x_{0}}^{2}+f_{y_{0}}^{2})^{1/2}$, $f_{t0}$ indicates the temporal frequency, and $\varphi_0$ denotes the phase of the filter. The dependence of $s$ on $y$ is due to $x_r$, which is a function of $x$ and $u$ (see Eq. \ref{x_r}). A Gabor filter is said to be even when $\varphi_0=0$ and odd when $\varphi_0=\pm\pi$. Further, note that the preferred velocity of the filter $v_0$ is related to $F_0$ and the temporal frequency $f_{t_{0}}$ via $v_0=f_{t_{0}}/F_0$, as in \cite{Heeger1988}. A higher spatial frequency $F_0$ allows tracking of motion of thinner image structures. When a signal is sampled in time or space, frequency components which are larger than or equal to $0.5$ cycles per frame (i.e., the Nyquist frequency) become undersampled and aliasing occurs. Thus, if we limit ourselves to signals which do not suffer from aliasing, the maximum velocity a signal can have is limited by its $F_0$. Fig. \ref{fig:gaborspace} shows the 3D frequency space with the half-magnitude profile of a Gabor filter. \begin{figure}[!t] \centering \includegraphics[width=0.425\textwidth]{images/3dgabor.pdf} \caption{Illustration of the half-magnitude profile in the 3D frequency domain of a spatiotemporal Gabor filter. The three ranges along which the responses of the Gabor half-magnitude profile are evaluated for the spectral response profile fitting process are shown in color.} \label{fig:gaborspace} \end{figure} Because we will fit the response of phase-sensitive Gabor filters, we highlight three phase-dependent convolution phenomena. Note that a valid convolution of two tensors with equal size corresponds to their dot product. First, because a sine is an odd signal, the dot product of two sines at opposite frequencies is negative. Second, the dot product of a cosine at opposite frequencies will be positive due to the even nature of the function. Third, sine and cosine are decorrelated and thus the dot product will be zero between these two signals. \noindent \textbf{Gabor spectral response profile fitting} \\ \noindent In the Gabor spectral response fitting process, translating grayscale plane waves $s$ are used as input to the network, and we try to minimize the difference in response between filters in the \texttt{c6} layer of our FlowNetS and spatiotemporal Gabor filters $g$. To better approximate the response of \texttt{c6} filters, we enhance the Gabor filter output with a gain term $K$, a bias term $b$, and pass the response through a ReLU non-linearity. Then, the response $r$ to a convolution with a translating plane wave $s$ and a Gabor filter $g$ is given by: \begin{equation} r = \textnormal{ReLU}\left(K(s(x,y,t) \ast g(x,y,t) + b)\right) \label{eq:fitgab} \end{equation} \noindent where $r$ is a function of nine parameters (i.e., $F_0$, $\theta_0$, $f_{t_{0}}$, $\varphi_0$, $\sigma_x, \sigma_y, \sigma_t$, $K$, $b$), which are estimated in a two-step process. First, a gridsearch is performed to determine the location in the spatiotemporal frequency domain with the highest response per filter in the \texttt{c6} layer. We denote the response of the filters in the network by $\hat{r}$, and their peak response value by $\hat{r}_0$. Because the fitted Gabor filters are phase sensitive, this amounts to estimating four parameters (i.e., $F_0$, $\theta_0$, $f_{t_{0}}$, $\varphi_0$). Therefore, a four-dimensional grid of translating plane waves (i.e., the input to the network) is constructed using all combinations of these parameters within a given range and step size (see Appendix B). The range for the value of half spatial wavelength $\lambda/2=1/2F$ is chosen so that it captures the sizes of the chairs present in the training dataset (as explained in Section \ref{sec:bg}). Second, once the peak response of the \texttt{c6} filters is found, we estimate the spatiotemporal spread of the Gaussian (determined by $\sigma_x, \sigma_y, \sigma_t$), the gain $K$, and the bias $b$. This is done by minimizing the difference in response between the fitted Gabor filters and the corresponding \texttt{c6} filters along three separate ranges in the spatiotemporal frequency space. These ranges are illustrated in Fig. \ref{fig:gaborspace}, and further described in Appendix B. We define the cost function $\mathcal{L}$ in response to a convolution with a translating plane wave $s$ as: \begin{equation} \begin{split} \mathcal{L} &= \sum_{i}^{} (r_i-\hat{r}_i)_{F}^{2} + \sum_{j}^{} (r_j-\hat{r}_j)_{\theta}^{2} + \sum_{k}^{} (r_k-\hat{r}_k)_{f_t}^{2}\\&= \mathcal{L}_F + \mathcal{L}_\theta + \mathcal{L}_{f_{t}} \label{eq:min} \end{split} \end{equation} \noindent where $\mathcal{L}_F$, $\mathcal{L}_\theta$, and $\mathcal{L}_{f_{t}}$ denote the sum of squared errors along their respective intervals. We constrain the bounds of the Gabor filter parameters to obtain reasonable values, which leads to a non-linear bounded convex optimization problem which can be solved using the robust trust-region-reflective algorithm \cite{Iciam2000}. In order to compare the obtained cost values between \texttt{c6} filters, we construct a normalized cost value $\mathcal{L}_{norm}$ by dividing the cost by the squared peak response of the filter: $\mathcal{L}_{norm} = \mathcal{L}/\hat{r}_{0}^2$. \begin{figure*}[!t] \begin{subfigure}[t]{0.5\textwidth} \centering \includegraphics[width=0.85\textwidth]{images/trans_polar.pdf} \end{subfigure}% ~ \begin{subfigure}[t]{0.5\textwidth} \centering \includegraphics[width=0.7\textwidth]{images/trans_v.pdf} \end{subfigure} \caption{Location of peak response $\hat{r}_0$ per \texttt{c6} filter in the spatiotemporal frequency domain in response to translating plane waves. \emph{Left:} Half spatial wavelength $\lambda_0/2$ and orientation $\theta_0$ corresponding to peak response $\hat{r}_0$ per filter. \emph{Right:} Half spatial wavelength $\lambda_0/2$ and temporal frequency $f_{t_{0}}$ corresponding to peak response $\hat{r}_0$ per filter. In both plots, the black dashed lines indicate the peak of the distribution in the half spatial wavelength dimension, which is around 200 pixels. } \label{fig:trans} \end{figure*} \begin{figure*}[!t] \begin{subfigure}[t]{0.2\textwidth} \centering \includegraphics[width=0.9\textwidth]{images/fit_box.pdf} \end{subfigure}% \centering \begin{subfigure}[t]{0.8\textwidth} \centering \includegraphics[width=1.\linewidth]{images/fit_sim.pdf} \end{subfigure} \caption{Quantitative results of the spectral Gabor filter fitting process. \emph{Left:} Boxplot containing the total normalized cost $\mathcal{L}_{\text{norm}}$ per filter ($592$ filters). \emph{Right 3x3 plots:} Row-wise, the measured responses of three different \texttt{c6} filters and their corresponding Gabor fits. The blue, green, and red \texttt{c6} filters correspond to the crosses at the median, near the 75th percentile and near the upper whisker limit of the boxplot, respectively.} \label{fig:gaborfit} \end{figure*} \subsection{Results} We found 592 of the 1024 filters in the \texttt{c6} layer of FlowNetS to have an activation larger than zero when using the aforementioned input waves. The location of the peak response of the active \texttt{c6} filters in terms of half spatial wavelength $\lambda_0 /2$, orientation $\theta_0$, and temporal frequency $f_{t_{0}}$ can be seen in Fig. \ref{fig:trans} (left). As shown, the locations of the peak responses of the filters are well distributed over all angles. Radially, there is a concentration around a half spatial wavelength of 200 pixels, which is to be expected based on the nature of the training data as the average size of the chairs in the training dataset is 200 pixels. The concentration of the peak responses becomes even more apparent in Fig. \ref{fig:trans} (right), which shows the distribution along the temporal and half spatial wavelength axes. Furthermore, we note that the distribution of the temporal frequencies is skewed toward the Nyquist limit of $0.5$ cycles per frame. A possible reason for this is the low resolution in the temporal frequency due to the low number frames used as input to the network. This is further discussed in Section \ref{sec:tempband}. The main observation of our spectral analysis is that the fitted modified Gabor functions (i.e., Eq. \ref{eq:fitgab}) capture the spatiotemporal frequency selectivity of the active \texttt{c6} filters of FlowNetS accurately. In order to give insight into the goodness of fits for all neural responses in the \texttt{c6} layer, we show three example responses corresponding to different normalized cost values $\mathcal{L}_{norm}$ in Fig. \ref{fig:gaborfit}. Note that the fitted Gabor filters correspond well to the response of the blue and green \texttt{c6} filters (with $\mathcal{L}_{norm}$ at $50\%$, $75\%$ of the distribution); but, in the red case (an outlier), the fitted Gabor shows a substantial deviation from the measured \texttt{c6} response near $\theta=0$. For this reason, all the fits and error patterns above the 75\% percent threshold (corresponding to the green \texttt{c6} filter) were visually inspected for systematic deviations. Visual inspection is performed instead of an auto-correlation procedure since the latter is not possible due to a non-uniformly spaced polar 3D frequency grid\cite{Jones1987}. Fig. \ref{fig:fit_viz} contains the qualitative results used for this analysis. \begin{figure}[!t] \centering \includegraphics[width=1.\linewidth]{images/theta_error4.pdf} \caption{Orientation cost $\mathcal{L}_{\theta}$ per filter as a function of $\varphi_0$.} \label{fig:theta_error} \end{figure} \begin{figure*}[!t] \centering \begin{subfigure}{\linewidth} \centering \includegraphics[width=0.96\textwidth]{images/A.pdf} \end{subfigure} \begin{subfigure}{\linewidth} \centering \includegraphics[width=0.96\textwidth]{images/B.pdf} \end{subfigure} \begin{subfigure}{\linewidth} \centering \includegraphics[width=0.96\textwidth]{images/C2.pdf} \end{subfigure} \begin{subfigure}{\linewidth} \centering \includegraphics[width=0.96\textwidth]{images/D.pdf} \end{subfigure} \caption[]{Qualitative results of the error patterns of the spectral Gabor fitting process. The spectral response profiles are shown as a function of spatial frequency $F$ and orientation $\theta$. \texttt{Data} shows to the measured response of a \texttt{c6} filter, \texttt{Fit} is the response of the corresponding fitted Gabor filter, and \texttt{Error} shows their difference. Evaluations are with respect to $f_{t_{0}}$ and $\varphi_0$. (A) \texttt{c6} filter whose response profile is accurately captured by the Gabor model. (B) Red \texttt{c6} filter from Fig. \ref{fig:gaborfit}, which activates on opposite spatial frequencies. (C) \texttt{c6} filter with a very weak directional bias. (D) Noisy \texttt{c6} filter pattern (further discussed in Section \ref{sec:dilrot}).} \end{figure*} \begin{figure*} \ContinuedFloat \begin{subfigure}{\linewidth} \centering \includegraphics[width=0.96\textwidth]{images/E2.pdf} \end{subfigure} \caption{(continued) (E) For this \texttt{c6} filter, the spectral response profile for three different temporal frequency $f_t$ values is visualized. Two different Gaussian peak responses at opposite orientation can be observed at $f_t=0.3$ and $f_t=0.5$ cycles per frame. The blue and red lines correspond to the axes of the 2D representation of this filter shown in Figure \ref{fig:viz_occ}.} \label{fig:fit_viz} \end{figure*} Similarly to the blue filter in Fig. \ref{fig:gaborfit}, Fig. \ref{fig:fit_viz}A shows a \texttt{c6} filter whose response fits nicely in the Gabor filter framework. On the other hand, we find three types of systematic deviations (i.e., Fig. \ref{fig:fit_viz}B, \ref{fig:fit_viz}C, \ref{fig:fit_viz}E) from the Gabor model, and also conclude that some patterns are too complex for interpretation, such as the \texttt{c6} filter shown in Fig. \ref{fig:fit_viz}D The filter in Fig. \ref{fig:fit_viz}B shows a deviation from the fitted Gabor 180 degrees away from $\theta_0$. This filter is responsive to edge structure (i.e., $|\varphi_0| \approx 90^{\circ}$) and is thus approximately odd, since the dot product of two odd signals at opposite frequencies results in a negative value. However, this filter still produces a positive activation at the opposite spatial frequency, corresponding to 180 degrees away from $\theta_0$. In Fig. \ref{fig:theta_error} the distribution of the phase values $\varphi_0$ versus orientation cost $\mathcal{L}_{\theta}$ for all filters is depicted. As shown, there are multiple filters responsive to edge structure that have a high $\mathcal{L}_{\theta}$ (e.g., the red filter in Fig. \ref{fig:gaborfit}). One possible reason for this systematic deviation from the Gabor response is that the network is able to learn flow filters that are invariant to polarity (meaning white-black or black-white transitions) \begin{figure}[!t] \centering \includegraphics[width=0.975\linewidth]{images/E3.pdf} \caption{Spatiotemporal frequency representation of the measured filter response in Fig. \ref{fig:fit_viz}E. The positive and negative $F$-axes correspond to the blue and red lines in Fig. \ref{fig:fit_viz}E.} \label{fig:viz_occ} \end{figure} We find two \texttt{c6} filters that exhibit weak directional bias, an example of which can be found in Fig. \ref{fig:fit_viz}C. Moreover, we also find filters that exhibit two or more Gaussian peaks with similar peak response magnitudes but tuned to different spatial frequencies $F_0$, orientations $\theta_0$, and temporal frequencies $f_{t_{0}}$. An example of such a filter can be found in Fig. \ref{fig:fit_viz}E, and its 2D spatiotemporal representation is shown in Fig. \ref{fig:viz_occ}. A possible explanation is that these filters are sensitive to occlusion, as discussed in Section \ref{sec:dilrot}. Lastly, we find filters that appear noisy and are hard to interpret given the limitations of our methodology (further discussed in Section \ref{sec:dilrot}). Such an example can be seen in Fig. \ref{fig:fit_viz}D. \subsection{Temporal bandwidth} \label{sec:tempband} For orientation $\theta$ and temporal frequency $f_t$, the bandwidth is defined as the width of the filter which provides an output above half the maximum response. This leads to a bandwidth in degrees $\Delta \theta_{1/2}$ and cycles per frame $\Delta f_{t_{1/2}}$ for orientation and temporal frequency respectively: \begin{equation} \Delta f_{t_{1 / 2}}=f_{t_{\max}}-f_{t_{\min}} \end{equation} \begin{equation} \Delta \theta_{1 / 2}=\theta_{\max }-\theta_{\min } \end{equation} For spatial frequency $F$, the bandwidth is defined in terms of octaves as follows: \begin{equation} \Delta F_{1 / 2}=\log _{2}\left(F_{\max } / F_{\min }\right) \end{equation} Although we estimate the Gabor parameters of the active \texttt{c6} filters in the fitting process, the apparent bandwidth of these filter differs due to the non-linear transform in Eq. \ref{eq:fitgab}. The bandwidth is therefore measured based on the fitted Gabor filter response. In Fig. \ref{fig:sigmas}, the bandwidth of $F$, $\theta$, and $f_t$ can be seen. As shown, the interquartile range for spatial frequency bandwidth is between 1 and 2 octaves and the median orientation bandwidth is approximately $50^{\circ}$. Lastly, the temporal frequency bandwidth is of large extent with a median of approximately $0.27$ cycles per frame. \begin{figure}[!t] \centering \includegraphics[width=\columnwidth, height=5.0cm]{images/sigmas.pdf} \caption{Bandwidth of spatial frequency $F$, orientation $\theta$, and temporal frequency $f_t$ of the fitted Gabor filters of the $75\%$ active \texttt{c6} filters with the lowest $\mathcal{L}_{norm}$.} \label{fig:sigmas} \end{figure} \begin{figure*}[!b] \centering \includegraphics[width=1.\linewidth]{images/dilation_VT.pdf} \caption{Convolution response of a dilation filter $dw$ with a translating plane wave $s$ evaluated with spatiotemporal frequencies at $k$ integer multiples of the fundamental frequency. In the $\psi$ plot, a larger phase difference corresponds to a darker color with black being equal to or greater than $\pi/2$. A red mask is applied to frequency components with low power. The dashed lines indicate the Gaussian pattern perceived by the spectral fitting procedure.} \label{fig:dil} \end{figure*} We note that the network is able to narrow the extent of the filter response in the temporal domain using the non-linear transform in Eq. \ref{eq:fitgab}. An illustration of this mechanism can be seen in Fig. \ref{fig:timsam}. As shown, the extent of the half-magnitude profile is wider if the non-linear transformation is not employed. This figure also shows what happens when more frames are added to the input and the other parameters are kept the same (see Fig. \ref{fig:timsam}, bottom). This suggests that an even narrower extent could be reached by feeding the network with more images over time than just the two subsequent images used in FlowNetS. A higher resolution in the frequency domain is beneficial as it allows for a more precise measurement of the flow. \begin{figure}[!t] \centering \includegraphics[width=.95\columnwidth]{images/time_sampling.pdf} \caption{Illustration of how the network is able to decrease the extent of the filter response in the temporal domain. \emph{Top:} Fit and measured data for the median \texttt{c6} filter (see Fig. \ref{fig:gaborfit}). \emph{Middle:} The response of the fitted Gabor filter without the bias term and ReLU non-linearity. \emph{Bottom:} Response of the fitted Gabor filter when the number of frames is increased. } \label{fig:timsam} \end{figure} \begin{figure*}[!t] \centering \includegraphics[width=1.\linewidth]{images/rotation12.pdf} \includegraphics[width=1.\linewidth]{images/rotation22.pdf} \includegraphics[width=1.\linewidth]{images/rotation32.pdf} \includegraphics[width=1.\linewidth]{images/rotation42_VT.pdf} \caption{Convolution response of a rotation filter $cw$ with a translating plane wave $s$ evaluated with spatiotemporal frequencies at $k$ integer multiples of the fundamental frequency. In the $\psi$ plot, a larger phase difference corresponds to a darker color with black being equal to or greater than $\pi/2$. A red mask is applied to frequency components with low power. The dashed circle indicates the double lobe Gaussian pattern perceived by the spectral fitting procedure.} \label{fig:rot} \end{figure*} \section{Network response to dilation \& rotation}\label{sec:dilrot} In this section, the sensitivity of \texttt{c6} filters to dilation and rotation is analyzed. First, we explain the limitations of the spectral Gabor response profile fitting process and why we are not able to discern filters activating on translation, dilation, rotation, and occlusion with this methodology. Second, the theory used to identify filters sensitive to dilation and rotation is presented. Lastly, our results are discussed. Note that Gabor translation filters \cite{Gabor1945} and occlusion filters \cite{Beauchemin2000} already have an analytical description in both the space-time and frequency domain. Such a description of dilation and rotation is, to the best of the authors' knowledge, missing. Therefore, fitting \texttt{c6} filters to a dilation and rotation motion filter model requires a novel mathematical foundation which is outside of the scope of this work. \subsection{Limitations of the spectral response profile fitting} In the first part of the spectral response fitting process, a gridsearch is performed to find the peak response. In the subsequent fitting process, three response lines are generated by varying either $F$, $f_{t}$, or $\theta$, whilst keeping $\varphi$ constant. This method only allows the measurement of the relative attenuation in amplitude with respect to the peak response $\hat{r}_0$. This is sufficient for translation, which can be defined as a single constant phase Gaussian in the 3D frequency spectrum and thus produces a Gaussian in response. However, it is insufficient for other more complex motion types. In this section, we convolve translating plane waves with dilation, rotation, and occlusion filters to simulate their response. Due to the ReLU activation function, the dot product of two translating plane waves at the same frequency, which are more than or equal to 90 degrees out-of-phase, is zero. To determine which frequency components of dilation, rotation, and occlusion are more than 90 degrees out of phase, the Discrete Fourier Transform (DFT) \cite{Bracewell1986} is used to transform a simulated space-time signal to a representation in the frequency domain. The DFT is defined as: \begin{equation} X[k]=\sum_{n=0}^{N-1} x[n] e^{-j k \frac{2 \pi}{N} n} \end{equation} \noindent where $k\frac{2\pi}{N}$ is the $k$-th discrete frequency, and $N$ the total length of the discrete signal. When the discrete signal is real, the DFT of the signal will result in a complex number: \begin{equation} X[k]=Ae^{i\varphi} \end{equation} \noindent where the magnitude is denoted by $A$ and the phase value by $\varphi$. Note that a convolution in the space-time domain equals to multiplication in the frequency domain according to the convolution theorem\cite{Bracewell1986}. Because we evaluate the convolution response only at discrete frequencies of $k$ integer multiples along the $f_x$, $f_y$, and $f_t$ axis, only a single frequency component of the Fourier-transformed translating plane wave $S$ will contain power\footnote{Not taking into account the complex conjugate component.}. Then, if we define the $k$-th frequency component of $S$ as the complex vector $\mathbf{p}$, and the $k$-th frequency component of the Fourier transformation of the filter to be analyzed as $\mathbf{q}$, the phase difference between these two complex vectors is defined as the angle $\psi$ and given by: \begin{equation} \psi = \cos^{-1}( \frac{\mathbf{p} \cdot \mathbf{q}}{|\mathbf{p}| |\mathbf{q}|} ) \end{equation} \noindent where the maximum value of $\psi$ is $\pi$, and values of $\psi\geq\pi/2$ result in a zero response due to the ReLU in Eq. \ref{eq:fitgab} \begin{figure*}[!t] \centering \includegraphics[width=1.\linewidth]{images/occlusion_VT.pdf} \caption{Convolution response of an occlusion filter with a translating plane wave $s$ evaluated with spatiotemporal frequencies at $k$ integer multiples of the fundamental frequency. \emph{Left:} Example occlusion signal following the description of \textit{Beauchemin et al.}\cite{Beauchemin2000}. \emph{Middle left:} The power spectrum of the Fourier-transformed occlusion filter. \emph{Middle right:} The angle $\psi$ indicating the phase difference between the Fourier components of the occlusion filter and $s$. A larger phase difference corresponds to a darker color with black being equal to or greater than $\pi /2$. A red mask is applied to frequency components with low power. \emph{Right:} Convolution response between the occlusion filter and $s$. The pattern above the dashed gray line resembles that of Figs. \ref{fig:fit_viz}E and \ref{fig:viz_occ}.} \label{fig:occ_sim} \end{figure*} \noindent \textbf{Convolution response: Dilation \& rotation filters}\\ \noindent Fig. \ref{fig:dil} shows the convolution response of a dilation filter $dw$ with a translating plane wave $s$. From this figure, it can be observed that a diamond-like pattern emerges in the response, due to the immeasurable out-of-phase components of $dw$ and $s$. Because we evaluate the responses along lines orthogonal to the peak response, the pattern perceived is indicated by the dashed lines in the right-most plot of this figure, which correspond to the colored linear patterns in Fig. \ref{fig:gaborspace}. Thus, a Gaussian will be perceived along the spatial and the temporal frequency ranges. Hence, we are not able to discern between dilation and translation filters. Similarly, Fig. \ref{fig:rot} shows the convolution response of a rotation filter $cw$ with $s$. Note that the 3D power spectrum of $cw$ is different from a Gaussian. At high temporal frequencies (i.e., $\pm0.2$ cycles per frame), the frequency components of $cw$ and $s$ are out-of-phase. Thus, these frequency components will not be detected. The pattern perceived along the varying $\theta$ (also shown in Fig. \ref{fig:gaborspace}) is two Gaussian lobes at opposite frequency. This pattern is similar to the convolution response of a cosine Gabor filter tuned to stationary patterns (i.e., zero temporal frequency). Therefore, our methodology is also not able to detect rotation filters. \noindent \textbf{Convolution response: Occlusion filters} \\ \noindent Furthermore, we convolve an occlusion filter, using the description of \textit{Beauchemin et al.} \cite{Beauchemin2000}, with translating plane waves $s$. Occlusion in the spatiotemporal domain can be described as the combination of a Gaussian, a Heaviside step function, and two translating plane waves translating with different frequencies, as shown in Fig. \ref{fig:occ_sim}. The power spectrum of the Fourier-transformed filter can be described as two Gaussian filter pairs with \textit{tails} due to the Heaviside step function. The angle $\psi$ demonstrates that these tails have a large phase difference. Consequently, only the pattern above the dashed line is detected using our methodology, which corresponds to two different Gaussian lobes tuned to different frequencies. This pattern resembles that of Figs. \ref{fig:fit_viz}E and \ref{fig:viz_occ}, thus making it likely that the filter represented in these figures is responsive to occlusion. However, it should be noted that we are not able to discern such a pattern from the superposition of two regular Gabor filter pairs tuned to different frequencies. \begin{figure*}[!t] \centering \begin{subfigure}[t]{0.5\textwidth} \centering \includegraphics[width=0.9\linewidth]{images/dil_polar.pdf} \end{subfigure}% ~ \begin{subfigure}[t]{0.5\textwidth} \centering \includegraphics[width=0.78\linewidth]{images/dil_v.pdf} \end{subfigure} \caption{Location of peak response $\hat{r}_0$ per \texttt{c6} filter in the spatiotemporal frequency domain in response to dilating waves. Note that only filters are shown whose peak response $\hat{r}_0$ was higher than the maximum found in the translation gridsearch. \emph{Left:} Half spatial wavelength $\lambda_0/2$ and initial orientation $\theta_0$. \emph{Right:} Half spatial wavelength $\lambda_0/2$ and scale factor $h$. The black dashed line indicates the temporal aliasing constraint given by Eq. \ref{eq:dilconstr}.} \label{fig:grid_dil} \end{figure*} \begin{figure*}[!t] \centering \begin{subfigure}[t]{0.5\textwidth} \centering \includegraphics[width=0.9\linewidth]{images/rot_polar.pdf} \end{subfigure}% ~ \begin{subfigure}[t]{0.5\textwidth} \centering \includegraphics[width=0.78\linewidth]{images/rot_v.pdf} \end{subfigure} \caption{Location of peak response $\hat{r}_0$ per \texttt{c6} filter in the spatiotemporal frequency domain in response to rotating waves. Note that only filters are shown whose peak response $\hat{r}_0$ was higher than the maximum found in the translation gridsearch. \emph{Left:} Half spatial wavelength $\lambda_0/2$ and initial orientation $\theta_0$. \emph{Right:} Half spatial wavelength $\lambda_0/2$ and angular temporal frequency $\omega$. The black dashed line indicates the temporal aliasing constraint given by Eq. \ref{eq:rotconstr}.} \label{fig:grid_rot} \end{figure*} \subsection{Methodology} In order to still assess the sensitivity of the \texttt{c6} filters to dilation and rotation, we come up with a different methodology in which two gridsearches are performed. We assess the locations of the peak responses for filters which have a higher response to dilation or rotation than to translation. We do not classify a filter as either a rotation or dilation filter, since a filter can be sensitive to a composition of these respective motions. \\ \noindent \textbf{Dilation parametrization} \\ \noindent As in \cite{Fleet1992}, a dilating wave $d$ is given by: \begin{equation} d(x, y,t)=\cos \left(2 \pi F_{0} (x_r-\alpha x_r t) +\varphi_{0}\right) \label{eq:dilat} \end{equation} \noindent where $\alpha$ denotes the dilation factor. The training dataset used to train FlowNetS, i.e. FlyingChairs \cite{Dosovitskiy2015}, defines scaling motion in terms of the affine scaling factor $h$. Because the network only takes two frames as input, we define the relation between $h$ and $\alpha$ as follows: \begin{equation} h = \frac{1}{1-\alpha} \end{equation} The gridsearch is performed for the $[0.5,2.0]$ range of $h$, as it encapsulates the values encountered during training. More details about this search space can be found in Appendix B. In order to mitigate the effect of temporal aliasing, the search space is constrained so that the velocity of a point is not more than half its spatial wavelength $\lambda_0/2$. For a dilating wave, this velocity is given by: \begin{equation} v = \big(\frac{1}{1-\alpha}-1\big)x = (h-1)x \end{equation} Then, the temporal aliasing constraint for dilating waves is given by: \begin{equation} (h-1)x \leq \frac{1}{2} \lambda_0 \label{eq:dilconstr} \end{equation} \noindent \textbf{Rotation parametrization} \\ \noindent A rotation wave $c$ is given by: \begin{equation} c(x, y,t)=\cos \left(2 \pi F_{0} x_r(t)+\varphi_{0}\right) \label{eq:rotation} \end{equation} \noindent where $x_r(t)$ varies with time, and is defined as: \begin{equation} x_r(t)=x \cos (\theta_0 + \omega t) + y \sin (\theta_0 +\omega t) \end{equation} \noindent where $\omega$ denotes the angular velocity in radians per frame. The search space for the rotation gridsearch can be found in Appendix B. A constraint was also added to limit the effect of temporal aliasing. $\omega$ can be related to a point at distance $m$ from the center of rotation by $v=\omega m$. The maximum distance from the center of rotation to the edge is equal to half the receptive field size, which is 383 pixels in the \texttt{c6} layer of our FlowNetS. As the wave rotates around the center pixel, the velocity at this point should thus be lower than half the spatial wavelength. The constraint is given by the following relation: \begin{equation} \omega m_{\text{max}} \leq \frac{1}{2} \lambda_0 \label{eq:rotconstr} \end{equation} \subsection{Results} The peak responses of \texttt{c6} filters which have a higher activation to dilation than to translation (i.e., approximately $15\%$ of the active filters) are shown in Fig. \ref{fig:grid_dil}. These filters show a radially dispersed pattern along the $\theta$-axis, and a peak in the distribution of half spatial wavelengths near 200 pixels, which is to be expected given the nature of the training dataset. Lastly, peak responses are often close to the temporal aliasing limit and the maximum scaling value of the gridsearch. This is similar to the temporal peak response location for the translation gridsearch (see Fig. \ref{fig:trans}). In Fig. \ref{fig:grid_rot}, the peak responses of the \texttt{c6} filters for the rotation gridsearch are shown. It can be observed that most filters are active near the temporal translation and temporal rotational aliasing limit. Also, a peak in the distribution of half spatial wavelengths can be identified around 250 pixels, which is slightly higher than expected. A possible explanation for this discrepancy is that rotation is actually a 3D motion and thus the scale should also be limited along its radial axis. Approximately $45\%$ of the active \texttt{c6} filters activate more on rotation than on translation, which could be due to the fact that we do not limit the wavelength along the axis of rotation. The points in the motion field at the far end of the receptive field then move with a very high velocity, and therefore, the response of the filters is higher. \begin{figure*}[!t] \centering \begin{subfigure}[c]{0.5\textwidth} \centering \includegraphics[width=.95\linewidth]{tikz/aperture_flow_crop} \label{fig:apfmap} \end{subfigure}% ~ \begin{subfigure}[c]{0.5\textwidth} \centering \includegraphics[width=0.98\linewidth]{images/aperture.pdf} \label{fig:aperror} \end{subfigure} \caption{Response of our FlowNetS and its two variations, FlowNetXS and FlowNetXXS, to diagonally translating bars with motion magnitude $|\mathbf{u}|=64$ pixels. \textit{Left:} \texttt{f6}, \texttt{f4} and \texttt{f2} FlowNetS flow maps in response to downward-left diagonally translating bars of different scales, using the color-coding scheme from \cite{Baker2011}. \textit{Right:} EPE versus scale of the bar in pixel coordinates. RF \texttt{f6} indicates the diagonal receptive field size in pixel coordinates corresponding to the \texttt{f6} flow map. } \label{fig:aperture} \end{figure*} \section{Solving the aperture problem} \label{sec:ap} In this section, we study the aperture problem and the flow refinement process. We first explain our methodology and then present the results. \subsection{Methodology} In order to determine until what scale of input stimuli FlowNetS can resolve the aperture problem, three different versions of this network are trained under the same circumstances with varying receptive field sizes. The receptive field size is defined as the region in the input images which affects the value of the feature map at a particular layer and feature map location. Therefore, we modify the filter size of the convolutional kernels in \texttt{c6}, which is actually composed of two layers: \texttt{c6\_0} and \texttt{c6\_1}. The original (and our) FlowNetS uses 3x3 kernels in these layers, which leads to a receptive field size of 383 pixels in the \texttt{f6} flow map. We train two additional models with kernels sizes (1x1, 3x3) and (1x1, 1x1) for \texttt{c6\_0} and \texttt{c6\_1}, which we name FlowNetXS and FlowNetXXS, and whose \texttt{f6} receptive field size is 255 pixels and 191 pixels, respectively. For the three of these networks, the receptive field size increases in the expanding part of the architecture due to the upconvolutional layers. As input, we use a diagonally translating bar of different scales with motion magnitude $|\mathbf{u}|=64$ pixels. We determine the error at the center of the bar, and at three flow maps of different resolutions: \texttt{f6}, \texttt{f4}, and \texttt{f2} (see Fig. \ref{fig:archflownet}). \subsection{Results} In Fig. \ref{fig:aperture} (left), the FlowNetS response to a downward left translating bar of varying scale is shown. Firstly, the flow becomes more and more refined in the expanding part of the architecture. Secondly, the network is able to extrapolate motion cues from the edges of the bar towards the center, but only to an extent determined by the scale of the bar. Fig. \ref{fig:aperture} (right) shows the average End-Point-Error (EPE) of FlowNetS, FlowNetXS, and FlowNetXXS in response to two translating bars of different scales moving upward right and downward left, respectively. As shown, the ability to resolve the aperture problem is related to the receptive field size, and networks with larger receptive fields are able to resolve the aperture problem at larger scales. \section{Discussion and future work} \label{sec:dis} \subsection{Impact on Computer Vision} Due to the emergence of Gabor-like filters in other learning-based methods, our work started out with the expectation of also finding Gabor-like filters in FlowNetS. Traditional Gabor filters for optical flow estimation had certain disadvantages. They deal badly with deviations from translation, varying contrast due to changing lighting conditions, and are subject to the uncertainty relation, which corresponds to the balance between localization of the stimuli in the spatial domain and resolution in the frequency domain. FlowNetS successfully copes with all of these issues. We have shown that deviations from translations are dealt with by additional filters that are sensitive to more complex motion types. Moreover, \textit{Mayer et al.} \cite{Mayer2018} showed that FlowNet is able to cope with varying contrast over time due to changing lighting conditions. Lastly, we have demonstrated that FlowNetS is able to achieve a better spatial localization of motion cues in the expanding part of the network, thus overcoming the uncertainty relation. In terms of accuracy, FlowNetS did not reach the levels of state-of-the-art methods. For example, it has poor performance on sub-pixel flow \cite{Ilg2017}. One reason for this might be the large number of strides utilized before the initial flow prediction is made. Also, our analysis shows that a Gabor filter based on two frames results in a large temporal frequency bandwidth, and hence limited performance concerning flow velocity estimation. This is narrowed somewhat by the non-linear transformations due to the ReLU activation function and bias term. However, our analysis indicates that this could be further improved by using more frames and thus providing more temporal information to the network When using translating plane waves as input to FlowNetS, we showed that only 592 of the 1024 \texttt{c6} filters have an activation larger than zero. Future work should delve into this, and study the selectivity of the dormant filters through more complex input patterns. However, the high similarity of the active filters to the Gabor model already suggests that it would also be worth studying a hybrid FlowNetS network, in which there is a fixed Gabor filter bank (extended with rotation and dilation features) followed by a convolutional multi-layer loss flow refinement. This would greatly reduce training time, and, most probably, improve the generalizability of the network. \subsection{Impact on biology} We have used and extended methods from neuropsychology for determining the types of motion filters represented by neurons in the deep \texttt{c6} layer of FlowNetS. The analysis gave very similar results to those on neurons in the mammalian visual cortex. First, many filter responses fit very accurately with Gabor filters that capture translational motion. Second, the spatial and orientation bandwidth statistics show similarity to bandwidths of neurons found in the mammalian visual cortex. We report a median spatial frequency bandwidth of 1.36 octaves, while \textit{De Valois et al.} \cite{DeValois1982a} report 1.4 octaves for the macaque visual cortex. Similarly, we find a median orientation bandwidth of 52 degrees, while \textit{De Valois et al.} \cite{DeValois1982b} find 65 degrees. These similarities may be due to similar optical flow statistics being perceived both by the network and the animals. Third, as in neuropsychological experiments \cite{Deangelis1993}, we observed that some filters respond poorly to translating plane waves. Our analysis shows that such poor response may be due to the filters being sensitive to more complex motions such as dilation and rotation. Indeed, in the human brain, channels sensitive to dilation have been found \cite{Regan1978a}. However, this did not provide conclusive evidence of neurons sensitive to dilation. Our analysis and results suggest that it is worth looking for dilation- and rotation-sensitive neurons in animal brains. In fact, one could even extend the analysis to also check for shear, as this forms an additional basis for the flow field derivatives \cite{Longuet-Higgins1980}. \section{Conclusion} \label{sec:conc} We have employed a spectral response fitting approach from neuropsychology to demonstrate that the deepest layer of FlowNetS essentially encodes a bank of spatiotemporal Gabor filters. Although accurate fits were obtained, the spectral response fitting approach is limited, since it is not able to identify the exact motion pattern causing the maximum activation of a filter. In this work, we have already shown that the network also contains a large number of filters that are more sensitive to dilation and rotation than to translation, but more complex motion filters may be present. Finally, we have studied how FlowNetS tackles the aperture problem. Our results suggest that, on the one hand, the receptive field size is highly correlated to the scale at which the network can resolve the aperture problem. On the other hand, the expanding part of the network allows to solve the aperture problem at slightly larger scales by performing a filling-in function similar to that in mammal vision systems. Future work could: (i) perform a similar analysis on SpyNet \cite{Ranjan2017a}, (ii) study the neural response to more complex motion patterns like compositions of affine and 3D motion, as present in more realistic synthetic training datasets (e.g., FlyingThings \cite{Mayer2016}), (iii) attempt to improve FlowNetS' performance by using smaller strides or more input images, and (iv) employ our extended spectral response fitting method to investigate if animal brains have dilation- and rotation-sensitive neurons as well. \input{main.bbl} \begin{IEEEbiography}[{\includegraphics[width=1in,height=1.25in,clip,keepaspectratio]{images/DavidDeJong5.pdf}}]{David B. de Jong} received his B.Sc. in Aerospace Engineering from the Delft University of Technology, the Netherlands, in 2016, and his M.Sc in Aerospace Engineering at the Control \& Simulation department from the same university in 2020. His research interest is the intersection of machine learning, neuroscience, and computer vision. \end{IEEEbiography} \begin{IEEEbiography}[{\includegraphics[width=1in,height=1.25in,clip,keepaspectratio]{images/FedericoParedesValles.eps}}]{Federico Paredes-Vall\'es} received his B.Sc. in Aerospace Engineering from the Polytechnic University of Valencia, Spain, in 2015, and his M.Sc. from Delft University of Technology, the Netherlands, in 2018. He is currently a Ph.D. candidate in the Micro Air Vehicle Laboratory at the latter university. His research interest is the intersection of machine learning, neuroscience, computer vision, and robotics. \end{IEEEbiography} \begin{IEEEbiography}[{\includegraphics[width=1in,height=1.25in,clip,keepaspectratio]{images/GuidoDeCroon.eps}}]{Guido~C.~H.~E.~de~Croon} received his M.Sc. and Ph.D. in the field of Artificial Intelligence at Maastricht University, the Netherlands. His research interest lies with computationally efficient algorithms for robot autonomy, with an emphasis on computer vision. Since 2008 he has worked on algorithms for achieving autonomous flight with small and light-weight flying robots, such as the DelFly flapping wing MAV. In 2011-2012, he was a research fellow in the Advanced Concepts Team of the European Space Agency, where he studied topics such as optical flow based control algorithms for extraterrestrial landing scenarios. Currently, he is full professor at Delft University of Technology, the Netherlands, where he is the scientific lead of the Micro Air Vehicle Laboratory. \end{IEEEbiography} \clearpage \pagestyle{empty} \appendices \section{Model details}\label{ap:moddet} Table \ref{tab:flownetdet} outlines the full details of our version of FlowNetS. The name of the \textquote{conv}, \textquote{flow} and \textquote{predict\_flow} layer is abbreviated to \texttt{c}, \texttt{f} and \texttt{pf}, respectively. The change in the \texttt{pf} size from $3 \times 3$ to $1 \times 1$ helps interpretability of the analysis, but does bring the total receptive field size in the \texttt{c6} layer to 383 pixels as opposed to the original size of 511 pixels. The output of the \textquote{predict\_flow} layer is called \textquote{flow}. In Table \ref{tab:perfcomp} a performance comparison between the slightly modified version of FlowNetS studied in this article and the original version of \textit{Dosovitskiy et al.} [16] can be found on the FlyingChairs [16] and MPI sintel [54] datasets. \begin{table*}[!htbp] \centering \caption{Full details of our version of FlowNetS.} \label{tab:flownetdet} \def1.2{1.2} \begin{tabular}{lccccccc} \hline \textbf{Name} & \textbf{Kernel} & \textbf{Stride} & \textbf{Padding} & \textbf{Ch I/O} & \textbf{In Res} & \textbf{Out Res} & \textbf{Input} \\ \hline conv1 & 7x7 & 2 & 3 & 6/64 & 512x384 & 256x192 & Images \\ conv2 & 5x5 & 2 & 2 & 64/128 & 256x192 & 128x96 & conv1 \\ conv3\_0 & 5x5 & 2 & 2 & 128/256 & 128x96 & 64x48 & conv2 \\ conv3\_1 & 3x3 & 1 & 1 & 256/256 & 64x48 & 64x48 & conv3\_0 \\ conv4\_0 & 3x3 & 2 & 1 & 256/512 & 64x48 & 32x24 & conv3\_1 \\ conv4\_1 & 3x3 & 1 & 1 & 512/512 & 32x24 & 32x24 & conv4\_0 \\ conv5\_0 & 3x3 & 2 & 1 & 512/512 & 32x24 & 16x12 & conv4\_1 \\ conv5\_1 & 3x3 & 1 & 1 & 512/512 & 16x12 & 16x12 & conv5\_0 \\ conv6\_0 & 3x3 & 2 & 1 & 512/1024 & 16x12 & 8x6 & conv5\_1 \\ conv6\_1 & 3x3 & 1 & 1 & 1024/1024 & 8x6 & 8x6 & conv6\_0 \\ \hline predict\_flow6 & 1x1 & 1 & 1 & 1024/2 & 8x6 & 8x6 & conv6\_1 \\ \hline upconv5 & 4x4 & 2 & 1 & 1024/512 & 8x6 & 16x12 & conv6\_1 \\ predict\_flow5 & 1x1 & 1 & 1 & 1026/2 & 16x12 & 16x12 & upconv5+conv5\_1+flow6 \\ upconv4 & 4x4 & 2 & 1 & 1026/256 & 16x12 & 32x24 & upconv5+conv5\_1+flow6 \\ predict\_flow4 & 1x1 & 1 & 1 & 770/2 & 32x24 & 32x24 & upconv4+conv4\_1+flow5 \\ upconv3 & 4x4 & 2 & 1 & 770/128 & 32x24 & 64x48 & upconv4+conv4\_1+flow5 \\ predict\_flow3 & 1x1 & 1 & 1 & 386/2 & 64x48 & 64x48 & upconv3+conv3\_1+flow4 \\ upconv2 & 4x4 & 2 & 1 & 386/64 & 64x48 & 128x96 & upconv3+conv3\_1+flow4 \\ predict\_flow2 & 1x1 & 1 & 1 & 192/2 & 128x96 & 128x96 & upconv2+conv2+flow3 \\ \hline \end{tabular}% \end{table*} \begin{table*}[!htbp] \centering \caption{Performance comparison between the original version of FlowNetS and ours on the MPI-Sintel [54] and FlyingChairs [16] datasets.} \label{tab:perfcomp} \def1.2{1.2} \resizebox{\textwidth}{!}{% \begin{tabular}{lp{60mm}lll} \hline \textbf{Model name} & \textbf{Model details} & \textbf{FlyingChairs test {[}EPE{]}} & \textbf{MPI Sintel clean train {[}EPE{]}} & \textbf{MPI Sintel Final train {[}EPE{]}} \\ \hline FlowNetS [16] & Original & 2,71 & 4,50 & 5,45 \\ FlowNetS-ours & ReLu activation function, \texttt{pf} layers with 1x1 kernels and no bias term, 300K training iterations, no data augmentation between frames & 3,10 & 5,06 & 5,81 \\ \hline \end{tabular}% } \end{table*} \section{Grid search parameters} \label{ap:params} The parameter ranges used for the translation gridsearch are shown in Table \ref{tab:gridtrans}, while Table \ref{tab:fittrans} contains the parameters used for the spectral Gabor response profile fitting. The parameter ranges used for the dilation gridsearch can found in Table \ref{tab:griddil}. Note that due to rotational symmetry, the initial orientation $\theta$ only varies from 0 to 170 degrees. The parameters used for the rotation gridsearch are shown in Table \ref{tab:gridrot}. For this gridsearch, $\theta$ is also constrained from 0 to 170 degrees due to rotational symmetry. Note that the half spatial wavelength $\lambda /2$ can be transformed to spatial frequency $F_0$ using the relation $F = 1/2\lambda$. \begin{table}[!htbp] \centering \caption{Parameter ranges used for the translating plane wave gridsearch.} \label{tab:gridtrans} \def1.2{1.2} \resizebox{.9\linewidth}{!}{ \begin{tabular}{lll} \hline \textbf{Parameter} & \textbf{Unit} &\textbf{Range {[}start, stop, step size{]}} \\ \hline $\lambda /2$ & pixels & {[}16, 800, 16{]} \\ $\theta$ & degrees &{[}0, 350, 10{]} \\ $f_{t}$ & cycles per frame &{[}0.0, 0.5, 0.01{]} \\ $\varphi$ & degrees &{[}-180, 170, 10{]} \\ \hline \end{tabular}} \end{table} \begin{table}[!htbp] \centering \caption{Parameter ranges used for the Gabor spectral profile fitting process.} \label{tab:fittrans} \def1.2{1.2} \resizebox{.9\linewidth}{!}{ \begin{tabular}{lll} \hline \textbf{Parameter} & \textbf{Unit} &\textbf{Range {[}start, stop, number of points{]}} \\ \hline $\lambda /2$ & cycles per pixel & {[}16, 800, 50{]} \\ $\theta$ & degrees &{[}0, 350, 36{]} \\ $f_{t}$ & cycles per frame &{[}-0.5, 0.5, 50{]} \\ \hline \end{tabular}} \end{table} \begin{table}[!htbp] \centering \caption{Parameter ranges used for the dilating wave gridsearch.} \label{tab:griddil} \def1.2{1.2} \resizebox{.9\linewidth}{!}{ \begin{tabular}{lll} \hline \textbf{Parameter} & \textbf{Unit} &\textbf{Range {[}start, stop, step size{]}} \\ \hline $\lambda /2$ & pixels & {[}50, 400, 10{]} \\ $\theta$ & degrees &{[}0, 170, 10{]} \\ $s_f$ & - &{[}0.5, 2.0, 0.1{]} \\ $\varphi$ & degrees &{[}-180, 170, 10{]} \\ \hline \end{tabular}} \end{table} \begin{table}[!htbp] \centering \caption{Parameter ranges used for the rotation gridsearch. The angular velocity $\omega$ is limited between $-0.5$ and $0.5$ cycles per sample which corresponds to $-\frac{1}{2}\pi$ and $\frac{1}{2}\pi$ radians per frame respectively.} \label{tab:gridrot} \def1.2{1.2} \resizebox{.9\linewidth}{!}{ \begin{tabular}{lll} \hline \textbf{Parameter} & \textbf{Unit} &\textbf{Range {[}start, stop, step size{]}} \\ \hline $\lambda /2$ & pixels & {[}50, 400, 10{]} \\ $\theta$ & degrees &{[}0, 170, 10{]} \\ $\omega$ & cycles per frame &{[}-0.5, 0.5, 0.1{]} \\ $\varphi$ & degrees &{[}-180, 170, 10{]} \\ \hline \end{tabular}} \end{table} \end{document}
{'timestamp': '2020-04-21T02:27:42', 'yymm': '2004', 'arxiv_id': '2004.09317', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09317'}
arxiv
\section{Introduction} \begin{figure}[t] \begin{center} \includegraphics[width=0.8\linewidth]{img/marked_samples.png} \end{center} \caption{Three sample COVID-19 images, and the corresponding marked areas by our radiologist.} \label{fig:sample3} \end{figure} Since December 2019, a novel corona-virus (SARS-CoV-2) has spread from Wuhan to the whole China, and many other countries. By April 18, more than 2 million confirmed cases, and more than 150,000 deaths cases were reported in the world \cite{Radio1}. Due to unavailability of therapeutic treatment or vaccine for novel COVID-19 disease, early diagnosis is of real importance to provide the opportunity of immediate isolation of the suspected person and to decrease the chance of infection to healthy population. Reverse transcription polymerase chain reaction (RT-PCR) or gene sequencing for respiratory or blood specimens are introduced as main screening methods for COVID-19 \cite{Radio2}. However, total positive rate of RT-PCR for throat swab samples is reported to be 30 to 60 percent, which accordingly yields to un-diagnosed patients, which may contagiously infect a huge population of healthy people \cite{Radio3}. Chest radiography imaging (e.g., X-ray or computed tomography (CT) imaging) as a routine tool for pneumonia diagnosis is easy to perform with fast diagnosis. Chest CT has a high sensitivity for diagnosis of COVID-19 \cite{Radio4} and X-ray images show visual indexes correlated with COVID-19 \cite{Radio5}. The reports of chest imaging demonstrated multilobar involvement and peripheral airspace opacities. The opacities most frequently reported are ground-glass (57\%) and mixed attenuation (29\%) \cite{Radio6}. During the early course of COVID-19, ground glass pattern is seen in areas that edges the pulmonary vessels and may be difficult to appreciate visually \cite{Radio7}. Asymmetric patchy or diffuse airspace opacities are also reported for COVID-19 \cite{Radio8}. Such subtle abnormalities can only be interpreted by expert radiologists. Considering huge rate of suspected people and limited number of trained radiologists, automatic methods for identification of such subtle abnormalities can assist the diagnosis procedure and increase the rate of early diagnosis with high accuracy. Artificial intelligence (AI)/machine learning solutions are potentially powerful tools for solving such problems. So far, due to the lack of availability of public images of COVID-19 patients, there has not been any detailed study looking at the potential of AI/machine learning solutions for automatic detection of COVID-19 from X-ray (or Chest CT) images. Recently a small dataset of COVID-19 X-ray images have been collected by some researchers, which made it possible for AI researchers to train machine learning models to perform automatic COVID-19 diagnostics from X-ray images \cite{covid_chest_paper}. These images were extracted from academic publications reporting the results on COVID-19 X-ray and CT images. With the help of a board-certified radiologist, we re-labeled those images, and only kept the ones which were detected to have a clear sign of COVID-19 by our radiologist. Three sample images with their corresponding marked areas by our radiologist are shown in Figure \ref{fig:sample3}. We then used a subset of images from ChexPert \cite{chexpert} dataset, as the negative samples for COVID-19 detection. The combined dataset has around 5,000 Chest X-ray images (called COVID-Xray-5k), which is dividing into 2,000 training, and 3,000 testing samples. It is worth mentioning that some of the earlier works in the past few weeks used the images from pediatric patients of one to five years old (from a Kaggle competition) as the negative class, which may not be the best idea, as there is a big difference among the age range of the positive and negative class in that case. We then use a machine a learning framework to predict the COVID-19, from the Chest X-ray images. Unlike the classical approaches for medical image classification which follow a two-step procedure (hand-crafted feature extraction+recognition), we use an end-to-end deep learning framework which directly predicts the COVID-19 from raw images without any need of feature extraction. Deep learning based models (and more specifically convolutional neural networks (CNN)) have been shown to outperform the classical AI approaches in most of computer vision and and medical image analysis tasks in recent years, and have been used in a wide range of problems from classification, segmentation, face recognition, to super-resolution and image enhancement \cite{cnn,cnn2,cnn3,cnn4,cnn5}. Here, we train 4 popular convolutional networks which have achieved promising results in several tasks during recent years (including ResNet18, ResNet50, SqueezeNet, and DesneNet-161) on COVID-Xray-5k dataset, and analyze their performance for COVID-19 detection. Since so far there are only a few X-ray images publicly available for COVID-19 class, we cannot simply train these models from scratch. We used two strategies to address the COVID-19 image scarcity issue in this work: \begin{itemize} \item We use data augmentation to create transformed version of COVID-19 images (such as flipping, small rotation, adding small amount of distortions), to increase the number of samples by a factor of 4. \item Instead of training these models from scratch, we fine-tune the last layer of the pre-trained version of these models on ImageNet. In this way, the model can be trained with less labeled samples from each class. \end{itemize} The above two strategies help us to train these networks with the available images, and achieve reasonable performance on the test set of 3,000 images. The best performing model out of the above four networks, achieves a sensitivity of 97.5\%, and specificity of around 95\%. Since the number of samples for COVID-19 class is limited, we also calculate the confidence interval of the performance metrics. To report a summarizing performance of these models, we provide the Receiver operating characteristic (ROC) curve, and area under the curve (AUC) for each of these models. Here are the contribution of this paper: \begin{itemize} \item We prepared a dataset of 5,000 images with binary labels, for COVID-19 detection from Chest X-ray images. This dataset can serve as a benchmark for the research community. The images in COVID-19 class, are labeled by a board-certified radiologist, and only those with a clear sign are used for testing purpose. \item We trained 4 promising deep learning models on this dataset, and evaluated their performance on a test set of 3,000 images. Our best performing model achieved a sensitivity rate of 97.5\%, while having a specificity of 95\%. \item We also provided the ROC curve, AUC, and the histogram of the predicted scores by these models. \item We provided a detailed experimental analysis on the performance of these models, in terms of sensitivity, specificity, ROC curve, area under the curve, and confusion matrix. \item We make the dataset, the trained models, and the implementation publicly available. \end{itemize} It is worth to mention that, although the result of this work is very encouraging, given the amount of the labeled data the result of this work is still preliminary, and more concrete conclusion requires further experiments on a larger dataset of COVID-19 labeled X-ray images. We believe this work can serve as a benchmark for future works and comparisons. The structure of the rest of this paper is as follows. Section \ref{sec_dataset} provides a summary of the prepared \textbf{COVID-Xray-5k Dataset}. Section \ref{sec_method} presents the description of the overall proposed framework. Section \ref{sec_result} provides the experimental studies and comparison with previous works. And finally the paper is concluded in Section \ref{sec_conc}. \section{COVID-Xray-5k Dataset} \label{sec_dataset} We have used the X-ray images from two datasets, to create the COVID-Xray-5k dataset. The COVID-Xray-5k dataset contains 2,031 training images, and 3,040 test images. One of the used datasets is the recently published \textbf{Covid-Chestxray-Dataset}, which contains a set of images from publications on COVID-19 topics, collected by Joseph Paul Cohen \cite{covid_chest, covid_chest_paper}. This dataset contains a mix of chest X-ray and CT images. As of March, 23, 2020, it contained 23 CT images (22 COVID-19, and 1 Non-Covid), and 126 X-ray images (102 COVID-19, and 24 Non-COVID images). It is mentioned that this dataset is continuously updated. It also contains some meta-data about each patients, such as sex and age. Our COVID-19 images are all coming from this dataset. The provided 102 COVID-19 images were examined by our board-certified radiologist which led to elimination of all lateral images and some less-reliable anterior-posterior images, yielding 71 X-ray images with COVID-19. Therefore, we have chosen 40 COVID-19 images to include in the test set (to meet some maximum confidence interval value), and 31 COVID-19 images for the training set. Data augmentation is applied to the training set to increase the number of COVID-19 samples to 496 (by a combination of flipping, rotation, small distortion, and over-sampling). We made sure all images for each patient go only to one of the training or test sets. It is worth mentioning that our radiologist marked some of the likely regions, which can have some sign of Covid-19 too. Since the number of Non-Covid images was very small in the \cite{covid_chest} dataset, additional images were employed from the \textbf{ChexPert} dataset \cite{chexpert}, a large public dataset for chest radiograph interpretation consisting of 224,316 chest radiographs of 65,240 patients, labeled for the presence of 14 sub-categories (no-finding, Edema, Pneumonia, etc.). For the non-COVID samples in the training set, we only used images belonging to a single sub-category, composed of 700 images form no-finding class and 100 images from each remaining 13 sub-classes, resulting in 2,000 non-COVID images. As for the Non-COVID samples in the test dataset, we selected 1,700 images from no-finding category and around 100 images from each remaining 13 sub-classes in distinct sub-folders, resulting into 3000 images in total. The exact number of images of each class for both training and testing is given in Table \ref{dataset_count}. \begin{table}[ht] \centering \caption{Number of images per category in COVID-Xray-5k dataset. } \centering \begin{tabular}{|c|c|c|} \hline Split & COVID-19 & Non-COVID\\ \hline Training Set & 31 (496 after augmentation) & 2000 \\ \hline Test Set & 40 & 3000 \\ \hline \end{tabular} \label{dataset_count} \end{table} Figure \ref{dataset_images} shows 16 sample images from COVID-Xray-5k dataset, including 4 COVID-19 images (the first row), 4 normal images from ChexPert (the second row), and 8 images with one of the 13 diseases in ChexPert (third and fourth rows). \begin{figure}[h] \begin{center} \includegraphics[width=1.0\linewidth]{img/fig2.pdf} \end{center} \caption{Sample images from COVID-Xray-5k dataset. The images in the first row show 4 COVID-19 images. The images in the second row are 4 sample images of no-finding category in Non-COVID images from \textbf{ChexPert}. The images in the third and fourth rows give 8 sample images from other sub-categotries in \textbf{ChexPert}.} \label{dataset_images} \end{figure} \section{The Proposed Framework} \label{sec_method} Since so far, the number of publicly available images, which are labeled as COVID-19 are very limited, it may not be possible to train a deep convolutional neural network from scratch to detect COVID-19 from X-ray images. To overcome this issue, we use a well-known strategy in machine learning, called "transfer learning", and fine-tune four popular pre-trained deep neural networks on the training images of COVID-Xray-5k dataset. We will first provide a quick introduction of transfer learning, and then discuss the proposed framework. \subsection{Transfer Learning Approach} In transfer learning, a model trained on one task is re-purposed on another related task, usually by some adaptation toward the new task. For example, one can imagine using an image classification model trained on ImageNet (which contains millions of labeled images) to initiate task-specific learning for COVID-19 detection on a smaller dataset. Transfer learning is mainly useful for tasks where enough training samples are not available to train a model from scratch, such as medical image classification for rare or emerging diseases, in which sufficiently large numbers of labeled samples may not be available. This is especially the case for models based on deep neural networks, which have a large number of parameters to train. By using transfer learning, the model parameters start with a;ready-good initial values that only need some small modifications to be better curated toward the new task. There are two main ways in which the pre-trained model is used for a different task. In one approach, the pre-trained model is treated as a feature extractor (i.e., the internal weights of the pre-trained model are not adapted to the new task), and a classifier is trained on top of it to perform classification. In another approach, the whole network, or a subset thereof, is fine-tuned on the new task. Therefore the pre-trained model weights are treated as the initial values for the new task, and are updated during the training stage. In our case, since the number of images in COVID-19 category is very limited, we only fine-tune the last layer of the convolutional neural networks, and essentially use the pre-trained models as a feature extractor. We evaluate the performance of four popular pre-trained models, ResNet18 \cite{resnet}, ResNet50 \cite{resnet}, SqueezeNet \cite{squeeze}, and DenseNet-121 \cite{densenet}. In the next section we provide a quick overview of the architecture of these models, and how they are used for COVID-19 recognition. \subsection{COVID-19 Detection Using Residual ConvNet -- ResNet18 and ResNet50} One of the models used in this work, is the pre-trained ResNet18, trained on ImageNet dataset. ResNet is one of the most popular CNN architecture, which provides easier gradient flow for more efficient training, and was the winner of the 2015 ImageNet competition. The core idea of ResNet is introducing a so-called \textit{identity shortcut connection} that skips one or more layers. This would help the network to provide a direct path to the very early layers in the network, making the gradient updates for those layers much easier. \iffalse \begin{figure}[h] \begin{center} \includegraphics[width=0.7\linewidth]{img/resnet.png} \end{center} \caption{The residual block used in ResNet model, courtesy of \cite{resnet}} \label{fig:Resnet} \end{figure} \fi The overall block diagram of ResNet18 model, and how it is used for COVID-19 detection is illustrated in Figure \ref{fig:ResnetNN}. ResNet50 architecture is pretty similar to ResNet18, the main difference being having more layers. \begin{figure}[h] \begin{center} \includegraphics[page=2,width=0.9\linewidth]{img/ResNet_arch.pdf} \end{center} \caption{The architecture of ResNet18 model \cite{resnet}.} \label{fig:ResnetNN} \end{figure} \subsection{COVID-19 Detection Using SqueezeNet} SqueezeNet \cite{squeeze} proposed by Iandola et al., is a small CNN architecture, which achieves AlexNet-level \cite{alexnet} accuracy on ImageNet with 50x fewer parameters. Using model compression techniques, the authors were able to compress SqueezeNet to less than 0.5MB, which made it very popular for applications that require light-weight models. They alternate a 1x1 layer that "squeezes" the incoming data in the vertical dimension followed by two parallel 1x1 and 3x3 convolutional layers that "expand" the depth of the data again. Three main strategies used in SqueezeNet includes: replace 3x3 filters with 1x1 filters, decrease the number of input channels to 3x3 filters, Down-sample late in the network so that convolution layers have large activation maps. Figure \ref{fig:squeezenet} shows the architecture of a simple SqueezeNet. \begin{figure}[h] \begin{center} \includegraphics[page=2,width=0.9\linewidth]{img/squeeze_arch.png} \end{center} \caption{The architecture of SqueezeNet based on "fire modules". Courtesy of Google \cite{googlecolab}.} \label{fig:squeezenet} \end{figure} \subsection{COVID-19 Detection Using DenseNet} Dense Convolutional Network (DenseNet) is another popular architecture \cite{densenet}, which was the winner of the 2017 ImageNet competition. In DenseNet, each layer obtains additional inputs from all preceding layers and passes on its own feature-maps to all subsequent layers. Each layer is receiving a “collective knowledge” from all preceding layers. Since each layer receives feature maps from all preceding layers, network can be thinner and compact, i.e., number of channels can be fewer (so, it have higher computational efficiency and memory efficiency). The architecture of sample DenseNet is shown in Figure \ref{fig:densenet}. \begin{figure}[h] \begin{center} \includegraphics[page=2,width=0.8\linewidth]{img/densenet.png} \end{center} \caption{The architecture of a DenseNet with 5 layers, with expansion of 4. Courtesy of model \cite{densenet}.} \label{fig:densenet} \end{figure} \subsection{Model Training} All employed models are trained with a cross-entropy loss function, which tries to minimize the distance between the predicted probability scores, and the ground truth probabilities (derived from labels), and is defined as: \begin{equation} \begin{aligned} & \mathcal{L}_{CE}= - \sum_{i=1}^N p_i \log q_i \; , \end{aligned} \end{equation} where $p_i$ and $q_i$ denote the ground-truth, and predicted probabilities for each image, respectively. We can then minimize this loss function using stochastic gradient descent algorithm (and its variations). We also tried to add regularization to the loss function, but the resulting model was not better than the case without regularization. \section{Experimental Results} \label{sec_result} In this section we provide the experimental results of the four neural networks trained for COVID-19 detection, the histogram of their predicted scores on the test images, and quantitative performance. \subsection{Model Hyper-parameters} We fine-tuned each model for 100 epochs. The batch size is set to 20, and ADAM optimizer is used to optimize the loss function, with a learning rate of 0.0001. All images are down-sampled to 224x224 before being fed to the neural network (as these pre-trained models are usually trained with a specific image resolution). All our implementations are done in PyTorch \cite{pytorch}, and are publicly available here: https://github.com/shervinmin/DeepCovid.git \subsection{Evaluation Metrics} There are different metrics which can be used for evaluating the performance of classification models, such as classification accuracy, sensitivity, specificity, precision, and F1-score. Since the current test dataset is highly imbalanced (as there are 40 images with COVID-19, and 3000 images that are Non-COVID), sensitivity and specificity are two propoer metrics which can be used for reporting the model performance. These metrics are also widely used in medical domain, and can be defined as Eq \ref{metrics}: \begin{equation} \begin{split} \textbf{Sensitivity} & = \frac{\text{\#Images correctly predicted as COVID-19}}{\text{\#Total COVID-19 Images}} \; ,\\ \textbf{Specificity} & = \frac{\text{\#Images correctly predicted as Non-COVID}}{\text{\#Total Non-COVID Images}}\; . \label{metrics} \end{split} \end{equation} \subsection{Model Predicted Scores} As mentioned earlier, we focused on four popular convolutional networks, ResNet18, ResNet50, SqueezeNet, DenseNet121. These models predict a probability score for each image, which shows the likelihood of the image being detected as COVID-19. By comparing this probability with a cut-off threshold, we can derive a binary label showing if the image is COVID-19 or not. An ideal model should predict the probability of all COVID-19 samples close to 1, and non-COVID samples close to 0. Figures \ref{fig:resnet18_scores}, \ref{fig:resnet50_scores}, \ref{fig:SqueezeNet_scores}, and \ref{fig:densenet_scores} show the distribution of predicted probability scores for the images in the test set, by ResNet18, ResNet50, SqueezeNet, and DenseNet-161 respectively. Since Non-COVID class in our study contains both normal cases, as well as other types of diseases, we provide the distribution of predicted scores for three classes: COVID-19, Non-COVID normal, and Non-COVID other diseases. As we can see the Non-Covid images with other types disease have slightly larger scores than the Non-COVID normal cases. This makes sense, since those images are more difficult to distinguish from COVID-19, than normal samples. Based on these figures, the images for COVID-19 patients, are predicted to have much higher probabilities than the Non-COVID images, which is really encouraging, as it shows the model is learning to discriminate COVID-19 from non-COVID images. Among different models, it can be observed that SqueezeNet does a much better job in pushing the predicted scores for COVID-19 and Non-COVID images far apart from each other. \begin{figure}[h] \begin{center} \includegraphics[width=0.7\linewidth]{img/hist_resnet18.png} \end{center} \caption{The predicted probability scores by ResNet18 on the test set.} \label{fig:resnet18_scores} \end{figure} \begin{figure}[h] \begin{center} \includegraphics[width=0.71\linewidth]{img/hist_resnet50.png} \end{center} \caption{The predicted probability scores by ResNet50 on the test set.} \label{fig:resnet50_scores} \end{figure} \begin{figure}[h] \begin{center} \includegraphics[width=0.7\linewidth]{img/hist_Squeezenet.png} \end{center} \caption{The predicted probability scores by SqueezeNet on the test set.} \label{fig:SqueezeNet_scores} \end{figure} \begin{figure}[h] \begin{center} \includegraphics[width=0.7\linewidth]{img/hist_densenet161.png} \end{center} \caption{The predicted probability scores by DesneNet-121 on the test set.} \label{fig:densenet_scores} \end{figure} \subsection{Model Sensitivity and Specificity} As we can see from previous part, each model predicts a probability score showing the chance of the image being COVID-19. We can then compare these scores with a threshold to infer if the image is COVID-19 or not (if the score is bigger than the threshold it will be predicted as COVID-19). The predicted labels are then used to estimate the sensitivity and specificity of each model. Depending on the value of cut-off threshold, we can get different sensitivity and specificity rates for each model. Tables \ref{tab:resnet_thresh}, \ref{tab:resnet50_thresh}, \ref{tab:squeezenet_thresh}, and \ref{tab:densenet_thresh} show the sensitivity and specificity rates for different thresholds, using ResNet18, ResNet50, SqueezeNet, and DenseNet-121 models, respectively. As we can see, all these models achieve very promising results, in which for a sensitivity rate of around 97\%, their specificity rate is in the range of 84-97\%. SqueezeNet and ResNet50 achieve slightly better performance than the other models. \begin{table}[ht] \centering \caption{Sensitivity and specificity rates of ResNet18 model, for different threshold values.} \centering \begin{tabular}{|c|c|c|} \hline Threshold & Sensitivity & Specificity\\ \hline 0.04 & 100\% & 81.6\% \\ \hline 0.055 & 97.5\% & 88.8\% \\ \hline 0.08 & 95\% & 94.1\% \\ \hline 0.18 & 92.5\% & 98.8\% \\ \hline 0.2 & 87.5\% & 99.2\% \\ \hline \end{tabular} \label{tab:resnet_thresh} \end{table} \begin{table}[ht] \centering \caption{Sensitivity and specificity rates of ResNet50 model, for different threshold values.} \centering \begin{tabular}{|c|c|c|} \hline Threshold & Sensitivity & Specificity\\ \hline 0.11 & 97.5\% & 90.5\% \\ \hline 0.2 & 95\% & 97.5\% \\ \hline 0.24 & 92.5\% & 98.8\% \\ \hline 0.28 & 87.5\% & 99.2\% \\ \hline \end{tabular} \label{tab:resnet50_thresh} \end{table} \begin{table}[ht] \centering \caption{Sensitivity and specificity rates of SqueezeNet model, for different threshold values.} \centering \begin{tabular}{|c|c|c|} \hline Threshold & Sensitivity & Specificity\\ \hline 0.08 & 100\% & 95.6\% \\ \hline 0.18 & 97.5\% & 97.8\% \\ \hline 0.2 & 95.0\% & 98.2\% \\ \hline 0.32 & 87.5\% & 99.3\% \\ \hline \end{tabular} \label{tab:squeezenet_thresh} \end{table} \begin{table}[ht] \centering \caption{Sensitivity and specificity rates of DenseNet-121 model, for different threshold values.} \centering \begin{tabular}{|c|c|c|} \hline Threshold & Sensitivity & Specificity\\ \hline 0.08 & 100\% & 74.2\% \\ \hline 0.1 & 97.5\% & 81.3\% \\ \hline 0.15 & 92.5\% & 92.4\% \\ \hline 0.2 & 87.5\% & 96.3\% \\ \hline \end{tabular} \label{tab:densenet_thresh} \end{table} \subsection{Small Number of COVID-19 Cases and Model Reliability} It is worth mentioning that since so far the number of reliably labeled COVID-19 X-ray images is very limited, and we only have 40 test images in COVID-19 class, it is hard to believe that all the sensitivity and specificity rates reported above of are reliable. Ideally more experiments on a larger number of test samples with COVID-19 is needed to derive a more reliable estimation of sensitivity rates. We can however estimate the 95\% confidence interval of the reported sensitivity and specificity rates here, to see what is the possible range of these values for the current number of test samples in each class. The confidence interval of the accuracy rates can be calculated as Eq \ref{eq:confidence}: \begin{equation} \begin{aligned} r= z \ \ \sqrt{\frac{accuracy \ (1-accuracy)}{N}} \; , \end{aligned} \label{eq:confidence} \end{equation} where $z$ denotes the significance level of the confidence interval (the number of standard deviation of the Gaussian distribution), and accuracy is the estimated accuracy (in our cases sensitivity and specificity), and $N$ denotes the number of samples for that class. Here we use 95\% confidence interval, for which the corresponding value of $z$ is 1.96. As for COVID-19 diagnostic, having a sensitive model is crucial, we choose the cut-off threshold corresponding to a sensitivity rate of 97.5\% for each model, and compare their specificity rates. Table \ref{table_comp} provides a comparison of the performance of these four models on the test set. As we can see the confidence interval of specificity rates are small (around 1\%), since we have around 3000 samples for this class, whereas for the sensitivity rate we get slightly higher confidence interval (around 4.8\%) because of the limited number of samples. \begin{table}[ht] \centering \caption{Comparison of sensitivity and specificity of four state-of-the-art deep neural networks.} \centering \begin{tabular}{|c|c|c|} \hline Model & Sensitivity & Specificity \\ \hline ResNet18 & 97.5\% $\pm$ 4.8\% & 88.8\% $\pm$ 1.1\% \\ \hline ResNet50 & 97.5\% $\pm$ 4.8\%& 90.5\% $\pm$ 1.1\% \\ \hline SqueezeNet & 97.5\% $\pm$ 4.8\%& 97.8\% $\pm$ 0.5\% \\ \hline Densenet-121 & 97.5\% $\pm$ 4.8\%& 81.3\% $\pm$ 1.4\% \\ \hline \end{tabular} \label{table_comp} \end{table} \subsection{The ROC Curve of Each Model and Confusion Matrix} As we can, it is hard to compare different models only based on their sensitivity and specificity rates, since these rates change by varying the cut-off thresholds. To see the overall comparison between these models, we need to look at the comparison for all possible threshold values. One way to do this, is through the Receiver Operating Characteristic (ROC) curve, which provides the true positive rate as a function of false positive rate. The ROC curve of these four models is shown in Figure \ref{fig:roc}. As we can see all models have relatively similar area under the curve, but SqueezeNet achieve slightly higher AUC than other models. \begin{figure}[h] \begin{center} \includegraphics[width=0.85\linewidth]{img/ROC_covid_normal.png} \end{center} \caption{The ROC curve of four CNN architectures on COVID-19 test set.} \label{fig:roc} \end{figure} To see the exact number of correctly samples as COVID-19 and Non-COVID, we also provide the confusion matrix the two top-performing models. The confusion matrix of the fine-tuned ResNet50, and SqueezeNet models on the set of 3040 test images are shown in Figure \ref{fig:conf_mat_res50}, and \ref{fig:conf_mat_squ}. \begin{figure}[h] \begin{center} \includegraphics[width=0.6\linewidth]{img/conf_resnet50.png} \end{center} \caption{The confusion matrix of the proposed ResNet50 model.} \label{fig:conf_mat_res50} \end{figure} \begin{figure}[h] \begin{center} \includegraphics[width=0.6\linewidth]{img/conf_Squeezenet.png} \end{center} \caption{The confusion matrix of the proposed SqueezeNet framework.} \label{fig:conf_mat_squ} \end{figure} \iffalse \subsection{The Heatmap of Potentially Infected Regions} We used a simple technique to detect the potentially infected areas while performing COVID-19 detection. This technique is inspired by the work pf Zeiler and Fergus \cite{fergus}, to visualize the result of deep convolutional networks. We start from the top-left corner of the image, and each time zero out a square region of size $N$x$N$ inside the image, and make a prediction using the trained model on the occluded image. If occluding that region causes the model to mis-classify a COVID-19 image as Non-COVID, that area would be considered as a potentially infected region in chest X-ray images (mainly because removing the information of that part, led the model mis-classification). On the other hand, if removing that region does not impact the model's prediction, we infer that region is not as infected. Now if we repeat this procedure for different sliding windows of $N$x$N$, each time shifting them with a stride of $S$, we can get a saliency map of the potentially infected regions in detecting COVID-19. The detected regions for four example COVID-19 images are shown in Figure \ref{fig_heatmaps}. \begin{figure}[h] \begin{center} \includegraphics[width=0.7\linewidth]{img/test0_str12_blk64.png} \includegraphics[width=0.7\linewidth]{img/test1_str12_blk64.png} \includegraphics[width=0.7\linewidth]{img/test5_str12_blk64.png} \includegraphics[width=0.7\linewidth]{img/test7_str12_blk64.png} \end{center} \caption{The detected potentially infected regions in chest X-ray, for several COVID-19 patients, by the proposed framework.} \label{fig_heatmaps} \end{figure} \fi \section{Conclusion} \label{sec_conc} In this work we propose a deep learning framework for COVID-19 detection from Chest X-ray images, by fine-tuning four pre-trained convolutional models (ResNet18, ResNet50, SqueezeNet, and DenseNet-121) on our training set. We prepared a dataset of around 5k images, called COVID-Xray-5k (using images from two datasets), with the help of a board-certified radiologist to confirm the COVID-19 labels. We make this dataset publicly available for the research community to use as a benchmark for training and evaluating future machine learning models for COVID-19 binary classification task. We performed a detail experimental analysis evaluating the performance of each of these 4 models on the test set of of COVID-Xray-5k Dataset, in terms of sensitivity, specificity, ROC, and AUC. For a sensitivity rate of 97.5\%, these models achieved a specificity rate of around 90\% on average. This is really encouraging, as it shows the promise of using X-ray images for COVID-19 diagnostics. This study is conducted on a set of publicly available images, which contains less than 100 COVID-19 images, and more than 5,000 non-COVID images. Due to the limited number of COVID-19 images publicly available so far, further experiments are needed on a larger set of cleanly labeled COVID-19 images for a more reliable estimation of the the sensitivity rates. \section*{Acknowledgment} The authors would like to thank Joseph Paul Cohen for collecting the COVID-Chestxray-dataset. We would also like to thank the providers of ChexPert dataset, which are used as the negative samples in our case.
{'timestamp': '2020-04-21T02:28:54', 'yymm': '2004', 'arxiv_id': '2004.09363', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09363'}
arxiv
\section{Introduction} Developing a way to easily manipulate face expression and head pose of an individual has been the focus of many research groups in the last decade. The baseline solution for this task involves creating a 3D model and animate it accordingly. However, building a photo-realistic head model using standard techniques can take substantial amount of time for a human artist. Many industries could benefit from optimizing this process such as cinematic, advertising and video games; furthermore, it has potential for image enhancement and editing software. A traditional automatic method for face manipulation is based on 3DMM fitting \cite{Blanz:1999:MMS:311535.311556}. Parameters can be estimated from a single image and then changed to obtain different expressions. This method is not sufficient by itself to work with hidden regions, e.g. teeth and closed eyes \cite{yuan2019face}. Other approaches rely on warping from one or more source images to the desired pose to generate guided head images \cite{Wiles18}. A drawback of this solution is the limited amount of variation between the source and target pose it can manage without great loss of quality \cite{zakharov2019fewshot}. New approaches for face image generation have been brought by recent advances in generative adversarial networks (GANs) \cite{NIPS2014_5423}. Seminal papers in this area \cite{karras2018progressive,tero2018style} show that one can generate high resolution realistic figures of human faces using GANs. Our contribution is a new model, Character Adaptive Identity Normalization GAN (CainGAN), that receives figures of faces from a certain individual and produces new ones while preserving the person's identity. CainGAN generates images in novel poses starting from a small set of source pictures with the individual, i.e. a few-shot setting, without any fine-tuning as found in \cite{finn2017model,zakharov2019fewshot}. We conducted experiments to compare images generated by CainGAN, with alternative systems using image-to-image translation \cite{pix2pix2017,wang2018pix2pixHD} and conditioning based on Adaptive Instance Normalization \cite{huang2017adain} using computed embeddings \cite{zakharov2019fewshot}. By performing quantitative measurements on the self-reenactment task we show that our model is able to achieve state-of-the-art results using less data compared to other methods and without fine-tuning. The rest of the paper is structured as follows: In section \ref{sec:related} we make a literature review; the subsequent section describes CainGAN in detail; section \ref{sec:experiments} contains a comparison between different methods and an ablation study. Eventually, we summarize our contributions in section \ref{sec:conclusion}. Code for the implementation of CainGAN is available at \href{https://github.com/TArdelean/CainGAN}{https://github.com/TArdelean/CainGAN} \section{Related Work} \label{sec:related} A number of works on face generation with preservation of identity focus on the talking face task, i.e. the area of interest is the mouth region with motion driven by either audio sources \cite{chen2018lip,XuSoundTV,suwajanakorn2017obama,zhou2019talking} or video to be imitated \cite{ijcai2019-129,zhou2019talking}. These methods cannot be easily extended to synthesize full head images that require handling more variation between poses or hidden elements in the source images. While it is possible to replace the face from an existing head footage, by using a face modeling approach as in \cite{thies2018face2face}, the result of pose manipulation would be limited to face expression. Providing conditional information to several layers of the generator has been widely used to prevent input constraints from vanishing. Good results were obtained especially by modulating activations using AdaINs \cite{chen2018on,huang2017adain,tero2018style} and SPADE \cite{park2019SPADE} that employs spatial denormalization to introduce semantic map constraints. Our model is based on a conditional GAN framework, i.e. instead of generating starting from noise as done traditionally \cite{NIPS2014_5423}, the input of the generative network can take different forms including images \cite{pix2pix2017,park2019SPADE} as done in this work. The use of multiple discriminators to stabilize GAN training has been recently studied in several works \cite{carneiro2019,Durugkar2016GenerativeMN,NIPS2017_6860}. Specifically our model uses two discriminators with different objectives. \section{The CainGAN model} In this section we present the architecture of the proposed model, followed by the training algorithm. Eventually we give some implementation details. \subsection{The Architecture} The goal is to train a generative model that is able to synthesize new images starting from $K$ existing source pictures with the same person. Let $x_i$ denote the $i$-th image of an image sequence $\mathbf{x}$; we uniformly sample $K+1$ distinct images from $\mathbf{x}$. The model receives as input $x_{i_1}, x_{i_2}, ..., x_{i_K}$ along with their corresponding landmark images \cite{bulat2017far} $L(x_{i_1}), L(x_{i_2}), ..., L(x_{i_K})$ and target landmark $L(x_{i_{K+1}})$, then generates a new image $\hat{x}_t$ that must follow target landmark and preserve identity of the person from the $K$ input images. The generated image is expected to be similar to the ground truth image $x_t := x_{i_{K+1}}$. \begin{figure}[!t] \centering \includegraphics[width=\linewidth]{Figures/arhitecture.png} \caption{Full architecture and model workflow. Top side depicts the embedding which is used at each upsampling step to spatially modulate activations. The generator (shown in the bottom side of the figure) starts from the target landmarks $L(x_t)$ to synthesize a new image $\hat{x}_t$. $D_I$ and $D_P$ represent the identity and pose discriminators, respectively.} \label{fig:full_arhi} \end{figure} We propose CainGAN, a model that consists of 4 networks (Figure \ref{fig:full_arhi}) which we will describe in the following. The embedder computes a spatial embedding $e_{x_i}$ from a single input image: $e_{x_i} = E(x_i, L(x_i))$. Implementation details can be found in section \ref{sec:implementation}. In order to use multiple source images, a method to combine the embeddings must be devised. Zakharov et al. in \cite{zakharov2019fewshot} simply averages the one-dimensional tensors computed by the embedder. We observed that weighing the features by their relevance helps to better capture the identity, therefore a responsibility based combining method was developed (eq. \eqref{eq:1}, Figure \ref{fig:comb_emb}). To achieve this, the embedder will also output a weighing tensor $r_{x_i}$ representing the certainty for the computed features. The final identity embedding is calculated by a function $\Psi$ as: \begin{equation} e_x = \Psi\left((e_{x_1}, r_{x_1}), \dots, (e_{x_K}, r_{x_K})\right) = \frac{\sum_{i \in \{i_1, \ldots, i_K\}}e_{x_i} \cdot r_{x_i}}{\sum_{i \in \{i_1, \ldots, i_K\}}r_{x_i}} \label{eq:1} \end{equation} We explored the use of target landmarks $L(x_t)$ as input to the embedder along with $x_i$ and $L(x_i)$ and found this helpful for the generation process, since the identity features can be aligned to the final pose earlier. Hence, this is the version used in our experiments, denoted Targeted Embedder, as illustrated in Figure \ref{fig:temb}. \begin{figure}[!t] \centering \begin{subfigure}{0.57\textwidth} \includegraphics[height=12em]{Figures/comb_emb.png} \caption{Combining embeddings based on responsibility, as in equation \eqref{eq:1}. The weights of the Targeted Embedder (E) are the same for each of the $K$ inputs. The Targeted Embedder is detalied in Figure \ref{fig:temb}.} \label{fig:comb_emb} \end{subfigure}\hspace{0.04\textwidth} \begin{subfigure}{0.37\textwidth} \includegraphics[height=12em]{Figures/t_embedder.png} \caption{The structure of the Targeted Embedder. The real frame $x_i$, its landmark image $L(x_i)$ and target landmarks $L(x_t)$ are concatenated and processed to get $r_{x_i}$ and $e_{x_i}$.} \label{fig:temb} \end{subfigure} \caption[]{Embedder network} \label{fig:embedder} \end{figure} The generator starts from the target landmark and generates a new image $\hat{x}_t = G(L(x_t), e_x)$. The landmark image is provided through the input layer while the combined spatial embedding $e_x$ is used to modulate the activations at several resolutions with SPADE blocks. In order to assess the quality of the generated image we employ two discriminators: identity discriminator and pose discriminator. Identity discriminator $D_I(x_a, x_b)$ follows the multi-scale architecture from pix2pixHD \cite{wang2018pix2pixHD} and is used to estimate identity resemblance. At this stage we only consider characteristic traits and the results are expected to be invariant to pose. Thus, the input consists of two RGB images of the same person in arbitrary positions. Pose discriminator $D_P(x_a, L(x_a))$ has the same architecture as $D_I$ with its own set of parameters. The network receives a frame and the appropriate target landmarks and checks the correspondence. While both discriminators will also assess general realism of a given image, $D_P$ is used specifically to avoid pose mismatch, whereas $D_I$ encourages identity preservation. This disengagement allows us to assign different importance factors to each discriminator while training. Different combinations may give results that correlate better with human visual perception. \subsection{Training} Videos are used as image sequences during training. For each epoch we sample a sequence of $K + 1$ distinct frames for each training video and compute landmark images: $L(x_{i_1}), L(x_{i_2}), ..., L(x_{i_{K+1}})$ using a pretrained face alignment network \cite{bulat2017far}. The embedding tensor $e_x$ is then computed according to (\ref{eq:1}). Using $L(x_t)$ and $e_x$, CainGAN generates the new image $\hat{x}_t$ which is further fed to the identity discriminator $D_I(\hat{x_t}, x_{i_1})$ along with a source frame $x_{i_1}$. The choice of the identity frame index $i_1$ is arbitrary as the generation process is not influenced by the order of input images. $\hat{x}_t$ and $L(x_t)$ are also fed to the pose discriminator $D_P(\hat{x_t}, L(x_t))$. Importance factors $\lambda_I$ and $\lambda_P$ control the weight of each discriminator in the objective function given by the hinge loss \cite{lim2017geometric,miyato2018spectral}: \begin{equation} \begin{aligned} \mathcal{L}_{Adv}(G, E, D) = -\lambda_I \cdot D_I(G(L(x_t), e_x), x_{i_1}) \\ -\lambda_P \cdot D_P(G(L(x_t), e_x), L(x_t)) \end{aligned} \label{eq:2} \end{equation} \begin{equation} \mathcal{L}_{Id}(D_I) = \max(0, 1 - D_I(x_t, x_{i_1})) + \max(0, 1 + D_I(\hat{x}_t, x_{i_1})) \label{eq:3} \end{equation} \begin{equation} \mathcal{L}_{Pose}(D_P) = \max(0, 1 - D_P(x_t, L(x_t)) + \max(0, 1 + D_P(\hat{x}_t, L(x_t)) \label{eq:4} \end{equation} The identity and pose discriminators are updated using $\mathcal{L}_{Id}$ and $\mathcal{L}_{Pose}$, respectively. The weights of the generator and the embedder are updated together using the full objective: \begin{equation} \begin{aligned} \mathcal{L}(G, E, D) = \mathcal{L}_{Adv}(G, E, D) + \lambda_{FM}( \lambda_{I} \cdot \mathcal{L}_{FM}(D_I) + \\ \lambda_{P} \cdot \mathcal{L}_{FM}(D_P)) + \lambda_{VGG} \cdot \mathcal{L}_{VGG} \end{aligned} \label{eq:5} \end{equation} $\lambda_{FM}$ and $\lambda_{VGG}$ represent hyperparameters that control the importance of the loss in the full objective. $\mathcal{L}_{VGG}$ is a perceptual loss that compares features extracted at several layers by a pretrained VGGNet \cite{simonyan2014very} from the original and the generated image. Feature matching loss $\mathcal{L}_{FM}$ is also a perceptual loss, comparing activations in the layers of the discriminator according to \eqref{eq:6}. Importance factors $\lambda_I$ and $\lambda_P$ also affect the weight of feature matching losses. The FM loss is similar to the one used in \cite{wang2018pix2pixHD} as we employ multiscale discriminators: \begin{equation} \mathcal{L}_{FM}(D) = \sum_{i=1}^{S}\sum_{j=1}^{T}\frac{L_1(D_i^{(j)}(x_t, y), D_i^{(j)}(\hat{x}_t, y))}{N_j} \label{eq:6} \end{equation} where $S$ represents the number of scales, $T$ is the number of layers in $D$, $N_j$ is the number of elements in layer $j$ and $L_1$ denotes the standard Manhattan distance. $y$ is either the value of $L(x_t)$ when using the perceptual loss induced by the pose discriminator, or $x_{i_1}$ for the identity discriminator, respectively. To ease the training process we start with a low importance factor for the identity discriminator and linearly increase it to its maximum value over the first 10 epochs. This allows the model to learn the easy task first, generating realistic face images in given pose, after which we gradually impose identity preservation. We alternate between ($G$, $E$) and $D$ updates, with twice more steps for the discriminator and using two time-scale update rule \cite{heusel2017gans} to stabilize training. \subsection{Implementation Details} \label{sec:implementation} The generator resembles an encoder-decoder architecture for image translation. There are 4 downsamplings residual blocks with learned skip connections, 3 same resolution residual blocks and 4 upsampling layers. Instance normalization \cite{ulyanov2016instance} is used after every downsampling and upsampling layer. A SPADE residual block with spectral normalization \cite{miyato2018spectral,zhang2019self} is used after each upsampling. Nearest interpolation is used to bring the spatial embeddings to the appropriate resolution for each SPADE block. The discriminators are based on the architecture proposed by Wang et al. in \cite{wang2018pix2pixHD}, and use 2 scales as the images are relatively small. The embedder consists of 2 downsampling and 4 same resolution residual blocks which are shared while computing $r_{x_i}$ and ${e_{x_i}}$. Two independent same resolution residual blocks are then used to get $r_{x_i}$ and ${e_{x_i}}$. \section{Experiments and Results} \label{sec:experiments} To evaluate our approach, we conduct extensive experiments on the VoxCeleb2 \cite{Chung18b} dataset. To emphasize the ability of our model to learn from less data, we only use a small subset of the actual dataset. Originally, the train set contains almost 6000 different speakers featuring more than a million videos. For our experiments we randomly selected 150 speakers and their corresponding videos (around 30,000), less than 3\% of the grand total. A video dataset was used since it is an accessible way to obtain multiple images with the same identity. Quantitative comparison is performed against two baselines: pix2pixHD \cite{wang2018pix2pixHD} and previously state-of-the-art method for talking head generation \cite{zakharov2019fewshot} denoted FSHM (Few-shot Head Models). We trained the pix2pixHD model from scratch as described in the original paper and official implementation. In order to use the model without fine-tuning, the network input consists of all source frames and their landmarks as well as the target landmark; these are also given to the discriminator. We also implemented a version of FSHM (feed-forward only) in order to assess the results in a limited training data setting. Three different metrics are used to compare the described methods: structural similarity metric (SSIM) between the ground truth and the generated image is used to measure low-level structural similarity, cosine similarity (CSIM) between embedding vectors as computed by a pretrained face recognition network and Fr\'echet Inception Distance (FID) \cite{heusel2017gans} measuring perceptual realism which usually better captures the similarity of real and fake images. We follow the same training setup presented by Zakharov et al. \cite{zakharov2019fewshot}, using 50 video sequences with 32 test frames for each. \setlength{\tabcolsep}{1em} \begin{table}[t] \centering \begin{tabular}{l c c c} Method (K) & SSIM $\uparrow$ & CSIM $\uparrow$ & FID $\downarrow$ \\ \hline pix2pixHD(1) & 0.66 & 0.80 & 72.26 \\ FSHM (1) & 0.64 & 0.72 & 93.17 \\ FSHM-FF-full (1) & 0.61 & N/A & 46.61 \\ FSHM-FT-full (1) & 0.64 & N/A & 48.5 \\ CainGAN (1) & \textbf{0.69} & \textbf{0.85} & \textbf{35} \\ \hline pix2pixHD(8) & 0.66 & 0.81 & 71.89 \\ FSHM (8) & 0.65 & 0.73 & 83.13 \\ FSHM-FF-full (8) & 0.64 & N/A & 42.2 \\ FSHM-FT-full (8) & 0.68 & N/A & 42.2 \\ CainGAN (8) & \textbf{0.77} & \textbf{0.91} & \textbf{24.92} \\ \hline \end{tabular} \caption{K is the number of source frames used for testing. For SSIM and CSIM higher is better, for FID lower is better. CainGAN (8) was stopped after 20 epochs to avoid overfitting, all other models were trained for 30 epochs. The ``full'' suffix refers to the models being trained on the entire dataset. These results are taken from \cite{zakharov2019fewshot}. CSIM is not reported here, as a different face recognition network was used for the original results. } \label{tab:exp} \end{table} \begin{figure}[!t] \centering \advance\leftskip-1.8cm \newlength\wid \setlength{\wid}{6.5em} \addtolength{\tabcolsep}{-5pt} \begin{tabular}{m{3em}m{\wid}m{\wid}m{\wid}m{\wid}m{\wid}} \centering{} & \multicolumn{1}{c}{\textbf{Source}} & \multicolumn{1}{c}{\textbf{pix2pixHD}} & \multicolumn{1}{c}{\textbf{FSHM}} & \multicolumn{1}{c}{\textbf{CainGAN}} & \multicolumn{1}{c}{\textbf{Real Image}} \\ \centering{\textbf{K=1}}& \includegraphics[width=\wid]{Figures/d150/source.png} & \includegraphics[width=\wid]{Figures/d150/p2p-os.png}& \includegraphics[width=\wid]{Figures/d150/fshm1.png}& \includegraphics[width=\wid]{Figures/d150/cain1.png}& \includegraphics[width=\wid]{Figures/d150/gt.png}\\ \centering{\textbf{K=8}}& \includegraphics[width=\wid]{Figures/d150/source.png}& \includegraphics[width=\wid]{Figures/d150/p2p-8shot.png}& \includegraphics[width=\wid]{Figures/d150/fshm8.png}& \includegraphics[width=\wid]{Figures/d150/cain8.png}& \includegraphics[width=\wid]{Figures/d150/gt.png}\\ \centering{\textbf{K=1}}& \includegraphics[width=\wid]{Figures/d39/source.png} & \includegraphics[width=\wid]{Figures/d39/p2p-os.png}& \includegraphics[width=\wid]{Figures/d39/fshm1.png}& \includegraphics[width=\wid]{Figures/d39/cain1.png}& \includegraphics[width=\wid]{Figures/d39/gt.png}\\ \centering{\textbf{K=8}}& \includegraphics[width=\wid]{Figures/d39/source.png}& \includegraphics[width=\wid]{Figures/d39/p2p-8shot.png}& \includegraphics[width=\wid]{Figures/d39/fshm8.png}& \includegraphics[width=\wid]{Figures/d39/cain8.png}& \includegraphics[width=\wid]{Figures/d39/gt.png}\\ \end{tabular}\vspace{-2pt} \caption{Visual assessment on the VoxCeleb2 dataset. First column represents the number of source frames, the next column illustrates one of the $K$ source images and the last column contains the ground truth ($x_t$) images. In between are the generated frames by different methods. The figure is best viewed in color.} \label{fig:qab} \end{figure} The comparison given in Table \ref{tab:exp} shows that CainGAN is able to get better quantitative results using only a fraction of the dataset. Additionally, the method is able to generate realistic images in the desired pose with a good preservation of identity. From qualitative comparison in Figure \ref{fig:qab} we can see that while FSHM can synthesize the face with the right alignment there is a high identity mismatch. Clearly, small amounts of training images severely affect the ability of the FSHM model to generalize to unseen faces. We also obtain the uncanny artifacts present in images generated by pix2pixHD, as reported in \cite{zakharov2019fewshot}. \subsection{Ablation Study} We performed an ablation study to analyze the influence of different components of our method. Quantitative results of the experiments are visible in Table \ref{tab:abl}. The variants are: CainGAN without targeting (CainGAN w/o T) where only the source frame and its landmarks are given to the embedder, CainGAN without discriminator importance weighing (CainGAN w/o I) where $\lambda_D = \lambda_I$ are fixed and CainGAN without responsibility based embedding mixing (CainGAN w/o R) where the weighted version in equation \eqref{eq:1} is replaced by: \begin{equation} e_x = \frac{1}{K}\sum_{i \in \{i_1, \ldots, i_K\}} e_{x_i} \end{equation} This variant is not applicable for $K=1$ as in this case the two expressions yield the same result. \setlength{\tabcolsep}{1em} \begin{table}[!t] \centering \begin{tabular}{l c c c} Method (K) & SSIM $\uparrow$ & CSIM $\uparrow$ & FID $\downarrow$ \\ \hline CainGAN w/o T (1) & \textbf{0.69} & \textbf{0.85} & 36.26 \\ CainGAN w/o I (1) & 0.68 & 0.84 & 46.44 \\ CainGAN (1) & \textbf{0.69} & \textbf{0.85} & \textbf{35} \\ \hline CainGAN w/o T (8) & 0.72 & 0.87 & 38.08 \\ CainGAN w/o I (8) & 0.76 & \textbf{0.91} & 28.72 \\ CainGAN w/o R (8) & 0.75 & 0.90 & 30.05 \\ CainGAN (8) & \textbf{0.77} & \textbf{0.91} & \textbf{24.92} \\ \hline \end{tabular} \caption{Ablation study on selection of VoxCeleb2 dataset. All models were trained for 30 epochs, the best result between epochs 20 and 30 was reported. $K$ is the number of source frames.} \label{tab:abl} \end{table} We can observe that all components are essential to obtain the best results. Using targeted embedder has a greater influence in the $K=8$ setting, which is expected since more images can benefit from early alignment. \section{Conclusions and Future Work} \label{sec:conclusion} We introduced a new method for synthesizing images in novel poses while preserving the identity of a given subject. CainGAN uses spatially adaptive normalization with a proper combining function of spatial feature maps in the embedding space. Experimental results show that CainGAN behaves better on scarce training sets compared to other methods. Furthermore, realistic images can be generated without the need for fine-tuning. The ablation study demonstrates CainGAN's non-redundant structure whereas the difference between scores in the $K=1$ and $K=8$ settings illustrate the ability to capitalize on more source images when available. Further development directions include designing a method to extend the applicability of CainGAN beyond the task of self-reenactment and closing the gap between one-shot and multi-shot results by improving on single source image generation.
{'timestamp': '2020-04-21T02:24:20', 'yymm': '2004', 'arxiv_id': '2004.09169', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09169'}
arxiv
\section{Introduction} \label{sec:intro} Call-based customer services are still prevalent in most online and offline business. In particular, call centers have played a crucial role in most business domains for a few decades and recently extended to contact centers which provide additional functions such as email, VoIP, and text chatting\footnote{\url{https://aircall.io/blog/call-center/contact-center-vs-call-center/}}. However, the increasing costs and the harsh working environments of contact centers have brought the necessity to apply artificial intelligence (AI) to contact center operation~\cite{delgado2020emerging}. AI for contact center (AICC) is an AI agent that communicates with human customers via call, which rapidly increases in B2B markets~\cite{delgado2020emerging}. Since AICC{} is based on a telephone environment, automatic speech recognition (ASR) via call is essential for successful AICC{} operation. ASR has been one of the tasks remarkably improved by deep learning since early years of 2010s~\cite{yao2012adaptation,mohamed2011acoustic}. It is well known that the improvement of ASR results from large-scale speech corpora including Wall Street Journal~\cite{paul1992design}, TIMIT~\cite{garofolo1993timit}, Switchboard~\cite{godfrey1997switchboard}, CallHome~\cite{canavan1997callhome}, and Librispeech~\cite{panayotov2015librispeech} datasets. However, most publicly available call speech corpora are very old-fashioned such as Swichboard, Wall Street Journal, and CallHome because they were released more than 20 years ago. Also, the language of most call corpora is mainly English, and thus call corpora of low resource languages are very scarce. The other issue is is that the utterances of most corpora are based on open domains such as day-life conversation and audiobook contents. Even if small numbers of Korean speech corpora are publicly available such as AIHub~\footnote{\url{http://www.aihub.or.kr/aidata/105}} and Zeroth project\footnote{\url{https://github.com/goodatlas/zeroth}}, they contain general open domain dialog utterances. Therefore, ASR models trained from these speech data generally show poor recognition performance when applied to domain-specific tasks due to the differences in their data distribution and vocabularies. In particular, AICC{} requires an accurate ASR model to ensure the precise intent classification or slot extraction~\cite{chen2019bert} from user natural language utterances \begin{figure*}[!t] \begin{center} \includegraphics[width=0.9\textwidth]{statistics_h_3.png} \end{center} \vspace{-0.5 cm} \caption{Distributions of four attributes on the \textit{raw} set of ClovaCall{} dataset (goal-oriented) with blue bars compared to those of AIHub dataset (open domain) with orange bars. We can find the different patterns between two datasets for all attributes.} \label{fig:graph_stat} \end{figure*} Here we release a new large-scale Korean call speech corpus containing goal-oriented dialog utterances under a restaurant reservation scenario, i.e., ClovaCall{} speech corpus. The proposed ClovaCall{} includes 61,000 pairs of short sentences and their utterances recorded via call by more than 11,000 people. In specific, the number of unique sentences is 8,990, and all of them are natural language questions and answers which frequently appear when making reservations. The utterances that each subject read given sentences aloud are recorded over a phone. Because most sentences are designated for reservation and short with at most 10 seconds, our dataset does not suffer from end point detection and alignment problems, dissimilar to Librispeech which is extracted from audiobooks. ClovaCall{} can be useful for diverse AICC-based reservation services because most words and expressions prevalent in reservations are commonly used regardless of its application domains, including time, people, date, and location. We demonstrate the effectiveness of the proposed ClovaCall{} with extensive experiments. We employ two standard ASR models such as Deep Speech 2 (DS2)~\cite{amodei2016deep} and Listen, Attend and Speech (LAS)~\cite{chan2016listen} under three training schemes including pretraining-finetuning, from-scratch training, and scratch training with data augmentation. Besides, we use two additional datasets for effective verification. One is an in-house Korean call-based goal-oriented dialog speech corpus on questions and answers for daily company life (QA Dataset) for verifying the necessity of task-specific data. The other is a large-scale Korean open domain dialog speech corpus from AIHub, an online Korean data hub site, for pretraining ASR models. Experimental results show the ASR models trained from large-scale open domain data only provide very poor recognition performances. Thus, the task-specific speech datasets are essential for speech recognition of goal-oriented dialogs like AICC. Interestingly, pretraining with open domain data remarkably improves the ASR accuracy compared to scratch training with task-specific data only even though their sampling rates and frequently used words are different from each other. \section{Related Work} \label{sec:rw} Large-scale speech corpora publicly available allows ASR models to be applied to many valuable real-world applications. Early public speech corpora were released in 1990s, including Wall Street Journal~\cite{paul1992design}, TIMIT~\cite{garofolo1993timit}, Switchboard~\cite{godfrey1997switchboard}, and CallHome~\cite{canavan1997callhome}. These datasets are still prevalent as benchmark datasets for evaluating ASR models~\cite{amodei2016deep,saon2017english,ravanelli2018light,baevski2019vq}. More recently, Librispeech~\cite{panayotov2015librispeech} is the most popular benchmark speech corpus on which the latest state-of-the-art ASR models are evaluated~\cite{han2019state,luscher2019rwth,park2019specaugment,baevski2020effectiveness}. Despite their usefulness, existing speech corpora mainly deal with general open domain dialogs. Even if the large-scale corpora are helpful for pretraining ASR models, the models not finetuned with task-specific data are likely to provide poor recognition accuracy when applied to recognize user utterances in goal-oriented scenarios such as call centers and reservations services (See Sec.~\ref{sec:results}). This poor performance results from the distribution difference between open domain and task-specific goal-oriented dialogs. However, compared to open domain dialog speech corpora, goal-oriented speech corpora are rarely released publicly. \section{Clova Call Speech Corpus} \label{sec:datset} \subsection{AI for Contact Center} ClovaCall{} dataset construction is one of main subtasks in our \emph{AI for Contact Center (AICC)} project~\footnote{\textcolor{blue}{\small{\url{https://clova.ai/aicontactcenter}}}}. The goal of AICC{} is to develop an AI agent which can help human contact center employees to communicate with customers via phone. In perspective of technology, the main functionality of AICC{} contains ASR, natural language understanding such as intent classification and slot filling, goal-oriented style dialog management, response generation, and voice synthesis. Here, we focus on its ASR component and construct a large-scale speech corpora concentrating on a restaurant reservation scenario. \subsection{Data Construction from Humans} ClovaCall{} contains 60,746 utterance and short sentence pairs on the restaurant reservation scenario via call. The process of data construction was carried out in the following order: 1) making a sentence pool, 2) call-based recording utterances with the sentences, and 3) refining the recorded speech data. \noindent\emph{\textbf{Sentence pool. }} We utilized Crowdworks\footnote{\url{https://www.crowdworks.kr/}}, a Korean crowd sourcing platform, to make a pool of candidate sentences. First, we defined 10 categories, 86 intents, and 7 multi-turn situations for restaurant call scenarios. 10 categories, which are high-level topics, include \texttt{reservation}, \texttt{delivery}, and 8 FAQ categories like \texttt{working time}, \texttt{menu}, and \texttt{discount}. 86 intents belong to one of 10 categories and contain \texttt{whether the restaurant is opened now}, \texttt{closing time}, \texttt{recommended menu}, etc. We also defined 7 multi-turn situations, which could be appear in a call to restaurants, inclu \texttt{reservation change} and \texttt{delivery call}, etc. The crowd-workers were asked to imagine and generate multiple interrogative or answer sentences for given intents and situations. After quality assurance process was performed by human experts, 8,990 sentences, which are mainly answer sentences, were selected to comprise the candidate pool by eliminating duplicated sentences. \begin{table}[t!] \small\centering \begin{tabular}{l|rrr|r} \hline \hline Values & Words & Chars & Phonemes & Utter. time \\ & & & & + silenence \\ \hline Voc size & 4,704 & 613 & 53 & - \\ \hline Mean & 4.39 & 13.79 & 32.39 & 2.94s \\ & & & & +2.57 \\ \hline Stdev & 1.99 & 5.50 & 12.99 & 1.77s \\ & & & & +0.79 \\ \hline Max / Min & 17 / 1 & 48 / 3 & 116 / 5 & 30s / 0.3s \\ & & & & + 0 / 0.7 \\ \hline\hline \end{tabular} \caption{Statistics of four attributes of ClovaCall-Base{} dataset. silence means including silence regions in utterances} \label{table:data_stats} \vskip -0.25in \end{table} \noindent\emph{\textbf{Call-based recording utterances. }} Utterance recording was performed based on crowd sourcing, operated by ourselves. 10 unique sentences are given to each crowd-worker. The crowd-worker reads each of the sentences aloud once or twice via call to make at most 20 utterances, which were transmitted into our server. From 11,000 people, we gathered more than 120k pairs of short sentences and utterances. Compared to Librispeech, there do not exist end point detection and alignment problems in our data because the utterances are short enough considering call-based reservation scenarios. Besides sentences, each utterance also has its anonymous speaker index as one of the labels. This allows our data to be useful for speaker identification task. \noindent\emph{\textbf{Refining data. }} Data gathered via crowdsourcing are likely to contain many noises, and thus it is essential to refine the gathered data. First, we carried out qualitative evaluation on the gathered data, which was performed by human experts engaged in CrowdWorks so that we could select a total of 82,306 utterance-sentence pairs. This is the \textit{raw} version of ClovaCall-Full{}. Next, we removed the starting or the ending silence regions below a specific energy level in the raw waveform of utterances. We used \texttt{librosa}~\cite{mcfee2015librosa} with 25db as the threshold for silence elimination. The silence-free data is called \textit{clean} version. Finally, we selected top-30 intents with the most utterance-sentence pairs to be a dataset containing 60,746 pairs. We call the dataset ClovaCall-Base{}. We release the \textit{clean} version of ClovaCall-Base{} via \textcolor{blue}{\small{\url{https://github.com/clovaai/ClovaCall}}}. From now, ClovaCall{} denotes to the \textit{clean} version of ClovaCall-Base{} for convenience. \begin{figure}[!t] \begin{center} \includegraphics[width=0.9\columnwidth]{dist_merge.png} \end{center} \vskip -0.25in \caption{Comparison between ClovaCall and AIHub datasets in terms of frequency rank-ratio of each word and character. Left and right graphs are for word and character.} \label{fig:unit_dist} \end{figure} \begin{table}[t!] \small\centering \begin{tabular}{c|r|r|r|r} \hline \hline ClovaCall & Ratio & ~Size~ & ~ No ~ & Rank in AIHub \\ \hline \multirow{4}*{Words} & 0.1 & 381 & 56 & 28,979 \\ & 0.25 & 952 & 230 & 37,664 \\ & 0.5 & 1,904 & 662 & 45,459 \\ & 1.0 & 3,808 & 1,714 & 52,065\\ \hline \multirow{4}*{Chars} & 0.1 & 61 & 0 & 93.7 \\ & 0.25 & 151 & 0 & 162.8 \\ & 0.5 & 302 & 0 & 227.3 \\ & 1.0 & 603 & 3 & 388.3 \\ \hline \hline \end{tabular} \caption{Usage patterns of top frequent words and characters of ClovaCall{} in AIHub dataset. Ratio and size denote the ratio and the number of the top ranked words and characters. No means the number of words and characters not used in AIHub. Rank in AIHub is the average rank in AIHub. The unique word and character sizes are different from Table~\ref{table:data_stats} because we discarded numerical characters. The sizes of unique words and characters of AIHub are 390,599 and 2,268.} \label{table:overlap} \vskip -0.25in \end{table} \subsection{Analysis on ClovaCall Dataset} To show the difference from open domain speech corpus, we compared our dataset with AIHub dataset, the largest Korean open domain dialog corpus. Fig.~\ref{fig:graph_stat} illustrates the frequency histograms of words, characters, phonemes, and utterance length. Overall, most sentences in ClovaCall{} include more than 4 and less than 8 words , and more than 11 and less than 20 characters. Thus, the length of most utterances is more than 4 and less than 10 seconds. These distributions reveal the characteristics of restaurant reservation scenario. Compared to those of AIHub, the frequencies of each attribute are more concentrated on a specific region. We conjecture this pattern results from that most utterances in ClovaCall{} are likely to contain information for reservation while open domain dialog covers much more diverse topics and situations including both very short response utterance such as \textit{``Yes''} and \textit{``Sure''}, and long utterances. Table~\ref{table:data_stats} depicts the number of unique elements, mean, standard deviation, maximum and minimum values for word, character, phoneme, and utterance length. Interestingly, the mean values of utterance length and silence time are very similar, which is caused by call-based recording setup. Fig.~\ref{fig:unit_dist} depicts the difference of frequency ratio of each word and character frequency rank. As shown in Fig.~\ref{fig:unit_dist}, we can find that higher ranked words and characters of ClovaCall{} are used much more frequently than those of AIHub. Table~\ref{table:overlap} shows the differences of usage pattern between ClovaCall and AIHub. In terms of characters, ClovaCall{} shows the similar pattern to AIHub considering the number of not used characters and their average rank in AIHub. However, the word usage of ClovaCall{} is significantly different from AIHub. Frequently used words of ClovaCall{} do not appear in AIHub or are rarely used with very low rank. These difference between two datasets enhances the necessity of goal-oriented dialog corpora. We show the difference causes poor accuracy of ASR models trained from AIHub data on ClovaCall dataset. \section{Speech Recognition Results} \label{sec:asr_result} \subsection{Experimental Setup} \noindent\emph{\textbf{Datasets. }} We use two additional datasets besides ClovaCall{} to effectively verify the efficacy of our dataset. One is our in-house speech corpus on internal questions and answers about company lives collected via phone calls, called QA Call dataset. The other is a large-scale Korean open domain speech dialog corpus from NIA AIHub, an open data hub site of Korea Government. The AIHub speech is used for pretraining the ASR models. Also, we verify the results on ClovaCall-Full{} in addition to ClovaCall{}. While QA Call and ClovaCall are sampled with 8kHz, AiIHub contains the speech voices recorded with 16kHz sampling rate. As shown in Table~\ref{table:data_desc} for experiments, we separate 59,662 and 1,084 sentence-utterance pairs from ClovaCall-Base{} as training and test sets. The training set of ClovaCall-Full{} contains approximately 22,000 more pairs whose intent is excluded from ClovaCall-Base{}. There is neither duplicated speaker nor sentence between two separated sets. For QA Call, we extract the same size of sentence-utterance pairs as ClovaCall{} as the training set. More data were used as test set of QA Call for robust evaluation. For fair comparison, the augmented amount is similar to the pretraining data of AIHub, which is explained in the next section. In addition, the finetuning data size of AIHub is equal to the training data size of two goal-oriented datasets. \begin{table}[t!] \small\centering \begin{tabular}{c|c|r|r} \hline \hline Dataset~~~~&~~~~~Type~~~~~&~~~~Number~~~~&~~~~Hour~~~~ \\ \hline \multirow{4}*{ClovaCall{}}& \underline{Training-Base} & \underline{59,662} & \underline{50}\\ & Training-Full & 81,222 & 67 \\ & Noise Aug & 406,110 & 337 \\ & \underline{Test} & \underline{1,084} & \underline{1} \\ \hline \multirow{3}*{QA Call}& Training & 80,984 & 83 \\ & Noise Aug & 404,920 & 415 \\ & Test & 10,000 & 12.4 \\ \hline \multirow{2}*{AIHub}& Pretraining & 381,603 & 510 \\ & Finetuning & 80,105 & 100 \\ \hline\hline \end{tabular} \caption{Description of three used datasets for experiments. Underlined data were released as ClovaCall{} dataset.} \label{table:data_desc} \vskip -0.25in \end{table} \noindent\emph{\textbf{Training schemes. }} For verifying the effectiveness of ClovaCall{} and the necessity of task-specific speech corpus, we employ three training scenarios: 1) pretraining and finetuing, 2) training from scratch, and 3) training from scratch with data augmentation. AIHub dataset is used for pretraining. Also, almost the same amount of AIHub data to the training portion of ClovaCall{} and QA Call was used for finetuning to investigate whether call-based goal-oriented utterance data are essential or not for task-specific services. We verify the effectiveness of pretraining with open domain speech corpora by comparing the results to those trained from data enhanced by two data augmentation methods such as noise augmentation and specaugment~\cite{park2019specaugment}. We augmented data with noises using our in-house room simulator by adding different types of noise and reverberations~\cite{ko2017study} that we obtained from daily environmental recordings. We did not perform experiments with a language model to enhance the ASR accuracy because we mainly focus on the efficacy our dataset in goal-oriented scenarios. \noindent\emph{\textbf{Data preprocessing. }} First, we upsample the 8Khz waveform datasets to 16Khz so that all datasets have the same frequency resolution. The reason of using upsampling instead of downsampling is that we assume an environment where conventional ASR models for 16KHz sampling rate are used for recognizing call-based speech signals. All models use log-spectrograms as input data, which are calculated with 20ms window size and 10ms stride size using \texttt{librosa}. In addition, all spectrograms were normalized by instance-wise standardazation. \noindent\emph{\textbf{ASR Models. }} We use two standard ASR models such as DS2~\cite{amodei2016deep} and LAS~\cite{chan2016listen} for verifying the effectiveness of our proposed ClovaCall{}. DS2 consists of a CNN and an RNN. In our setting, the CNN module has two 2D-Convolutional layers with 32 channels, which reduce both the frequency and the time resolution of the input spectrogram with stride 4 and 2 for each layer. The RNN module consists of five bidirectional LSTM layers. All these layers have 800 hidden units per direction, in total, 1600 units per layer. Next, one fully connected layer outputs the softmax distribution over characters. Finally, DS2 is trained with CTC loss~\cite{graves2006connectionist}. More details of DS2 are described in \cite{amodei2016deep}. LAS is a sequence-to-sequence model consisting of an encoder, decoder, and attention. The encoder includes a CNN module and an RNN module sequentially. The CNN module is identical to that of DS2. The RNN module of LAS encoder consists of three stacked bidirectional LSTMs with 512 units per direction. The decoder has two unidirectional LSTMs with 512 units and one fully connected layer to predict the character probability distribution. The attention learns the alignment between the encoder outputs and the decoder hidden states. Location-aware attention~\cite{chorowski2015attention} is employed for the attention context of the previous state. All the experiments are performed based on NAVER Smart Machine Learning (NSML) platform~\cite{kim2018nsml,sung2017nsml}. \noindent\emph{\textbf{Metrics. }} We use character error rate (CER) as a metric: \[D = Distance_{LEV}(X,Y),~ CER(\%) = \frac{D}{L} \times 100\] \noindent where $X$, $Y$ are a predicted and a ground truth scripts. The distance $D$ is the Levenshtein distance between $X$, $Y$~\cite{yujian2007normalized} and the length $L$ is a length of ground truth script $Y$. \begin{table}[t!] \small\centering \begin{tabular}{l|rr|rr} \hline \hline \multirow{2}*{Models }&\multicolumn{2}{c|}{DS2~\cite{amodei2016deep}}&\multicolumn{2}{c}{~~~LAS~\cite{chan2016listen}~~~} \\ (Parameters)&\multicolumn{2}{c|}{(56M)}&\multicolumn{2}{c}{(31M)} \\ \hline Data &~~~$QA$~~~ &~~~$CC$~~~&~~~$QA$~~~ &~~~$CC$~~~ \\ \hline \multicolumn{5}{c}{Pretraining and finetuning} \\ \hline $A^{pt} \rightarrow A^{ft}$~~~& 54.6 & 59.5 & 62.3 & 69.2 \\ $A^{pt} \rightarrow QA$~~~& 12.2 & 25.6 & \textbf{10.9} & 26.7 \\ $A^{pt} \rightarrow CC$-Base~~~& 35.9 & 9.54 & 38.7 & 8.0 \\ $A^{pt} \rightarrow CC$-Full~~~& 32.9 & 8.31 & 35.3 & \textbf{7.0} \\ \hline \multicolumn{5}{c}{From-scratch training} \\ \hline $QA$ & 15.2 & 34.7 & 15.3 & 40.0 \\ $CC$-Base & 75.2 & 16.7 & 87.7 & 22.1 \\ $CC$-Full & 62.3 & 11.4 & 76.7 & 15.1 \\ \hline \multicolumn{5}{c}{From-scratch training with data augmentation} \\ \hline $QA$ /w NA & 16.5 & 38.5 & 14.8 & 38.3 \\ $CC$-Full /w NA & 64.4 & 10.7 & 81.4 & 18.9 \\ $QA$ /w SA & 16.5 & 39.7 & 17.1 & 43.5 \\ $CC$-Full /w SA & 63.4 & 10.1 & 88.3 & 31.1 \\ \hline \hline \end{tabular} \caption{CER of each ASR model on two datasets under three training schemes. $A$, $QA$, $CC$ denote AIHub, QA Call, ClovaCall{} datasets, respectively. $pt$ and $ft$ mean the data for pretraining and finetunig. NA and SA are noise augmentation~\cite{ko2017study} and specaugment~\cite{park2019specaugment} on ClovaCall-Full{}. } \label{table:user_study} \vskip -0.25in \end{table} \subsection{Comparison Results on Datasets} \label{sec:results} Our experiments focus on verifying the effectiveness of task-specific speech corpora for a certain AICC{} services. Table~\ref{table:user_study} depicts the results of two popular ASR models under the three training scenarios described in Sec 4.1. In the pretraining and finetuning scheme, despite the largest size of the general domain dataset, AIHub, the performance of ASR models trained from only AIHub is very poor. We conjecture this poor performance results from the differences between open domain and goal-oriented dialog datasets as shown in Fig.~\ref{fig:graph_stat}. On the other hand, when pretrained with AIHub and finetuned with QA Call or ClovaCall{}, both models show remarkable improvement. This supports the necessity of using task-specific data for ASR models in real-world goal-oriented services. In from-scratch training, both DS2 and LAS perform much better in the same domain than the different domain. Because, if a domain shifts, its data distribution and vocabulary also change. Moreover, QA Call provides more stable and better ASR performance than ClovaCall{} as well as in pretraning-finetuning scheme. We conjecture that these results are from larger size of QA Call testset. Also, QA Call contains a little more vocabulary and topics even though both speech corpora belong to goal-oriented dialog category. In data augmentation experiments, no meaningful gain was found. We conjecture that two Call datasets have already been distorted by noises in the recording stage. In particular, the poor result of LAS on ClovaCall{} with SA is likely that too enhanced noise-based regularization harms the model capability of LAS with smaller parameter size, even if overall performance patterns of both models are similar to each other. These results confirm that task-specific speech corpora play a crucial role in improving ASR models for real-world goal-oriented dialog services such as AICC{}. Therefore, we expect that our ClovaCall{} can considerably contribute to call-based reservation services. In addition, we can find that it is required to learn effective representation by pretraining with general-domain data to improve task-specific ASR models as well. \section{Concluding Remarks} We release a large-scale Korean goal-oriented dialog speech corpus, i.e., ClovaCall{}, which is useful for AI for Contact Center (AICC) services. To the best of our knowledge, our dataset is the first Korean goal-oriented dialog speech corpus. Our ClovaCall{} contains 60,746 short sentence and utterance pairs under a restaurant reservation scenario. We verify the effectiveness of ClovaCall{} under three training schemes such as pretraining-finetuning, from-scratch learning, and data augmented from-scratch learning with two additional speech corpora. Experimental results support ClovaCall{} remarkably improves the performance of ASR models, thus being crucial for call-based restaurant reservation services. Furthermore, our ClovaCall{} can contribute to ASR models for diverse call-based reservation services, considering that many reservation services share common expressions such as working time and availability. The contribution of ClovaCall might be considered to be marginal because Korean is not a major language. On the contrary, however, opening low-resource language speech corpora to the public can enhance research diversity. Furthermore, ClovaCall{} is a goal-oriented dialog speech, which is rare in even major languages. Our dataset can contribute to design and construct other goal-oriented speech corpora in various languages. \section{Acknowledgement} The authors thank all members of Clova AI for supporting this work. In particular, we appreciate DUET, AICC{}, and Speech teams including Icksang Han for data preparation and insightful discussion. \bibliographystyle{IEEEtran}
{'timestamp': '2020-05-19T02:17:40', 'yymm': '2004', 'arxiv_id': '2004.09367', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09367'}
arxiv
\section{Introduction} \section{Introduction} \label{sec:intro} Metallic implants are one of the main causes for image quality degradation in medical imaging. In Computed Tomography (CT), the metal's higher attenuation coefficient causes signal corruption, resulting in bright and dark streaks that irradiate from the metal source throughout the reconstructed image. In Magnetic Resonance Imaging (MRI), metal objects induce local magnetic field inhomogeneities that cause intensity and geometrical distortions in the reconstructed image. These susceptibility artefacts typically appear as blackened areas close to the implant, partially shadowing the neighbouring structures. \\ In patients with hip replacement, the size of the metallic prosthesis makes the artefacts even more severe and extended \cite{Gjesteby2016}, hampering the diagnostic interpretation of the images in the most clinically relevant areas, i.e. close to the implant. As a result, the introduction of successful metal artefact reduction (MAR) techniques in hip replacement imaging is of great importance and an active field of research. \\ Numerous approaches have been proposed in the literature for MAR in CT \cite{Gjesteby2016}. Traditional physics-based or iterative reconstruction methods are now being challenged by novel deep neural network approaches, which are data-driven and less dependent on physical model assumptions. However, most methods \cite{Wang2018,Gjesteby2018} are trained in a supervised fashion, relying on either pre- and post-operative paired data (not always available) or simulations (not realistic enough). A solution to the supervised training setting was recently proposed by Liao \textit{et al.}~\cite{Liao2019}. They introduced an unsupervised adversarial training scheme to disentangle the artefact from the anatomy appearance in CT images, showing state-of-the-art performance on both synthetic and real data. In MRI research, efforts have focused mostly on image acquisition improvements: Tailored MR sequences such as MARS \cite{Olsen2000} or SEMAC \cite{Lu2009} have proven effective in reducing the extension of the shadowing, but cannot completely eliminate it, making the clear visualisation of the implant in MRI impossible. \\ In this work we introduce a novel unsupervised deep learning MAR method for \textit{jointly} correcting same-subject CT and MR hip images. Our Multimodal Artefact Disentanglement Network (MADN) extends the approach proposed by Liao \textit{et al.}~\cite{Liao2019} by introducing a similarity loss that induces the network to learn shared information between CT and MRI content. As a result, the CT correction takes advantage of the sharper contrast of MRI throughout the field of view, while the MRI correction is helped by implant localisation information from the CT. As the appearance of the artefact is different in CT and MRI, we believe that making use of their contextual complementary information would help better correct for the artefact in both modalities. We demonstrate the effect of our approach using intensity distribution analysis in the CT and on a segmentation propagation task in MRI, showing how multimodal information improves the correction compared to single-modality approaches. \section{Method} \label{sec:method} \subsection{Artefact Disentanglement Network} \begin{figure*} \begin{center} \includegraphics[height=5cm, width=15.5cm]{ADN_LNCC.png} \caption{Schematic representation of MADN. We used a multichannel ADN architecture~\cite{Liao2019} and introduced a novel similarity loss term to adapt it to the multimodal scenario.} \label{fig:arch} \end{center} \end{figure*} Our work builds upon the Artefact Disentanglement Network (ADN) recently proposed by Liao \textit{et al.}~\cite{Liao2019} to perform unsupervised MAR on CT images. The ADN uses two sets of unpaired images, one including metal artefact corrupted CTs and one with clean non-corrupted images. The key idea is to use encoder-decoder networks coupled with adversarial training to learn a latent representation of the data where the artefact is disentangled from the anatomical content. This separation allows to reconstruct the corrupted images using only the latent content representation, therefore removing the artefact. It also allows to reconstruct the denoised images with the latent artefact representation and thus synthesising corrupted images. \\ Let $\mathcal{I}$ and $\mathcal{I}_a$ be the domains of clean and corrupted images respectively. The network architecture (Fig. \ref{fig:arch}) is composed as follows: Three encoders ($\mathrm{E}_{\mathcal{I}}: \mathcal{I} \rightarrow \mathcal{C}$, $\mathrm{E}_{\mathcal{I}_a}: \mathcal{I}_a \rightarrow \mathcal{C}$, $\mathrm{E}_{a}: \mathcal{I}_a \rightarrow \mathcal{A}$) map the input images to either the content $\mathcal{C}$ or the artefact $\mathcal{A}$ latent spaces; two decoders map the latent space back to the image domain and work as generators ($\mathrm{G}_{\mathcal{I}}: \mathcal{C} \rightarrow \mathcal{I}$, $\mathrm{G}_{\mathcal{I}_a}: \mathcal{C}\times\mathcal{A}\rightarrow \mathcal{I}_a$); finally two discriminators ($\mathrm{D}_{\mathcal{I}}$, $\mathrm{D}_{\mathcal{I}_a}$) define whether an input is real (i.e. coming from the real distribution of $\mathcal{I}$ or $\mathcal{I}_a$ respectively) or fake (i.e. synthetically generated by the decoders $\mathrm{G}_{\mathcal{I}}$ and $\mathrm{G}_{\mathcal{I}_a}$ respectively). We refer the reader to the original manuscript~\cite{Liao2019} for the layer-by-layer outline of the network. \\ Given a corrupted image $x^a \in \mathcal{I}_a$ and a clean image $y \in \mathcal{I}$, we can define their encoding as $c^a = \mathrm{E}_{\mathcal{I}_a}(x^a), a = \mathrm{E}_a(x^a)$ and $c = \mathrm{E}_{\mathcal{I}}(x)$. Indicating by $\hat{}$ the decoded images, from $x^a$ we obtain a reconstructed corrupted image $\hat{x}^a = G_{\mathcal{I}_a}(c^a, a)$ and its corrected version $\hat{x} = G_{\mathcal{I}}(c^a)$. Similarly, $\hat{y}^a = G_{\mathcal{I}_a}(c, a)$ is the synthetically corrupted image from the clean input and $\hat{y} = G_{\mathcal{I}}(c)$ is the reconstructed clean image. To guarantee the expected outputs, the network is trained to minimise the following total loss function: \begin{equation} \mathcal{L}_{tot} = \lambda_{adv}^{\mathcal{I}} \mathcal{L}_{adv}^{\mathcal{I}} + \lambda_{adv}^{\mathcal{I}_a} \mathcal{L}_{adv}^{\mathcal{I}_a} + \lambda_{rec}\mathcal{L}_{rec} + \lambda_{sr}\mathcal{L}_{sr} + \lambda_{art}\mathcal{L}_{art} \end{equation} The first two terms are the traditional adversarial losses that promote a realistic generation of clean and corrupted images from $G_{\mathcal{I}}$ and $G_{\mathcal{I}_a}$: \begin{equation} \begin{split} \mathcal{L}_{adv}^{\mathcal{I}} & = \mathbb{E}_{\mathcal{I}}[\log D_{\mathcal{I}}(y)] + \mathbb{E}_{\mathcal{I}_a}[1 - \log D_{\mathcal{I}}(\hat{x})] \\ \mathcal{L}_{adv}^{\mathcal{I}_a} &= \mathbb{E}_{\mathcal{I}_a}[\log D_{\mathcal{I}_a}(x)] + \mathbb{E}_{\mathcal{I},\mathcal{I}_a}[1 - \log D_{\mathcal{I}_a}(\hat{y}^a)] \end{split} \end{equation} The reconstruction loss guarantees that same-branch encoding-decoding correctly reconstructs the input, thus ensuring the preservation of patient's anatomy: \begin{equation} \mathcal{L}_{rec} = \mathbb{E}_{\mathcal{I},\mathcal{I}_a} [||\hat{x}^a - x^a||_1 + ||\hat{y} - y||_1 ] \end{equation} The self-reduction loss promotes cycle consistency within the cycle ``clean - corrupted - clean": \begin{equation} \mathcal{L}_{sr} = \mathbb{E}_{\mathcal{I},\mathcal{I}_a} [||G_{\mathcal{I}}(E_{\mathcal{I}_a}(\hat{y}^a)) - y ||_1 ] \end{equation} Finally, the artefact consistency loss enforces that the artefact removed through the denoising path is the same added from the artefact-synthesis path, \textit{de facto} training $E_a$ to encode the artefact only: \begin{equation} \mathcal{L}_{art} = \mathbb{E}_{\mathcal{I},\mathcal{I}_a} [||(x^a - \hat{x}) -(\hat{y}^a - y)||_1 ] \end{equation} Each loss term is weighted by the respective hyper-parameter $\lambda$. \subsection{Multimodal Artefact Disentanglement Network} In this work, the ADN is extended to a multimodal case, using two-channel inputs $x^a$ and $y$, with CT image as first channel and respective registered MRI as second channel. The network learns to correct for the artefact on both modalities simultaneously, using multimodal information to encode the anatomical content of the images. To further enforce this sharing of information between the modalities, we introduce the use of a loss term to maximise the similarity of the artefact-corrected images. This is motivated by the idea that two different images of the same object appear less similar if corrupted by noise or artefacts, especially when the artefacts present with different patterns in the two images. Conversely, the two images should look more similar if artefact-free. By maximising the similarity between the output channels, we aim to improve artefact reduction for both modalities: firstly, the high-frequency and full-field-of-view nature of the artefact in the CT could be corrected through comparison with artefact-free MRI regions; secondly, the implant lack of signal in MRI could be compensated by the CT information, and better reconstruction should be achieved. We choose Locally Normalised Cross Correlation (LNCC) as a measure of similarity, as it is suitable for multimodal comparison and it can be efficiently incorporated onto a neural network framework thanks to its convolution formulation~\cite{Cachier2003}. The new similarity loss term is thus defined as: \begin{equation} \mathcal{L}_{sim} = 1 - \mathbb{E}_{\mathcal{I}_a}[|LNCC(\hat{x}_{CT}, \hat{x}_{MRI})|] \end{equation} In addition, we also consider a self-synthesis consistency loss for the cycle ``corrupted - clean - corrupted", that constitutes a full cycle loss together with the self-reduction loss: \begin{equation} \mathcal{L}_{cycle} = \mathcal{L}_{sr} + \mathbb{E}_{\mathcal{I}_a} [||G_{\mathcal{I}_a}(E_{\mathcal{I}}(\hat{x}), a) - x^a ||_1 ] \end{equation} In our experience, this helps obtain sharper output images, especially with small training set size. The final total loss for training the MADN architecture is thus \begin{multline} \mathcal{L}_{tot} = \lambda_{adv}^{\mathcal{I}} \mathcal{L}_{adv}^{\mathcal{I}} + \lambda_{adv}^{\mathcal{I}_a} \mathcal{L}_{adv}^{\mathcal{I}_a} + \lambda_{rec}\mathcal{L}_{rec} + \\ \lambda_{cycle}\mathcal{L}_{cycle} + \lambda_{art}\mathcal{L}_{art} + \lambda_{sim}\mathcal{L}_{sim} \end{multline} \subsection{Experimental Setup} \label{ssec:subhead} Our dataset included 65 3D CT-T1 MARS MRI pairs from subjects with metal hip implants, and 63 CT-T1 MRI clean pairs, with no metal artefacts. Data was collected in clinical setting, with a variety of acquisition protocols, in compliance with the Helsinki Declaration. Each CT-MRI pair has been aligned with non-linear registration using a cubic b-spline free-form deformation algorithm~\cite{Modat2010}. Note that the CT images were initially corrected with the Refined Metal Artefact Reduction (RMAR)~\cite{treece2017} for more accurate transformation estimation. However, the uncorrected images were utilised in all the experiments subsequently described. 11 pairs of corrupted CT-MRI were associated with manual segmentation of four muscles - Gluteus Maximus (GMAX), Gluteus Medius (GMED), Gluteus Minimus (GMIN) and Tensor Fasciae Latae (TFL). These subjects were thus left out from training and used as test set.\\ To quantify the effect of the MAR on CT we computed the standard deviation of the intensities ($\sigma_{CT}$) within the muscle regions. The presence of metal artefact induces noise even further from the implant, causing fluctuations of the intensities from their true value, and therefore higher standard deviation. We performed this analysis before correction (No MAR) and after correction with: (RMAR CT) a conventional MAR algorithm~\cite{treece2017}; (ADN CT) correction using an ADN model trained on CT only; (Multichannel ADN) correction using an ADN two-channel model trained on CT and MRI; (MADN) our proposed correction based on two-channel ADN model with LNCC similarity loss. For the MRI, we performed a segmentation propagation experiment: each test MRI was registered to all others using an intensity-based free-form deformation algorithm~\cite{Modat2010}, their manual segmentation was propagated with the estimated transformation and compared with the manual ground truth using the Dice score. In addition to No MAR, Multichannel ADN and MADN, for this task we also trained an ADN model using MR only (ADN MR). All ADN models were trained on 2D slices with ADAM optimiser and learning rate $=10^{-5}$. The loss weights were set to $\lambda_{adv}^{\mathcal{I}}=\lambda_{adv}^{\mathcal{I}_a} = 1.0 $, $\lambda_{cycle} = \lambda_{rs}=\lambda_{rec} = \lambda_{art} = 20.0$. For the proposed MADN, we set $\lambda_{sim} = 1.0$, and LNCC estimated through a Gaussian kernel with $\sigma=5$. \begin{figure*}[t!] \begin{center} \includegraphics[width=0.87\textwidth,height=4.5cm]{visual_comparison_overlay.pdf} \caption{Visual comparison of MAR methods on CT and MRI. The implant is highlighted in yellow in all the corrected CT images. No overlay is applied to the MRI to better display the effect of the MAR.} \label{fig:qualitative} \end{center} \end{figure*} \section{Results and discussion} \label{sec:conc} Figure \ref{fig:qualitative} presents a visual comparison of all the tested MAR methods. On the CT, our approach is the most effective in reducing the streaks artefacts throughout the full field of view, as the correction is also driven by non-corrupted MRI corresponding areas. This reduction is also demonstrated by the decrease in $\sigma_{CT}$ within the muscular tissue (Fig. \ref{fig:resCT}), on either the implanted and non-implanted hip sides. \begin{figure}[h!] \subfigure[]{\includegraphics[width=8.8cm,height=4.6cm]{ct_std_implant_withsig.png}} \subfigure[]{\includegraphics[width=8.8cm,height=4.6cm]{ct_std_healthy_withsig.png}} \captionsetup{belowskip=-2pt} \caption{Standard deviation of CT intensity values within specific muscles. Cases significantly different from MADN are indicated by * (two-tailed paired t-test with $p<0.05$). (a) Implanted hip side. (b) Non implanted hip side.} \label{fig:resCT} \end{figure}\vfill On the MRI, Fig. \ref{fig:qualitative} shows that training with MR images only (ADN MR) is not sufficient to learn an embedding of the artefact and therefore correct for it. The multichannel ADN and MADN approaches instead identify the corrupted area correctly and attempt to reconstruct the signal in it. However, the shape of the implant or the surrounding tissue is still not fully recovered. The quantitative experiments reported in Table \ref{tab:MR_to_MR_dice} and Fig. \ref{fig:mr_to_mr} show that MADN provides slightly better alignment for GMAX and TFL, but it performs worse on GMIN. It is however worth noticing that the manual segmentations were performed on the non-corrected MRI, where GMIN is the most affected by the artefact. This makes it challenging to determine whether such result is due to less accurate registration or unreliable ground truth. Further analysis is thus needed to better quantify the MAR impact on MRI. \\ Together with the lack of a clear ground truth, a few limitations characterise our study. First, the ADN architecture was not modified, keeping the same amount of parameters for either single- or multi-modality tests and thus not optimising the model capacity to the multimodal task. Moreover, different multimodal similarity measures could be implemented in place of LNCC (e.g. Cross Correlation or Normalised Mutual Information) to test their impact on the reconstruction. Finally, the test set is currently limited in size due to lack of ground truth for quantitative analysis. Hence, the generalisability of the proposed approach is to be more extensively validated. Despite these limitations, the qualitative examples and quantitative results on the CT suggest that the use of the multimodal approach for MAR could be beneficial, as it combines different information to learn a better embedding of the anatomy and of the artefact. Future work will thus address the aforementioned limitations and focus on hyperparameters optimisation in order to improve the correction in MRI. \begin{table}[t!] \begin{minipage}[b]{1.0\linewidth} \centering \resizebox{8.5cm}{!}{ \begin{tabular}{l|c|c|c|c} & GMAX & GMED & GMIN & TFL \\ \hline No MAR & 0.76$\pm$0.15 & \textbf{0.54}$\pm$0.17 & \textbf{0.37}$\pm$0.18 & 0.41$\pm$0.27 \\ ADN MR & 0.76$\pm$0.18 & 0.53$\pm$0.16 & 0.34$\pm$0.19 & 0.44$\pm$0.26 \\ Multich ADN & \textbf{0.77}$\pm$0.17 & 0.53$\pm$0.16 & 0.31$\pm$0.19 & 0.46$\pm$0.27 \\ MADN & \textbf{0.77}$\pm$0.16 & \textbf{0.54}$\pm$0.15 & 0.32$\pm$0.19 & \textbf{0.50}$\pm$0.26 \\ \hline \end{tabular} } \caption{Mean and standard deviation of Dice score for MR-to-MR inter-subject segmentation propagation task.} \label{tab:MR_to_MR_dice} \vspace{0.25cm} \end{minipage} \begin{minipage}[b]{1.0\linewidth} \centering \centerline{\includegraphics[width=8cm, height=4.5cm]{mr_to_mr_reg_withsig.png}} \captionsetup{belowskip=0pt} \captionof{figure}{Dice score obtained from MR-to-MR inter-subject registration and segmentation propagation. Cases significantly different from MADN are indicated by * (two-tailed paired t-test with $p<0.05$)} \label{fig:mr_to_mr} \end{minipage} \end{table}\vfill \paragraph*{Acknowledgements} This work is supported by the EPSRC-funded UCL CDT in Medical Imaging [EP/L016 478/1], the RNOH NHS Trust, the Wellcome/EPSRC Centre for Medical Engineering [WT 203148/Z/16/Z, NS/A000049/1] and the NIHR Biomedical Research Centre based at GSTT NHS Trust and KCL. \bibliographystyle{IEEEbib} \balance
{'timestamp': '2020-04-21T02:27:58', 'yymm': '2004', 'arxiv_id': '2004.09321', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09321'}
arxiv
\section{Introduction} 3D object detection and tracking play a significant role for autonomous driving vehicles where the time-independent detection undertakes the fundamental perception, and continuous object tracking further enables temporal motion prediction and planning. With the rapid evolution of 3D deep learning and feature representation, the detection part has been made great progress in terms of 3D localization ability by many efforts \cite{cvpr18xu, ku2019monocular, ma2019accurate, li2019stereo, wang2019pseudo, chen2017multi,qi2017frustum,zhou2017voxelnet,liang2018deep,liang2019multi, lang2019pointpillars, shi2019pointrcnn}. However, as an equally essential task, the 3D object tracking has rarely been explored. Only a few recent works \cite{li2018stereo, luo2018fast, hu2018joint} demonstrate 3D object tracking ability in the context of self-driving scenarios. To bridge this gap and take advantage of sequential visual cues, we aim at a complete 3D object tracking system that joint exploits spatial-temporal information and estimates accurate 3D object trajectories with motion consistency. We focus on the use of stereo cameras as it shows a promising balance between the cost and 3D sensing ability comparing with the expensive LiDAR sensor and the inadequate single camera. \begin{figure} \setlength{\belowcaptionskip}{-0.8cm} \begin{center} \includegraphics[width=1.0\columnwidth]{cover_small} \end{center} \vspace{-0.5em} \caption{\textbf{An example of our 3D tracking system.} From top to bottom: The sampled object local depth which is color mapped by local coordinates; 3D tracking result on sequential images; 3D tracking result on the bird's eye view. Here the trajectory is transformed to global coordinates for visualization using the off-shelf ego-camera pose.} \vspace{-0.5em} \label{fig:cover} \end{figure} \begin{figure*} \begin{center} \includegraphics[width=1.91\columnwidth]{system} \end{center} \caption{Architecture of the proposed Stereo 3D object tracking system, which generates paired 2D boxes for data association (Sect.~\ref{sec:det}), initial 3D box estimation (Sect.~\ref{sec:box}) and dense local predictions (Sect.~\ref{sec:dense}) for the following spatial-temporal optimization (Sect.~\ref{sec:opti}).} \label{fig:system} \end{figure*} In this paper, we consider the 3D object tracking as not only a \textit{data association} problem but also a \textit{continuous state estimation} problem, where the estimation result should satisfy both instant spatial constraints and the accumulated history evidence. To this end, we propose our joint spatial-temporal optimization-based 3D object tracking system. As illustrated in Fig.~\ref{fig:system}, our system firstly generates paired region proposals on the concatenated current and previous feature maps. After \textit{RoIAlign} \cite{he2017mask}, we employ three parallel branches on the concatenated RoI (region of interest) feature to refine the proposal and generate object-level and pixel-level information. As Fig.~\ref{fig:system} shows, the paired regression branch refines the paired proposals to accurate 2D bounding box pairs. Benefit from the paired detection, the sequential objects can be naturally associated without additional similarity computation (Sect.~\ref{sec:det}). The 3D estimation branch predicts object-level information, e.g., centroid projection, observation angle to form an initial 3D box (Sect.~\ref{sec:box}). The dense prediction branch outputs pixel-level segmentation and local geometry cues such as local depth and local coordinates (Sect.~\ref{sec:dense}) that are aggregated later to formulate our spatial-temporal optimization. To estimate a consistent and accurate 3D trajectory, we enforce precise geometry modeling by jointly considering the dense spatial and historic cues. From the spatial view, an optimal object depth should yield minimal stereo photometric error given the local depth relations between foreground pixels and object centroid. From the temporal view, the consistent object motion will yield minimal reprojection error after warping foreground pixels to the adjacent frame. Based on this, we propose a joint spatial-temporal optimization which models all these dense constraints in a tightly-coupled manner (Sect.~\ref{sec:opti}). To trade off the large amount information introduced by dense cues from multiple frames, we further introduce a per-frame marginalization strategy where the previous observations will be iteratively marginalized as a linear prior, s.t., all historical evidence will naturally contribute to the current object estimation without the need of information reuse. Overall, our main contributions can be summarized as: \begin{itemize} \item A complete 3D object tracking framework that handles simultaneous detection \& association via learned correspondences, and solves continuous estimation by fully exploiting dense spatial-temporal constraints. \item Significantly outperform state-of-the-art image-based 3D tracking methods on the KITTI tracking dataset. \item Report extensive evaluation on more categories and larger-scale datasets (KITTI Raw and Argoverse Tracking) to benefit future benchmarking. \end{itemize} \section{Related Work} {\setlength{\parindent}{0cm} \subparagraph*{3D Object Detection.} There are plenty of research efforts focus on the detecting 3D object using instant sensor data in autonomous driving scenarios. From the modality of input data, we can roughly outline them into three categories: monocular image-based methods, stereo imagery-based, and LiDAR-based methods. Given a \textbf{monocular image}, some earlier works \cite{chen2016monocular, zeeshan2014cars, chabot2017deep, kundu20183d} exploit multiple levels of information such as segmentation, shape prior, keypoint, and instance model to help the 3D object understanding, while recent state-of-the-art works \cite{cvpr18xu, qin2019monogrnet, ku2019monocular, ma2019accurate, brazil2019m3d} pay more attention to the depth information encoding from different aspects to detect and localize the 3D object. Adding additional images with known extrinsic configuration, \textbf{stereo based methods} \cite{3dopJournal, li2019stereo, wang2019pseudo, pon2019object} demonstrate much better 3D object localization accuracy, where \cite{li2019stereo} utilizes object-level prior and geometric constraints to solves the object pose using raw stereo image alignment. \cite{wang2019pseudo} converts the stereo-generate depth to a pseudo point cloud representation and directly detect object in 3D space. While \cite{pon2019object} takes advantages of both and predict object-level point cloud then regress the 3D bounding box based on the object point cloud. Besides the image-based approaches, rich works \cite{li2016vehicle, engelcke2017vote3deep, zhou2017voxelnet, lang2019pointpillars, yang2018pixor, qi2017frustum, shi2019pointrcnn} utilize the direct 3D information from the \textbf{LiDAR point cloud} to detect 3D objects, where \cite{engelcke2017vote3deep, zhou2017voxelnet, lang2019pointpillars} samples the unstructured point cloud into structured voxel representation and use 2D or 3D convolution to encode features. \cite{li2016vehicle, yang2018pixor} project the point cloud to the front or bird's eye views such that the 3D object detection can be achieved by regular 2D convolutional networks. From another aspect, \cite{qi2017frustum, shi2019pointrcnn} directly localize 3D objects in unstructured point cloud with the aid of PointNet \cite{qi2017pointnet} encoder. Furthermore, \cite{chen2017multi, ku2017joint, liang2018deep, liang2019multi} exploit fuse the image and point cloud in feature level to enable multi-modality detection and scene understanding. } \vspace{-0.2cm} {\setlength{\parindent}{0cm} \subparagraph*{3D Object Tracking.} Although extensive object tracking approaches have been studied in recent decades, in this paper, we mainly discuss the most relevant literature: the 3D object tracking. Based on the 3D detection results, \cite{osep2017combined, scheidegger2018mono, simon2019complexer} employ a filter based modeling (multi-Bernoulli, Kalman filter) to track the 3D object continuously. Alternatively, \cite{hu2018joint} directly learns the object motion using an LSTM model by taking advantage of data-driving approaches. However, decoupling the detection and tracking might cause a sub-optimal solution due to the information loss. Benefit from the stereo vision, \cite{engelmann2017samp} focuses on the object reconstruction with continuous tracked visual cues, and \cite{li2018stereo} employ an object bundle adjustment approach to solve consistent object motion in a sliding window, while relying on the sparse feature matching and loosely coupling the stereo reconstruction with temporal motion limits its performance on 3D localization for occluded and faraway objects. In another way, \cite{luo2018fast} encodes sequential 3D point cloud into a concatenated voxel representation, and directly produces associated multi-frame 3D object detections as tracked trajectory together with motion forecasting. } \section{Sequential 3D Tracking Network} In this section, we describe our sequential 3D object tracking network, which simultaneously detects and associates objects in consecutive monocular images, and introduce our network predictions to enable the initial 3D box estimation and the subsequent joint optimization (Sect.~\ref{sec:opti}). \subsection{Simultaneous Detection \& Association} \label{sec:det} To avoid additional pair-wise similarity computation for object association, we leverage the network directly detect the corresponding objects in adjacent frames. Before object-wise estimation, we use the region proposal network (RPN) \cite{ren2015faster} to densely classify the foreground object and predict coarse object region on the feature map. Inspired from \cite{li2019stereo} for stereo detection, we extend the RPN to recognize the union area of where the object appearing in two sequential images. Specifically, After feature extraction, the feature maps of current image and the previous image are concatenated to involve temporal information (see Fig.~\ref{fig:system}). We pre-calculate the union of corresponding object boxes in the current and previous images. On the concatenated feature map with per-location defined anchors, an anchor will be classified as the foreground only if its IoU (intersection-over-union) with one of the union box is larger than 0.7. On this definition, the positive anchor will cover the object area on both images, thereby it can be regressed to paired RoIs proposals on the current and previous image respectively. Note that this paired RPN does not beyond the network capability since it can be thought as a special classification task where only a repeated and motion-reasonable pattern with same instances can be recognized as a positive sample. \begin{figure} \begin{center} \includegraphics[width=1.0\columnwidth]{ass} \end{center} \caption{\textbf{Association illustration}. At t0 timestamp, the network predicts paired 2D box (b0, b1) for image I0 and I1 respectively. Then at time T1, the green car can be associated by comparing 2D IoU of b1 and b2. The \textit{Birth} and \textit{Death} represent the newborn trackers and died trackers respectively.} \label{fig:ass} \end{figure} The coarse proposal pairs are further refined in the paired regression. As Fig.~\ref{fig:system} shows, we use the RoI pairs to perform \textit{RoIAlign} \cite{he2017mask} on the current and previous feature maps respectively. The cropped current and previous RoI features are then concatenated again to enable the R-CNN based 2D box refinement. By predicting two sets of box offset $[\Delta x, \Delta y, \Delta w, \Delta h]$ which denote offsets in $x, y$ direction, width and height, we obtain paired 2D boxes for current and previous images at each timestamp. During inference, we associate sequential trackers by comparing the 2D IoU between the previous box and current's previous box. An example is visualized in Fig.~\ref{fig:ass} for better illustration. Benefited from this simple design, we achieve simultaneous object detection and association with almost no additional computation, and avoid being affected by large motion as the neural network can find the correspondences around large receptive field. \subsection{3D Object Estimation} \label{sec:box} A complete 3D bounding box is parameterized by $[x,y,z,w,h,l,\theta]$, where $x,y,z$ are the 3D centroid position respecting to the camera frame, $w,h,l$ the 3D dimension, and $\theta$ the horizontal orientation. Since the global location information is lost after crop and resize operation in \textit{RoIAlign} \cite{he2017mask}, we predict several local geometric properties (centroid projection, depth, observation angle $\alpha$) to form a initial 3D bounding box. The centroid projection is defined as the projection coordinates of the 3D object centroid on the image, which can be learnt from the offset between the projection center and the RoI center. For dimension and depth, we predict a residual term based on a dimension prior and an inferred coarse depth $f\frac{h_{3d}}{h_{2d}}$, given by the focal length $f$, 3D object height $h_{3d}$, and 2D RoI height $h_{2d}$. The observation angle represents the object local viewpoint, which can be learnt from the deformed RoI pattern. Note that the observation angle $\alpha$ is not equivalent to the object orientation $\theta$, instead holds the relation: $\alpha = \theta + \arctan\frac{x}{z}$, as proved in \cite{mousavian20173d, li2019stereo}. \subsection{Dense Prediction} \label{sec:dense} However, the predicted 3D box is far from enough for a consistent and accurate 3D tracker as it does not explicitly utilize spatial nor temporal information, we thus define essential dense representations to enable our following joint spatial-temporal optimization. {\setlength{\parindent}{0cm} \textbf{Mask:} We use a stacked region-based FCN layers \cite{he2017mask} to predict dense object mask on the RoI feature maps, which is used for our foreground pixel selection. } {\setlength{\parindent}{0cm} \textbf{Local Depth:} For the foreground pixel, we define the local depth $\delta$, given by the depth difference between the pixels and the object centroid, which are integrated later for constraining the object centroid depth using stereo alignment. } {\setlength{\parindent}{0cm} \textbf{Local Coordinates:} We predict each pixel's 3D local coordinates respecting to the object frame as also used in \cite{wang2019normalized, li2019multisensor}. On this representation, the same part of the object holds a unique coordinate which is invariant with object translation and rotation across time, therefore it can be used as the geometric descriptor to obtain dense pixel correspondences between sequential object patches. Comparing to traditional descriptor such as ORB \cite{rublee2011orb}, our learned local coordinate is a unique representation in object domain and robust to perspective-changing, textureless, and illumination variance, thereby give us robust and dense pixel correspondences even for high occluded and faraway objects. } \section{Joint Spatial-Temporal Optimization} \label{sec:opti} Based on these network predictions, we introduce our joint spatial-temporal optimization model. For simplicity, we consider a single object in the following formulation since we solve all objects analogously in a parallel way. Let $I^l_i, I^r_i$ be the sequential stereo image where $i$ denote the frame index, $\mathbf{c}_i$, $\alpha_i$ be the predicted object centroid projection and observation angle respectively. Let $\mathbf{u}_i$ be the observed foreground pixels given by the object mask. For each observed pixel, we have the local depth $\delta_i$ which serves as spatial cues for stereo alignment, local coordinates $C_i$ that serve our temporal cues for pixel association. For each object, we aim to estimate an accurate object position $\mathbf{p}_i=\{x,y,z\}$ and rotation $\mathbf{R}_i(\theta)$ respecting to the instant camera frame, s.t., we have overall minimum spatial alignment errors and meanwhile are best fitted with the previous pixel observation across multiple frames. \vspace{-0.2cm} {\setlength{\parindent}{0cm} \subparagraph*{Spatial Alignment.}The spatial alignment cost is defined as the photometric error between left-right images: \begin{equation} \label{eq:error1} \begin{array}{lr} \mathbf{E}_{si} := \displaystyle\sum_{\mathbf{u}_i\in\mathcal{N}_s}{w_I} \Big\| I^l_i(\mathbf{u}_i)- I^r_i({\mathbf{u}^r_i}) \Big\|_h, \end{array} \end{equation} where $\mathcal{N}_s$ is the set of sampled foreground pixels according to the image gradient, $w_I$ the weight of the photometric error, $\|\cdot\|_h$ the Huber norm. $\mathbf{u}^i_r$ represents the warped pixel location on the right image $I^r_i$, given by \begin{equation} \label{eq:error11} \begin{array}{lr} \mathbf{u}^r_i = \pi \big(\pi^{-1}(\mathbf{u}_i, \delta_i + \mathbf{p}^z_i) + \mathbf{p}_s\big) \end{array} \end{equation} where we use $\pi(\mathbf{p})$ $:$ $\mathbb{R}^3$ $\rightarrow$ $\mathbb{R}^2$ to denote projecting a 3D point $\mathbf{p}$ on the image and $\pi^{-1}(\mathbf{u}, d)$ $:$ $\mathbb{R}^2 \times \mathbb{R}$ $\rightarrow$ $\mathbb{R}^2$ its back-projection according to the pixel localtion $\mathbf{u}$ and depth $d$. The per-pixel depth is given by the predicted $\delta_i$ and the object centroid depth $\mathbf{p}^z_i$, i.e., all pixels are associated with the object centroid. $\mathbf{p}_s$ stands for the extrinsic translation between stereo cameras. Note that we formulate a more accurate stereo alignment model using our predicted local depth (see Fig.~\ref{fig:cover}) instead of the na\"{\i}ve box-shape in \cite{li2019stereo}. } \vspace{-0.2cm} {\setlength{\parindent}{0cm} \subparagraph*{Temporal Constraints.} Benefit from the geometric and unique property of the local coordinates representation, we can easily obtain temporal pixel correspondences by calculating the pairwise Euclidean distance between the local coordinates in associated object patches. An example of pixel correspondences can be found in the left column of Fig.~\ref{fig:error}. Let $\mathbf{u}_{i-1}$ be the dense correspondences for $\mathbf{u}_{i}$ in the previous frame, given by selecting the closest local coordinates. The temporal constraints encourage all $\mathbf{u}_{i}$ should also be projected to $\mathbf{u}_{i-1}$ (minimal reprojection error) after rigid-body transformation. Let \begin{equation} \label{eq:error2} \begin{array}{lr} \mathbf{E}_{ti} := \displaystyle\sum_{\mathbf{u}_i\in\mathcal{N}_t}w_{\mathbf{p}} \Big\| \mathbf{u}^p_{i} - \mathbf{u}_{i-1} \Big\|_h, \end{array} \end{equation} where $\mathcal{N}_t$ is the set of pixels which found correspondence in the previous frame. $\mathbf{u}^p_{i}$ stands for the projected position of $\mathbf{u}_i$ in the previous frame, given by \begin{align*} \label{eq:error21} \begin{array}{lr} \mathbf{u}^p_i = \pi \Big(\mathbf{R}_{i-1}\mathbf{R}^{-1}_i\big(\pi^{-1}(\mathbf{u}_i, \delta_i + \mathbf{p}^z_i) - \mathbf{p}_i\big) + \mathbf{p}_{i-1}\Big). \end{array} \end{align*} } \vspace{-0.6cm} {\setlength{\parindent}{0cm} \subparagraph*{Pose Error.} In above equations, the object pose in consecutive frames are coupled together, i.e., only relative motion is constrained. Although the object depth $\mathbf{p}^z_i$ is fully observable from Eq. \ref{eq:error11}, we still need object-level observation angle $\alpha_i$ and centroid projection $\mathbf{c}_i$ to constrain the object orientation and position in $x, y$ direction for each frame separately, which can be simply given by a linear error \begin{equation} \label{eq:error_pose} \begin{array}{lr} \mathbf{E}_{pi} := \| \pi(\mathbf{p}_i) - \mathbf{c}_i\| + \| \theta_i - \alpha_i - \arctan(\frac{\mathbf{p}^x_i}{\mathbf{p}^z_i})\| \end{array} \end{equation} } \iffalse \begin{figure} \begin{center} \includegraphics[width=1.0\columnwidth]{error_curve} \end{center} \caption{\textbf{Stereo photometric error vs. object depth}. where we collected error statistics for multiple instances (one color per instance) at different time, enlarged view in the right. The solved depths and the corresponding errors in the final iteration are subtracted respectively for better visualization, i.e., (0, 0) denotes the terminated point of the Gauss-Newton optimization and color dots for the initial iteration points. This figure indicates that our aggregated photometric error has a large converge range around the initial depth value, and the solved depth can reach the global optimal easily.} \label{fig:error_curve} \end{figure} \vspace{-0.6cm} \fi \begin{figure} \begin{center} \includegraphics[width=1.0\columnwidth]{error} \end{center} \caption{\textbf{Left}: Pixel correspondences, where we overlay the color mapped local coordinates on adjacent images. Green lines show sampled pixel matches using pair-wise coordinates distance. \textbf{Right}: {Reprojection error vs. Coordinates error}. The top and bottom show the error pattern for reprojection and coordinates aligning respectively.} \label{fig:error} \end{figure} {\setlength{\parindent}{0cm} \subparagraph*{Per-Frame Marginalization.} To utilize the history information, a straight forward solution would be minimizing all above error terms over multiple frames in a sliding window, \begin{equation} \label{eq:error_s} \begin{array}{lr} \mathbf{E}_n = \displaystyle\sum_{i = 0}^n \mathbf{E}_{si} + \mathbf{E}_{ti} + \mathbf{E}_{pi}. \end{array} \end{equation} However, re-evaluating the spatial alignment cost for all history frames at each timestamp is unnecessary as we already reach the minimum photometric error for historic frames. To fully exploit history information while avoiding the repeated computation, we use a per-frame marginalization strategy to convert the information from the previous optimization to a prior knowledge for the current frame, which is a common technique in SLAM approaches \cite{engel2017direct, qin2018vins}.} For each new object, we joint solve the first two frames by minimizing $\mathbf{E}_2$ of Eq.~\ref{eq:error_s} using Gauss-Newton optimization. We use a stacked 8 dimension vector ${\mathbf{x} = [\mathbf{x}_1, \mathbf{x}_2]}$ to denote the object states at $1^{th}, 2^{th}$ frames, where $\mathbf{x}_i = [\mathbf{p}_i, \theta_i] \in \mathbb{R}^4$ (transpose is omitted for simplicity). During each iteration, we update the object states by \begin{equation} \label{eq:gn} \begin{array}{lr} \mathbf{x} \leftarrow \mathbf{x} + \Delta\mathbf{x}, \,\,\, \rm with \,\,\,\Delta \mathbf{x} = - \mathbf{H}^{-1}\mathbf{b} \end{array} \end{equation} where $\mathbf{H} \in \mathbb{R}^{8\times8}, \mathbf{b}\in \mathbb{R}^{8}$ are calculated by summarizing all costs and jacobians in Eq.~\ref{eq:error_s} respecting to the target states via standard Guass-Newton process. $\Delta\mathbf{x} \in \mathbb{R}^{8}$ is the state increment respecting to the current linearization point. After several iterations, we achieve an optimal estimation $\mathbf{x}$ obtained from a linear system: \begin{equation} \label{eq:gn2} \begin{array}{lr} \mathbf{x} = \widetilde{\mathbf{x}} + \Delta\mathbf{x}, \,\,\, \Leftrightarrow \,\,\,\mathbf{H}\mathbf{x} = \mathbf{H}\widetilde{\mathbf{x}} -\mathbf{b}, \end{array} \end{equation} given by the last linearization point $\widetilde{\mathbf{x}}$ and the corresponding $\mathbf{H}, \mathbf{b}$. Eq.~\ref{eq:gn2} can be thought as a linear constraint for $\mathbf{x}$ that jointly considers two frames' stereo alignment, dense temporal correspondences, and individual pose constraints. Writing the linear constraints separately for two frames, we have \begin{equation} \label{eq:schur} \begin{array}{lr} \left[ {\begin{array}{cc} \mathbf{H}_{11} &\mathbf{H}_{12}\\ \mathbf{H}_{21} &\mathbf{H}_{22}\\ \end{array} } \right] \left[ {\begin{array}{c} \mathbf{x}_1\\ \mathbf{x}_2\\ \end{array} } \right] = \left[{\begin{array}{c} \mathbf{b}^\prime_{1} \\ \mathbf{b}^\prime_{2} \\ \end{array}}\right] \,\,\, \rm with \,\,\,\mathbf{b}^\prime = \mathbf{H}\widetilde{\mathbf{x}} -\mathbf{b} \end{array} \end{equation} where $\mathbf{H}_{11}, \mathbf{H}_{22}$ contain the individual stereo and pose information for $1^{th}, 2^{th}$ frames, while $\mathbf{H}_{12}, \mathbf{H}_{21}$ symmetricly involve the temporal relations from dense pixel correspondences. Marginalizing the $\mathbf{x}_1$ from Eq.~\ref{eq:schur} using Schur complement will give us $\widetilde{\mathbf{H}} \mathbf{x}_2 = \widetilde{\mathbf{b}}^\prime$, derived by \begin{equation} \label{eq:schur2} \begin{array}{lr} \widetilde{\mathbf{H}} = \mathbf{H}_{22} - \mathbf{H}_{21}\mathbf{H}^{-1}_{11}\mathbf{H}_{12}; \,\,\,\, \widetilde{\mathbf{b}}^\prime = \mathbf{b}^\prime_{2} - \mathbf{H}_{21}\mathbf{H}^{-1}_{11}\mathbf{b}^\prime_{1} \end{array} \end{equation} As a result, we obtain an isolated linear constraint on the pose $\mathbf{x}_2$ of the $2^{th}$ frame while still taking both two frames' information into count. When the object keep tracked in the $3^{th}$ frame, we can directly borrow the marginalized information as a prior to constrain the $2^{th}$ pose, meanwhile build the temporal constraints between $2^{th}$ and $3^{th}$ frame. Without loss of generality, for the $i^{th}$ frame we minimize \begin{equation} \label{eq:final} \begin{array}{lr} \mathbf{E}_i = \mathbf{E}_{si} + \mathbf{E}_{ti} + \mathbf{E}_{pi} + \big\| \widetilde{\mathbf{H}} \mathbf{x}_{i-1} - \widetilde{\mathbf{b}}^\prime \big\|. \end{array} \end{equation} After $\mathbf{x}_i$ is solved, we analogously marginalize $\mathbf{x}_{i-1}$ as derivative in Eq.~\ref{eq:schur},\ref{eq:schur2} and extract the linear constraint for $\mathbf{x}_{i}$ that will be used for the next frame. In this way, we only need to evaluate the dense photometric error and temporal reprojection error for the current frame while still incorporate all history information. All previous stereo constraints will eventually contribute to the current estimation through step-by-step temporal relations. Note that our optimization solves a relative trajectory based on pure geometric relations, we thereby do not rely on the given ego-camera pose. Qualitative examples of our \textit{relative} trajectory estimation can be found in Fig.~\ref{fig:quali}. {\setlength{\parindent}{0cm} \subparagraph*{Alternative Way to Model Temporal Relations.} Besides finding dense pixel matching and minimizing the reprojection error in Eq.~\ref{eq:error2}, we also explore an alternative way to model the temporal relations by directly aligning the object local coordinates patch in adjacent frames, given by: \begin{equation} \label{eq:error_direct} \begin{array}{lr} \mathbf{E}_{ti} := \displaystyle\sum_{\mathbf{u}_i\in\mathcal{N}_t}w_{\mathbf{c}} \Big\| C_i(\mathbf{u}^p_{i}) - C_{i-1}(\mathbf{u}_{i-1}) \Big\|_h, \end{array} \end{equation} where the $C_i, C_{i-1}$ are the foreground local coordinates map in the current and previous frames respectively. Benefit from our learned local coordinates representation, we can evaluate a smooth gradient on $C_i, C_{i-1}$ map, and are robust to the exposure imbalance in different frames. We compare and analysis these two ways in the experiment section (Table~\ref{table:3d},~\ref{table:tra} and Fig.~\ref{fig:error}). } \begin{figure*} \begin{center} \includegraphics[width=2\columnwidth]{quali} \end{center} \caption{\textbf{Qualitative results of our 3D object tracking.} We project the estimated 3D bounding box on two sequential images and bird's view map, where different color represents unique tracking id. Note that the color dots represent the \textit{relative} trajectory with respect to the corresponding ego-camera poses at each timestamp respectively.} \label{fig:quali} \end{figure*} \section{Implementation Details} {\setlength{\parindent}{0cm} \subparagraph*{Network Details.} We use ResNet-50 \cite{he2016deep} and FPN \cite{lin2017feature} as our network backbone. Three sets of anchor ratios \{0.5, 1, 2\} with four scales \{4, 8, 16, 32\} are used in the paired RPN stage. For each anchor, we regress 8-d outputs that correspond to the offsets for the box in the current and previous image respectively. For the 2D box regression and 3D box estimation, we fed the concatenated RoI feature maps into two sequential fully-connected layers to produce 1024-d feature vectors. Similarly, we have 8 channels outputs for the paired 2D box regression and 6 channels output for the 3D box centroid and dimension regression. Following \cite{mousavian20173d}, we use two \textit{bin}s for angle classification and residual regression. For the dense prediction, we employ six stacked 256-d FCN (each layer is with 3 $\times$ 3 convolution and ReLU) on the dense RoI feature map, and predict 5-d dense output (1-d mask classification, 1-d local depth and 3-d local coordinates regression). The network inference time is $\sim$80 ms and the joint optimization takes $\sim$130 ms. } {\setlength{\parindent}{0cm} \subparagraph*{Training.} As MOTS \cite{Voigtlaender2019CVPR} provides dense instance segmentation labels for the KITTI tracking \cite{Geiger2012CVPR} sequences, we can directly use it for object mask supervision. The ground-truth for the local depth and local coordinates are calculated from the sparse LiDAR scanning and the labeled 3D bounding box. To leverage the network learn a better 3D object estimation, we firstly pretrain our model on the KITTI object dataset but excluded images appeared in the KITTI tracking sequences ($\sim$ 4000 images are left). Since the KITTI object dataset only provides single image with 3D object label, we apply two random scales with opposite direction (e.g., 0.95, 1.05) on the original image then crop or pad them into the original size, which can be roughly thought as equivalent scales in 3D object position. We thus get simulated adjacent images to initialize our tracking network. After that, we train our network on the tracking dataset to learn more actual association patterns. We expand the training set to 2$\times$ by flipping each image respecting the vertical axis, where the object angle and local coordinates are also mirrored respectively. The total loss is defined as: \begin{equation} \label{eq:loss} \renewcommand*{\arraystretch}{1.5} \begin{array}{lr} {L} = \lambda_1L_{\rm rpn} + \lambda_2L_{\rm box} + \lambda_3L_{3d} + \lambda_4L_{\rm angle} + \lambda_5L_{\rm dense}, \end{array} \end{equation} where $L_{\rm rpn}, L_{\rm box}, L_{\rm angle}, L_{\rm dense}$ contain both classification loss and regression loss, $\lambda_i$ denotes the individual uncertainty to balance the loss according to \cite{kendall2017multi}. For each iteration, we feed one adjacent images pair into the network and sample 512 RoIs in RCNN stage. The network is trained using SGD optimizer with a momentum of 0.9 and a weight decay of 0.0005. We train 10 epochs with 0.001 learning rate followed by 2 epochs with 0.0001 learning rate. } \begin{table*} \begin{center} \renewcommand{\arraystretch}{1.3} \resizebox{0.93\textwidth}{!}{% \begin{tabular}{l|c|ccccccc|ccccccc} \, & \, & \multicolumn{7}{c|}{3D IoU = 0.25} & \multicolumn{7}{c}{{3D IoU = 0.5}} \\ \cline{3-16} Method & Sensor & MOTA $\uparrow$ & MOTP $\uparrow$ & F1 $\uparrow$ & MT $\uparrow$ & ML $\downarrow$ & \# FP $\downarrow$ & \# FN $\downarrow$ & MOTA $\uparrow$ & MOTP $\uparrow$ & F1 $\uparrow$ & MT $\uparrow$ & ML $\downarrow$ & \# FP $\downarrow$ & \# FN $\downarrow$ \\ \Xhline{1pt} Joint-Tracking \cite{hu2018joint} & Mono & -15.55 \footnotemark[1] & 47.91 & 42.14 & 9.33 & 33.33 & 3855 & 4868 & -55.57 & 63.76 & 18.90 & 0.67 & 68.00 & 5378 & 6366 \\ Semantic-Tracking \cite{li2018stereo} & Stereo & 3.31 & 51.72 & 47.32 & 11.33 & 40.67 & 2662 & 4620 & -34.14 & 65.39 & 24.72 & 2.00 & 62.67 & 4070 & 6054 \\ \cline{1-16} Ours (Coord) & Stereo & 56.14 & 62.20 & 77.53 & 42.67 & 14.00 & 820 & 2464 & 28.56 & 69.34 & 61.67 & 22.67 & 24.00 & 1730 & 3651 \\ Ours (Repro) & Stereo & \textbf{56.70} & \textbf{62.33} & \textbf{77.85} & \textbf{44.00} & \textbf{12.00} & \textbf{794} & \textbf{2443} & \textbf{29.39} & \textbf{69.39} & \textbf{62.13} & \textbf{24.00} & \textbf{23.33} & \textbf{1697} & \textbf{3618} \\ \end{tabular} } \end{center} \caption{\textbf{3D bounding box tracking results on the KITTI tracking \textit{val} set}, where 3D box IoU are used for True Positive (TP) assignments.} \label{table:3d} \end{table*} \begin{table*} \begin{center} \renewcommand{\arraystretch}{1.3} \resizebox{0.99\textwidth}{!}{% \begin{tabular}{l|c|ccccc|ccccc|ccccc} \, & \, & \multicolumn{5}{c|}{Distance = 3m} & \multicolumn{5}{c|}{{Distance = 2m}} & \multicolumn{5}{c}{{Distance = 1m}} \\ \cline{3-17} Method & Sensor & MOTA $\uparrow$ & MOTP $\downarrow$ & F1 $\uparrow$ & MT $\uparrow$ & ML $\downarrow$ & MOTA $\uparrow$ & MOTP $\downarrow$ & F1 $\uparrow$ & MT $\uparrow$ & ML $\downarrow$ & MOTA $\uparrow$ & MOTP $\downarrow$ & F1 $\uparrow$ & MT $\uparrow$ & ML $\downarrow$ \\ \Xhline{1pt} 3D-CNN/PMBM \cite{scheidegger2018mono} & Mono & 47.20 & 1.11 m & 73.86 & 48.65 & 11.35 & - & - & - & - & - & - & - & - \, \\ Joint-Tracking \cite{hu2018joint} & Mono & 47.22 & 1.13 m & 75.63 & 40.00 & 7.33 & 27.16 & 0.88 m & 65.20 & 28.00 & 12.67 & -14.58 & 0.53 m & 42.52 & 10.67 & 33.33 \\ Semantic-Tracking \cite{li2018stereo} & Stereo & 51.19 & 1.00 m & 74.82 & 39.33 & 12.00 & 34.84 & 0.76 m & 65.54 & 28.67 & 20.00 & 4.03 & 0.49 m & 47.76 & 14.00 & 38.67 \\ \cline{1-17} Ours (Coord) & Stereo & 74.75 & 0.49 m & 87.66 & 64.67 & 7.33 & 71.12 & 0.44 m & 85.69 & 58.67 & 8.67 & 56.11 & 0.32 m & 77.57 & 43.33 & 13.33 \\ Ours (Repro) & Stereo & \textbf{74.92} & \textbf{0.49 m} & \textbf{87.77} & \textbf{65.33} & \textbf{7.33} & \textbf{71.40} & \textbf{0.44 m} & \textbf{85.85} & \textbf{60.67} & \textbf{8.00} & \textbf{56.74} & \textbf{0.32 m} & \textbf{77.94} & \textbf{47.33} & \textbf{12.00} \\ \end{tabular} } \end{center} \caption{\textbf{3D trajectory tracking results on the the KITTI tracking \textit{val} set.} We assign the True Positive trajectories according to the 3D Euclidean distance between object centroids with different threshholds. Note that the tracking precision (MOTP) is defined based on the distance error, i.e., the lower the better.} \label{table:tra} \vspace{-1mm} \end{table*} \section{Experiments} \label{sec:exp} We evaluate our method on the KITTI tracking dataset \cite{Geiger2012CVPR} using the standard CLEAR \cite{Bernardin2008} metric for multiple objects tracking (MOT) evaluation. As this paper focuses on the 3D object tracking, we define the similarity function between the estimated trackers and ground truth objects in the 3D space. Specifically, we use the overlap between two 3D object cuboids with 0.25 and 0.5 IoU thresholds to evaluate the 3D bounding box tracking performance, and use the Euclidean distance between 3D object centroids to evaluate the 3D trajectory tracking performance (3, 2, 1 meters thresholds are used respectively). The overall tracking performance is evaluated by the MOTA (multiple objects tracking accuracy), MOTP (multiple objects tracking precision), F1 score (calculated from the precision and recall), MT (most tracked percent), ML (most lost percent), and FP (false positives), FN (false negatives), etc. Since the official KITTI tracking server does not support 3D tracking evaluation, we follow \cite{Voigtlaender2019CVPR} to split the whole train data into \textit{training} and \textit{val} set, and conduct extensive comparisons and ablation analysis on the val set for the car category. We also report 3D pedestrian tracking results and extend the evaluation to KITTI raw \cite{Geiger2013IJRR} and Argoverse tracking \cite{chang2019argoverse} dataset. \begin{table} \begin{center} \renewcommand{\arraystretch}{1.4} \resizebox{0.41\textwidth}{!}{% \begin{tabular}{l|ccccc} Method & MOTA $\uparrow$ &MOTP $\uparrow$ & F1 $\uparrow$ & MT $\uparrow$ & ML $\downarrow$ \\ \Xhline{1pt} Stereo R-CNN \cite{li2019stereo} & 23.59 & 69.98 & 56.29 & 18.00 & 28.00 \\ Pseudo-LiDAR \cite{wang2019pseudo} & 25.88 & \textbf{71.10} & 58.14 & 20.00 & 25.33 \\ \cline{1-6} Ours (Coord) & 28.56 & 69.34 & 62.13 & 24.00 & 23.33 \\ Ours (Repro) & \textbf{29.39} & 69.39 & \textbf{62.13} & \textbf{24.00} & \textbf{23.33} \\ \end{tabular} } \end{center} \caption{\textbf{Comparing with 3D detectors + KF tracker \cite{weng2019baseline}}. Note that MOTP \cite{bernardin2008evaluating} is defined on TPs (3D IoU $>$ 0.5) only, which is independent of the overall tracking a consistent trajectory ability. } \label{table:det} \vspace{-2mm} \end{table} \vspace{-4mm} {\setlength{\parindent}{0cm} \subparagraph*{3D Object Tracking Evaluation.} We compare our 3D bounding box and 3D trajectory tracking performance with recent image-based 3D object tracking approaches in Table.\ref{table:3d},~\ref{table:tra} respectively, where 3D-CNN/PMBM \cite{scheidegger2018mono} and Joint-Tracking \cite{hu2018joint} use monocular image for object detection and use PMBM filter or LSTM to generate continuous 3D tracking. Semantic-Tracking \cite{li2018stereo} uses stereo images to achieve a better 3D localization accuracy. As the code for PMBM \cite{scheidegger2018mono} is not available, we directly list the 3D trajectory tracking results in its original paper for reference. We finetune \cite{hu2018joint} on the same tracking split \cite{Voigtlaender2019CVPR} based on its released pre-trained weight on a large scale GTA dataset. For Semantic-Tracking \cite{li2018stereo}, we replace the 2D IoU-based association and the fixed size prior in its original implementation to our learned association and dimension for a fair comparison. As detailed in Table.~\ref{table:3d},~\ref{table:tra}, our method significantly outperforms all image-based 3D object tracking methods for both 3D bounding box and 3D trajectory tracking evaluation. Note that 3D MOTA can be negative\footnotemark[1] as it assigns TPs using 3D IoU or 3D distance, which poses a high strict requirement for image-based approaches. Although \cite{li2018stereo} employs the stereo sensor and considers the motion consistency as well, however, it solves the object relative motion in a sliding window and aligns the object box to the sparse point cloud recovered by the discrete stereo feature matching in separate stages, which is in essence differ from our joint spatial-temporal optimization approach. Both the sparse stereo matching and loosely coupled spatial-temporal information limit its 3D tracking performance. } \footnotetext[1]{$\rm MOTA = (1 - \dfrac{\sum (\rm FN + FP + IDS)}{\sum \rm GT} )\times100$, i.e. $\in (-\infty, 100)$} We also note that modeling temporal relations by local coordinates error in Eq.~\ref{eq:error_direct} (denoted as Coord) slightly underperforms the reprojection error in Eq.~\ref{eq:error2} (denoted as Repro). As minimizing the local coordinates error tries to align the whole object patch, however, the visible areas are not identical even for adjacent frames due to slight viewpoint changing and truncation. An error pattern to reveal the phenomenon can be found in Fig.~\ref{fig:error}, where we can observe a large error in the rear wheel region because the optimizer tries to align the truncated patch to the complete patch in the last frame. Minimizing reprojection error avoids this issue easily by setting a distance threshold for local coordinates matching. If not specified, we report our (repro) results in the following experiments by default. {\setlength{\parindent}{0cm} \subparagraph*{Comparison with 3D Detection Methods.} To further demonstrate our tracking performance, we extend the comparison to state-of-the-art stereo 3D detection methods Stereo RCNN \cite{li2019stereo} and Pseudo LiDAR \cite{wang2019pseudo}. We train these two detectors on our KITTI object split which does not contain images in KITTI tracking sequences, and run the inference on the KITTI tracking $val$ set. We use the recent proposed KF-based tracker \cite{Weng2019_3dmot} to associate the discrete detections and produce sequential 3D object trajectories. As Table.~\ref{table:det} shows, although the detection-based method \cite{wang2019pseudo} shows a good precision (MOTP) for True Positives, a KF tracker cannot guarantee the optimal trajectory from only detection data as most of the original information is lost. We outperform them in the overall tracking performance (MOTA, MT, etc), which evidences again the advantage of our joint spatial-temporal optimization approach. } {\setlength{\parindent}{0cm} \subparagraph*{Benefits of Spatial \& Temporal Information.} This experiment shows how the spatial and temporal information helps our 3D object tracking. As listed in Table.~\ref{tab:aba}, we use the Regress to denote the 3D tracking result using the monocular regressed 3D box only, which shows inadequate 3D tracking performance. While modeling spatial constraints (stereo alignment) significantly improves the 3D localization ability due to introducing accurate depth-sensing ability. Further, adding temporal information by considering geometric relations and motion consistency improves 3D tracking robustness again. The tracking accuracy (MOTA), tracking precision (MOTP) and tracking robustness (MT, ML) are all improved by remarkable margins. } \begin{table} \begin{center} \renewcommand{\arraystretch}{1.4} \resizebox{0.4\textwidth}{!}{% \begin{tabular}{l|ccccc} Method & MOTA $\uparrow$ &MOTP $\uparrow$ & F1 $\uparrow$ & MT $\uparrow$ & ML $\downarrow$ \\ \Xhline{1pt} Mono Regress & -35.26 & 66.96 & 22.28 & 0.00 & 64.00 \\ + Spatial & 26.86 & 69.24 & 60.62 & 18.00 & 24.00 \\ + Temporal & \textbf{29.39} & \textbf{69.39} & \textbf{62.13} & \textbf{24.00} & \textbf{23.33} \\ \end{tabular} } \end{center} \caption{\textbf{Comparing effects of adding different information}.} \label{tab:aba} \vspace{-2mm} \end{table} {\setlength{\parindent}{0cm} \subparagraph*{More Quantitative Experiments.} Since our method predicts object shape and is based on pure geometry, we can seamlessly use it for 3D pedestrian tracking. The quantitative results on the KITTI tracking set and an example can be found in Table.~\ref{tab:ped} and Fig.~\ref{fig:ped} respectively. Besides the evaluation on the KITTI tracking dataset, we also report our 3D tracking results on the KITTI raw sequence \cite{Geiger2013IJRR} and Argoverse Tracking \cite{chang2019argoverse} dataset for future benchmarking. As reported in Table.~\ref{tab:more}, we evaluate on totall 24 KITTI raw sequences that are excluded from the tracking dataset. Note that here we train the network on the whole KITTI tracking dataset without pretraining on the object dataset as the KITTI object images are distributed in most of the raw sequences. The Argoverse dataset provides stereo images with 5 fps and labeled 3D object trackers on 10 fps LiDAR scans. Since the official server only evaluates the 10 fps 3D object tracking on the LiDAR timestamps, we thereby report our results on the 24 stereo validation sequences by assigning the ground truths of the LiDAR frame with the nearest timestamp. As detailed in Table.~\ref{tab:more}, we note that our image-based method works reasonably in short range while unavoidably suffers from performance decent for long-range objects. This is due to a combined reason for low fps stereo images, reciprocal relations between disparity and depth, and non-trivial projection error for extremely faraway objects, etc. } \section{Conclusion} In this paper, we propose a joint spatial-temporal optimization approach for stereo 3D object tracking. Our method models the relations between the invisible object centroid and the local object geometric cues into a joint spatial photometric and temporal reprojection error function. By minimizing the joint error with a per-frame marginalized prior, we estimate an optimal object trajectory that satisfies both the instant stereo constraints and accumulated history evidence. Our approach significantly outperforms previous image-based 3D tracking methods on the KITTI tracking dataset. Extensive experiments on multiple categories and larger datasets (KITTI raw and Argoverse Tracking) are also reported for future benchmarking. \iffalse \begin{table} \begin{center} \renewcommand{\arraystretch}{1.3} \resizebox{0.47\textwidth}{!}{% \begin{tabular}{l|cccccccc} Information &MOTA $\uparrow$ &MOTP $\uparrow$ & F1 $\uparrow$ & MT $\uparrow$ & ML $\downarrow$ & \# FP $\downarrow$ & \# FN $\downarrow$ \\ \Xhline{1pt} \,\,\, Regress & -4.00 & 53.26 & 43.17 & 10.00 & 34.67 & 2883 & 4958\\ + Spatial & 49.98 & 61.01 & 74.06 & 40.00 & 15.33 & 970 & 2783 \\ + Temporal & \textbf{54.38} & \textbf{61.70} & \textbf{76.72} & \textbf{43.33} & \textbf{12.00} & \textbf{897} & \textbf{2516} \end{tabular}} \end{center} \caption{\textbf{Comparing effects of different constraints}, where we use 3D box IoU with 0.25 thresholds.} \label{tab:orien} \end{table} \begin{table} \begin{center} \renewcommand{\arraystretch}{1.3} \resizebox{0.47\textwidth}{!}{% \begin{tabular}{l|cccccccc} Information &MOTA $\uparrow$ &MOTP $\uparrow$ & F1 $\uparrow$ & MT $\uparrow$ & ML $\downarrow$ & \# FP $\downarrow$ & \# FN $\downarrow$ \\ \Xhline{1pt} \,\,\, Regress & 31.37 & 0.79 m & 63.89 & 26.67 & 19.33 & 1690 & 3465\\ + Spatial & 69.07 & 0.50 m & 84.61 & 55.33 & 8.67 & 348 & 1945 \\ + Temporal & \textbf{71.28} & \textbf{0.45 m} & \textbf{85.81} & \textbf{58.00} & \textbf{8.67} & 309 & 1818 \end{tabular}} \end{center} \caption{\textbf{Comparing effects of different constraints}, where we use 3D box IoU with 0.25 thresholds.} \label{tab:orien} \end{table} \fi \begin{figure} \begin{center} \includegraphics[width=1.0\columnwidth]{ped2} \end{center} \caption{\textbf{Qualitative example for 3D pedestrian tracking}.} \label{fig:ped} \end{figure} \begin{table} \begin{center} \renewcommand{\arraystretch}{1.3} \resizebox{0.47\textwidth}{!}{% \begin{tabular}{l|ccccccc} Threshhold & MOTA & MOTP & F1 & MT & ML & \# FP\, & \# FN \,\\ \Xhline{1pt} Distance = 1 m & 33.79 & 0.26 m & 67.78 & 44.12 & 13.24 & 1014 & 1082\\ 3D IoU = 0.25 & 16.73 & 48.02 & 58.60 & 27.94 & 22.06 & 1276 & 1392\\ \end{tabular}} \end{center} \caption{\textbf{3D pedestrian tracking results on KITTI tracking \textit{val} set}. Note that we require the true positive trajectory has $< 1$ m distance error since pedestrians are more crowded than vehicles.} \label{tab:ped} \end{table} \begin{table} \begin{center} \renewcommand{\arraystretch}{1.3} \resizebox{0.46\textwidth}{!}{% \begin{tabular}{l|l|ccccc} Dataset & Threshhold & MOTA & MOTP & F1 & MT & ML \,\\ \Xhline{1pt} \multirow{2}{*}{KITTI Raw} & Distance = 2 m & 63.02 & 0.47 m & 84.81 & 50.32 & 14.95 \\ \, & 3D IoU = 0.25 & 46.29 & 59.88 & 77.07 & 37.89 & 21.05\\ \hline \multirow{3}{*}{\shortstack{Argoverse\\Tracking}} & Range 100 m & 4.10 & 0.93 m & 46.30 & 16.09 & 40.66 \\ \, & Range 50 m & 25.71 & 0.87 m & 63.00 & 30.72 & 21.02 \\ \, & Range 30 m & 43.81 & 0.68 m & 76.24 & 72.92 & 7.22\\ \end{tabular}} \end{center} \caption{\textbf{Evaluation on KITTI raw sequences and Argoverse datasets}, where we seperate the evaluation range and use 2.25 m 3D centroid distance as the threshold for true positive assignment following the Argoverse official setting.} \label{tab:more} \vspace{-2mm} \end{table} {\setlength{\parindent}{0cm} \subparagraph*{Acknowledgment.} This work was supported by the HKUST Postgraduate Studentship and the Hong Kong Research Grants Council Early Career Scheme under project 26201616. } {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2020-04-21T02:27:28', 'yymm': '2004', 'arxiv_id': '2004.09305', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09305'}
arxiv
\section{Introduction} \label{sec:intro} Many European countries impose temporary driving bans for heavy vehicles. Driving may be restricted during the night, on weekends, and on public holidays. Such bans may apply to the whole road network of a country or parts of it. When routing a heavy vehicle from a source to a destination, it is crucial to take these temporary driving bans into account. But it is not only about heavy vehicles. Temporary closures of bridges, tunnels, border crossings, mountain pass roads, or certain inner-city areas as well as closures due to roadworks may affect all road users alike. In case of road space rationing in cities, the driving restriction may depend on the license plate number. To sum up, temporary driving restrictions exist in different forms, and the closing and re-opening times of a road segment must be considered in the route planning. As a consequence of temporary driving restrictions, waiting times may be inevitable and even last for hours. During such waiting hours, the vehicle must be parked properly, and thus a suitable parking area has to be found. The driving time of the detour from and to such a parking area should also be incorporated in the route planning. Unfortunately, the underlying shortest (here: quickest) path problem becomes \textsl{NP}-hard if waiting is only allowed at dedicated locations~\cite{or-tnp-89}. This is because in this case, the so-called \emph{FIFO} (first in, first out) property is not satisfied, that is, the property that a driver cannot arrive earlier by departing later. Thus, our first research question is how we can consider dedicated waiting locations without making the underlying problem \textsl{NP}-hard. It is our aim to obtain a feasible running time even for long-distance routes. In practice, we often find that small parking areas without any facilities like public toilets or restaurants cause the least detour. So an algorithm that looks for the shortest route, that is, a route with the shortest driving time, would select small parking areas in these cases, provided that waiting is necessary. But the longer the waiting time is, the more vital a secure and pleasant place for waiting becomes. So it may be important for the driver that nearby facilities of the parking area and their quality are somehow taken into account as well. How to do this is our second research question. In our setting, a single-criterion objective is not practical. A driver may not always be in favor of the shortest route if that means to spend a very long time waiting and to arrive at the destination considerably later than on the quickest route, that is, a route with the earliest arrival at the destination. Conversely, a driver may not always be interested in a quickest route if that route means to take an unjustified long detour around temporarily closed road segments that could be avoided by waiting in a comfortable place. In other words, an early arrival at the destination (and thus low opportunity costs), little driving time (and thus low fuel costs), and pleasant waiting conditions (and thus high driver satisfaction) are competing criteria. Solutions can differ significantly with regards to these criteria. How to deal with this and find reasonable routes is the third research question. In this paper, we answer these questions as follows: \begin{enumerate} \item We present a model in which waiting is allowed at any vertex and any edge at any time in the road graph but waiting on edges and waiting on those vertices that do not correspond to parking areas is penalized. This is done by assigning a cost to time spent waiting there. Since driving comes at a price, too, we also assign a cost per time unit spent driving. As we will show, we can find a route with least costs in polynomial time if both cost parameters are set to the same value. \item We assume that the nearby facilities of a parking area and their quality can be expressed by some single rating number. To take account of this, we assign a waiting cost to every corresponding vertex as well. This cost is lower than the cost of waiting anywhere else in the road graph, and it is even lower the higher the rating of the parking area is. \item We return routes that are Pareto-optimal with regards to arrival time at the destination on the one hand and total costs on the other. Despite the potentially larger output, our algorithm still runs in polynomial time under the same condition as before. \end{enumerate} As our experiments reveal, many queries within Europe are answered within milliseconds. Except some pathological cases, even more complex queries with four or more Pareto-optimal solutions are solved in less than a second. \subparagraph{Related Work} Many route planning problems are modeled as shortest path problems. To this day, the theoretically fastest known algorithm to find shortest paths on graphs with static non-negative edge weights is the algorithm of Dijkstra~\cite{d-ntpcg-59}. However, for many practical applications, it is not fast enough. One approach to speed up the computation is to reduce the search space of Dijkstra's algorithm by guiding the search towards the destination by means of estimates of the remaining distance to the destination. It is known as the A* algorithm~\cite{hnr-afbhd-68}. Since the advent of routing services, a lot of research has been done on efficient algorithms for routing in road networks. Routing services have to answer many queries on the same network. This can be used to speed up shortest path queries through precomputed auxiliary data. Many approaches exploit certain characteristics of road networks, for example the hierarchical structure (freeways are more important than rural roads). For an extensive overview, we refer to~\cite{bdgmpsww-rptn-16}. One particularly popular speed-up technique are Contraction Hierarchies~\cite{gssv-erlrn-12}. During preprocessing, additional shortcut edges are inserted into the graph, which skip over unimportant vertices. This preprocessing typically takes a few minutes. Then, shortest path queries can be answered in less than a millisecond. A natural approach to handle driving restrictions is to model them as time-dependent travel times~\cite{d-aassp-69}. For the blocked time, the travel time of the edge can be set to infinity. Time-dependent route planning has also received some attention and effective speed-up techniques are known~\cite{bgsv-mtdtt-13,bdpw-dtdrp-16,dn-crdtd-12,d-tdsr-11,ndls-bastd-12}. Variants of our problem have been studied in the literature. In~\cite{desaulniers2000shortest} a related problem is discussed where nodes (not edges) have time windows and waiting is associated with a cost. In~\cite{pugliese2013survey} an overview is given over different exact approaches to solving shortest path problems with resource constraints. Time windows on nodes are a specific kind of constraint in this framework. More specialized models for routing applications have been proposed. The authors of~\cite{twb-rpbtd-18} study the problem of planning a single break, considering driving restrictions and provisions on driver breaks. They aim to find only the route with the earliest arrival. \subparagraph{Contribution} We present a novel model that helps answer our three research questions in the context of temporary driving restrictions and dedicated waiting locations. To the best of our knowledge, this is the first unifying approach that gives answers to all three research questions. Our theoretical analysis reveals that our model can be solved to optimality in polynomial time, given certain restrictions on the parameterization. The experimental evaluation of our implementation demonstrates a practical running time. \subparagraph{Outline} In \cref{sec:problem}, we give a formal definition of the routing problem at hand. In \cref{sec:algorithm}, we present an exact algorithm for this problem. In \cref{sec:analysis}, we analyze the complexity of the problem and show that our algorithm runs in polynomial time if the costs for driving are the same as for waiting anywhere else than at a dedicated waiting location. In \cref{sec:impl}, we describe techniques to speed-up the computation. In \cref{sec:exp}, we present the main results of our experiments. Finally, we conclude in \cref{sec:conclusion}. \section{Problem} \label{sec:problem} A problem instance comprises a \emph{road graph with ban intervals on edges, driving costs and location-dependent waiting costs} (or \emph{road graph with ban intervals and costs} for short) as well as a set of \emph{queries}. The road graph is characterized by the following attributes: \begin{itemize} \item A set $V$ of $n$ vertices and a set $E$ of $m$ directed edges. \item A mapping $\Phi$ that maps each edge $e \in E$ to a sequence of disjoint time intervals, where the edge is considered to be \emph{closed} during each interval. Precisely, for any \emph{ban interval} $[t^{closed},t^{open}) \in \Phi(e)$ of an edge $e$, $t^{open}$ denotes the first point in time after $t^{closed}$ where the edge is open again. Here and in the following, all points in time are integers and the length of an interval is denoted by $|[t^{closed},t^{open})|$ and equals $t^{open} - t^{closed} > 0$. During such a time span, a vehicle on the corresponding road segment must not move. We denote the total number of ban intervals as $b$. \item A mapping $\delta: E \rightarrow \mathbb{N}$ that maps each edge $e:=(u,v)\in E$ to the time $\delta(e)$ that it takes to drive from $u$ to $v$, provided the edge is open. \item A mapping $\rho$ that maps each vertex to a rating in $\{0,1,\ldots,r\}$ with $r \le n$. Rating 0 means \emph{unrated}, that is, it is assumed that it is highly difficult, dangerous, and not allowed to park the vehicle there. In contrast to an unrated location, we call a vertex $v$ with $\rho(v) > 0$ a \emph{parking location}. \item A parameter set of abstract costs, consisting of $d \in \mathbb{Q}_{\ge 0}$, the cost per unit of driving time, and $\cwait[i] \in \mathbb{Q}_{\ge 0}$ for all $i$ from 0 to $r$, the cost per time unit of waiting on a vertex with rating~$i$. Edges are always unrated so waiting there costs $\cwait[0]$ per time unit. W.l.o.g. $\cwait[i] < \cwait[i-1]$ holds for all $i$ between 1 and $r$, that is, we assume that waiting on vertices with a higher rating costs less than waiting on those with a lower rating. \end{itemize} A \emph{$u$-$v$-route} is a triple $(R, A,D)$ of three sequences of the same length $\ell:=|R|=|A|=|D|$. Here, $R$ is the sequence of vertices along the route. It describes a (not necessarily simple) \emph{path} in the graph that starts at $u$ and ends in $v$, that is, $e_i:=(R[i],R[i+1])\in E$ for all $1 \le i< \ell$ and $R[1]=u$ and $R[\ell]=v$. The other two sequences $A$ and $D$ denote the \emph{arrival times} and the \emph{departure times} from the respective vertices, where $A[i] \le D[i]$ for all $1\le i \le \ell$ and $A[{i+1}] - D[i] \ge \delta(e_i)$ for all $1\le i < \ell$ holds. A query comprises a \emph{source} $\ensuremath{s} \in V$ and a \emph{destination} $\ensuremath{z} \in V$ as well as a \emph{planning horizon} $H$. The latter is defined as the time interval between an \emph{earliest departure time} $t^{min}$ from $\ensuremath{s}$ and a \emph{latest arrival time} $t^{max}$ at $\ensuremath{z}$. Waiting costs arise as soon as the planning horizon opens. For a given query, we look for \emph{feasible} $\ensuremath{s}$-$\ensuremath{z}$-routes. A route is feasible with respect to the planning horizon if $A[1]=t^{min}$ and $D[\ell]\le t^{max}$. In addition, ban intervals must be taken account of. Let $T_i:=[D[{i}],A[{i+1}])$ be the time interval in which the edge $e_i:=(R[i],R[{i+1}])$ of the route's path is traversed. A route is feasible with respect to the ban intervals if $\sum_{I \in \Phi(e_i)} | T_i \cap I | \le |T_i| - \delta(e_i)$ for all $1\le i < \ell$. Here, $\sum_{I \in \Phi(e_i)} | T_i \cap I |$ is the time during which the edge between $R[i]$ and $R[{i+1}]$ is closed while the edge is being traversed. Let \emph{travel time} include driving time and waiting time. The \emph{travel time costs} of a route are the sum of the waiting time costs and the driving time costs. So given a route of length $\ell$, the travel time costs are \[\sum_{i=1}^{\ell} \cwait[{\rho(R[i])}] \cdot \left(D[i] - A[i]\right) + \sum_{i=1}^{\ell-1} \cwait \cdot \left(A[{i+1}] - D[i] - \delta(e_i)\right) + d \cdot \delta(e_i), \] where we use $e_i:=(R[i],R[{i+1}])$. We say an $\ensuremath{s}$-$\ensuremath{z}$-route is \emph{Pareto-optimal} (or simply \emph{optimal}) if it is feasible and if its travel time costs are less or its arrival time at $\ensuremath{z}$ is earlier or equality holds in both cases compared to any other feasible $\ensuremath{s}$-$\ensuremath{z}$-route. For a query, the objective is to find a maximal set of (Pareto-)optimal $\ensuremath{s}$-$\ensuremath{z}$-routes such that no two routes in the set have both the same arrival time at~$\ensuremath{z}$ and the same travel time costs. \section{Algorithm} \label{sec:algorithm} The algorithm maintains a priority queue. Each entry of the queue consists of a vertex and a point in time within the planning horizon as key. We say a vertex is \emph{visited} at a certain point in time whenever we remove the top entry from the queue, that is, an entry with the earliest time among the entries in the queue. At every vertex $v \in V$, we store a time-dependent function $\mathcal{C}_v: H \rightarrow \mathbb{Q}_{\ge 0}\cup \{\infty\}$. It maps a point in time $t$ within the planning horizon $H$ to an upper bound on the minimum travel time cost over all $\ensuremath{s}$-$v$-routes that end in $v$ at time $t$. We call this function \emph{cost profile} of $v$ or, more general, \emph{label} of $v$. The algorithm works in a \emph{label correcting} manner in the sense that a vertex may be visited multiple times, albeit at different times within the planning horizon. Before we describe the phases of the algorithm in greater detail, we introduce an auxiliary time-dependent function~$\mathcal{T}_e$ for every edge $e \in E$. It maps a time $t$ at the head $v$ of an edge $e:=(u,v)$ to the \emph{shortest travel time} that it takes to traverse the edge from $u$ to $v$ completely and be at $v$ at time $t$, possibly including waiting time. That is, for a time $t$ at $v$, $\mathcal{T}_e(t)$ is the minimum period~$p$ such that $p - \sum_{I \in \Phi(e)} | [t-p,t) \cap I | \ge \delta(e)$ holds if such a $p$ exists, and $\infty$ otherwise. In other words, $t - \mathcal{T}_e(t)$ is the latest departure time from $u$ in order not to arrive at $v$ later than at time $t$. An example is given in \cref{fig:exampleTravelTimeFunction}. \begin{figure} \begin{subfigure}[b]{0.49\textwidth} \centering \resizebox{\linewidth}{!}{\input{Figures/exampleTravelTimeFunction.tikz} } \caption{Travel time function $\mathcal{T}_e$ of an edge $e$ with ban intervals (grey) and a driving time $\delta(e)$ of 3. The latest departure to be at $v$ at time $t$ is $t-\mathcal{T}_e(t)$.} \label{fig:exampleTravelTimeFunction} \end{subfigure} \hspace{1mm} \begin{subfigure}[b]{0.49\textwidth} \centering \resizebox{\linewidth}{!}{\input{Figures/exampleCostProfileNeighbor.tikz}} \caption{Cost profile of vertex $v$ after linking, that is, after considering travel time (dashed) and waiting time at $v$ (solid).} \label{fig:exampleCostProfileNeighbor} \end{subfigure} \caption{Computing the cost profile of a vertex $v$. Let $v$ be adjacent to the source $\ensuremath{s}$ via an edge $e:=(\ensuremath{s},v)$ with three ban intervals and a driving time $\delta(e)$ of 3. The corresponding travel time function is given in \cref{fig:exampleTravelTimeFunction}. It is infinite between $0=t^{min}$ and $3=\delta(e)$. In \cref{fig:exampleCostProfileNeighbor}, we see the cost profile $\mathcal{C}_{v}$ after considering the travel time along the edge (dashed) and after considering waiting at $v$ (solid). Here, the assumed cost parameters are $\cwait[{\rho(\ensuremath{s})}] = 0$, $\cwait[{\rho(v)}] = 0.5$, and $d = \cwait = 2$, where $\cwait[{\rho(\ensuremath{s})}] = 0$ implies that the cost profile $\mathcal{C}_{\ensuremath{s}}$ at the source is 0 over the whole planning horizon. } \label{fig:exampleAlgorithm} \end{figure} In the initialization phase of the algorithm, we set $\mathcal{C}_\ensuremath{s}(t) := \cwait[{\rho(\ensuremath{s})}] \cdot (t-t^{min})$ for all $t \in H$. For every other $v\in V \setminus \{\ensuremath{s}\}$, we set $\mathcal{C}_v(t) := \infty$ for all $t \in H$. Furthermore, we insert the source $\ensuremath{s}$ with key $t^{min}$ into the priority queue. As long as the queue is not empty, we are in the main loop of the algorithm. In every iteration of the main loop, we remove the top entry from the queue. Let us suppose we visit a vertex $u$ at time $t^{visit} \ge t^{min}$. Then, we check for every edge $e:=(u,v)$ going out of $u$ whether we can improve the cost profile $\mathcal{C}_v$ of $v$. We do so in three steps. In the first step, we consider the travel time along the edge and set \begin{equation} \label{eqn:step1} \mathcal{C}'_v(t) := \mathcal{C}_u(t - \mathcal{T}_e(t)) + d \cdot \delta(e) + \cwait \cdot (\mathcal{T}_e(t) - \delta(e)) \end{equation} for all $t$ with $t^{visit} + \mathcal{T}_e(t) \le t \le t^{max}$. For all other $t\in H$ we set $\mathcal{C}'_v(t) := \infty$. In the second step, we consider waiting at $v$ at cost $\cwait[{\rho(v)}]$ per time unit and set \begin{equation} \label{eqn:step2} \mathcal{C}'_v(t) := \min \{\mathcal{C}'_v(t') + \cwait[{\rho(v)}] \cdot (t-t') \mid t^{min} \le t'\le t \} \end{equation} for all $t \in H$. An example of the first two steps is illustrated in \cref{fig:exampleCostProfileNeighbor}. Finally, in the third step, we compare $\mathcal{C}'_v$ and $\mathcal{C}_v$. Let $t^*$ be the earliest point in time such that $\mathcal{C}'_v(t^*)$ is less than $\mathcal{C}_v(t^*)$ if such a time $t^*$ exists. Only if it exists, we set $\mathcal{C}_v(t)$ to the minimum of $\mathcal{C}_v(t)$ and $\mathcal{C}'_v(t)$ for all $t^* \le t \le t^{max}$. Furthermore, we insert vertex $v$ with key $t^*$ into the priority queue or decrease the key if $v$ is already contained. When the priority queue is empty, we enter the finalization phase of the algorithm. We say a time-cost-pair $(t,\mathcal{C}_\ensuremath{z}(t))$ with $t \in H$ and $\mathcal{C}_\ensuremath{z}(t) < \infty$ is Pareto-optimal if there is no time~$t'$ with $t^{min} \le t' < t$ and $\mathcal{C}_\ensuremath{z}(t') \le \mathcal{C}_\ensuremath{z}(t)$. In the finalization phase, we extract an $\ensuremath{s}$-$\ensuremath{z}$-route for every Pareto-optimal time-cost-pair. So let such a time-cost-pair $(t,\mathcal{C}_\ensuremath{z}(t))$ be given. In order to find a corresponding route $(R, A,D)$, we initially push $\ensuremath{z}$ and $t$ and $t$ to the front of the (empty) sequences $R$ and $A$ and $D$, respectively. The following is done iteratively until we reach the source, that is, $R[1]=\ensuremath{s}$ holds. First, we look for an incoming edge $e:=(u,R[1])$ of $R[1]$ and a departure time $t$ from $u$ with \[\mathcal{C}_u(t) + d \cdot \delta(e) + \cwait \cdot (\mathcal{T}_e(A[1]) - \delta(e)) = \mathcal{C}_{R[1]}(A[1]) \] which must exist. We push $u$ and $t$ to the front of $R$ and $D$, respectively. Then, we push the earliest time $t\le D[1]$ such that \[\mathcal{C}_{R[1]}(t) + \cwait[{\rho({R[1]})}] \cdot (D[1]-t) = \mathcal{C}_{R[1]}(D[1]) \] holds to the front of the arrival time sequence $A$, and continue with the next iteration. This concludes the description of the finalization phase and thus the whole algorithm. For the correctness of the algorithm it is important that the upper bound $\mathcal{C}_v(t)$ on the minimum travel time cost is tight for all $t \le t^{visit}$ and all $v \in V$ whenever we visit a vertex at time $t^{visit}$. After the main loop, it is tight for every $t\in H$ and all $v \in V$, especially for $\ensuremath{z}$. This can be proven by induction on the time of visit. The time of visiting a vertex increases monotonically because whenever a vertex is inserted into the queue or its key is decreased, the (new) value of that key can only be later than the current time of visit. \section{Analysis} \label{sec:analysis} In this section, we first show the intractability of the general problem. Then, we restrict the problem by requiring the driving cost $d$ to be equal to the unrated waiting cost $\cwait$, and prove that our algorithm solves the restricted problem in polynomial time. \subparagraph{Intractability of the General Problem} The first two theorems show the intractability of the general problem if $d \ne \cwait$. Parking locations are not used in the proofs, so already the simplified problem without parking locations is intractable if $d \ne \cwait$. \begin{restatable}{theorem}{nphard} \label{thm:np_hard} If $d < \cwait[0]$ then it is $\textsl{NP}$-complete to decide whether there is a feasible route with travel time costs less than or equal to a given threshold $k$. \end{restatable} We prove this theorem in Appendix~\ref{sec:appendixA} by reduction from PARTITION. \begin{restatable}{theorem}{exproutes} \label{thm:exp_routes} If $d > \cwait[0]$ then the number of Pareto-optimal routes can be exponential in the number of vertices. \end{restatable} Given a number of vertices a graph with ban intervals can be constructed that has exponentially many routes which are all Pareto-optimal. The construction and the proof that all those routes are Pareto-optimal can be found in Appendix~\ref{sec:appendixB}. \subparagraph{Tractable Problem Variant} For the remaining analysis we assume $d = \cwait$. In the setting without parking locations, there is only one optimal solution, since the quickest solution has also the least cost. Hence, this setting is a single-criterion shortest path problem with time-dependent edge weights that fulfill the \emph{FIFO} property and can be solved in polynomial time with a time-dependent variant of Dijkstra's algorithm~\cite{d-aassp-69}, and also our algorithm reduces to such a time-dependent Dijkstra variant and has polynomial running time. Now we turn to the setting $d = \cwait$ with parking locations and show that it is still tractable. Cost profiles are piecewise linear functions. An important aspect of our polynomial time proof is to count the non-differentiable points of the profiles. The running time of each profile operation of our algorithm is linear in the number of non-differentiable points of the involved profiles. These points are either \emph{convex}, \emph{concave}, or \emph{discontinuous}, meaning an environment around such a point exists in which the profile is convex or concave or discontinuous, respectively. In a discontinuous point, a profile is always jumping down. The non-differentiable points in the cost profiles are induced by the travel time functions. In our example of \cref{fig:exampleTravelTimeFunction}, the convex points are $\{4,8,11\}$, the concave points are $\{6,9,12\}$, and the discontinuous points are $\{10,13,15\}$. For a travel time function $\mathcal{T}_e$ of an edge $e$, we can assign a convex point $t$ to the beginning of a ban interval in $t$, a concave point $t$ to the end of a ban interval in $t$, and a discontinuous point $t$ to the end of a ban interval in $t-\mathcal{T}_e(t)$. From this initial assignment, we can derive a ban interval assignment of the convex or discontinuous points of cost profiles. We omit to count the number of concave points of a cost profile because every gradient of a piece must be in $\{\cwait,\ldots,\cwait[r]\}$, so the number of consecutive concave points in a cost profile is limited by $r$. Initially, a profile $\mathcal{C}_{v}$ of a vertex $v$ has no convex or discontinuous points. Such points may be introduced in the third step of an iteration of the algorithm when the auxiliary profile $\mathcal{C}'_{v}$ is merged into $\mathcal{C}_{v}$. In the second step of an iteration, no new convex or discontinuous points can arise in $\mathcal{C}'_{v}$, so all such points must be created in $\mathcal{C}'_{v}$ in the first step. Since $d=\cwait$, $\mathcal{C}'_v(t)$ is set to $\mathcal{C}_u(t - \mathcal{T}_e(t)) + d \cdot \mathcal{T}_e(t)$ (compare \cref{eqn:step1}) for some edge $e=(u,v)$ in this step. If $t_v$ is a convex or discontinuous point of $\mathcal{C}'_v$, then $\mathcal{T}_e$ must be convex or discontinuous in the same point in time, or $\mathcal{C}_u$ must be convex or discontinuous in $t_u:=t_v - \mathcal{T}_e(t_v)$. In the former case, $t_v$ inherits the assignment of the same point in time in $\mathcal{T}_e$, whereas in the latter case, $t_v$ inherits the assignment of $t_u$ in $\mathcal{C}_u$. Since the cost profiles change during the algorithm, we do not only assign a ban interval to every convex or discontinuous point but also an iteration. Again, in the former case, $t_v$ is assigned the current iteration, whereas in the latter case, $t_v$ inherits the iteration assignment of $t_u$ in $\mathcal{C}_u$. \begin{lemma} \label{lemma:numberOfPointsInCostProfile} If $d = \cwait$ then a cost profile after iteration $i$ has at most $ib$ convex and at most $ib$ discontinuous points. \end{lemma} \begin{proof} In the following, we denote the state of the profile $C_v$ after iteration $i$ by $C^i_v$. Let $t_v$ be a convex or discontinuous point of $\mathcal{C}^i_{v}$ that is assigned both to an iteration $k$ and to a ban interval of some edge with head $x$. We can follow the inheritance relation until we finally reach a convex or discontinuous point $t_x$ in $\mathcal{C}^k_x$. By induction, we have $\mathcal{C}^i_v(t_v) = \mathcal{C}^k_x(t_x) + d \cdot (t_v - t_x)$. Now suppose there are two convex or two discontinuous points $t^1_v < t^2_v$ in the profile $\mathcal{C}^i_{v}$ that are assigned to the same ban interval and the same iteration $k$, so they can be traced back to the same point $t_x$ in $\mathcal{C}^k_x$. Then the previous observation implies that $\mathcal{C}^i_v(t^2_v) - \mathcal{C}^i_v(t^1_v) = d \cdot (t^2_v - t^1_v)$ holds, that is, the profile $\mathcal{C}^i_{v}$ must contain a piece with gradient $d$ that contains both $t^1_v$ and $t^2_v$. But then $t^2_v$ can neither be convex nor discontinuous. Hence, two convex or two discontinuous points must differ in their assigned ban interval or their assigned iteration and there can only be $ib$ discontinuous and convex points, respectively. \end{proof} \begin{restatable}{lemma}{iterations} \label{lemma:iterations} If $d = \cwait[0]$ then the total number of iterations is at most $2n(b(r+1)+1)$. \end{restatable} As in the proof of Lemma~\ref{lemma:numberOfPointsInCostProfile} we use the ban interval assignment of convex and discontinuous points. Every visit of a vertex can either be assigned to the start or end of a ban interval, or it can be assigned to a concave point of the final cost profile of the vertex. The detailed proof is omitted due to space limitations and can be found in Appendix~\ref{sec:poly_iterations}. \begin{theorem} If $d = \cwait[0]$ then the running time of the algorithm is polynomial. \end{theorem} \begin{proof} From Lemma~\ref{lemma:numberOfPointsInCostProfile} with the bound from Lemma~\ref{lemma:iterations} it follows that the number of pieces of any profile that is constructed during the algorithm is polynomial. We now estimate the overall running time of our algorithm: Lemma~\ref{lemma:iterations} states that the total number of iterations is polynomial. In every iteration of the algorithm one vertex is considered and for its outgoing edges the profiles are updated with a running time linear in the number of pieces of the profiles. The adjacent vertices are inserted into the priority queue or their keys are decreased. Since the size of the priority queue is at most the total number of vertices also the running time of the priority queue operations is polynomial. \end{proof} \section{Implementation} \label{sec:impl} The past decade has seen a lot of research effort on the engineering of efficient route planning algorithms. This section describes the speed-up techniques we employ in our implementation and some implementation details. We store cost profiles as a sorted list of pieces. Each piece is represented as a triple: a point in time from which this piece is valid, the costs it takes to reach the vertex at the beginning of the piece and the incline of the piece. For each piece we also store a parent vertex. This allows us to efficiently reconstruct routes by traversing the parent pointers. We employ A* to guide the search toward the destination vertex. The queue is ordered by the original key plus an estimate of the remaining distance (here: driving time) to the destination. The estimate for vertex $u$ is denoted by $\pi_\ensuremath{z}(u)$. We use the exact shortest driving time to $\ensuremath{z}$ without driving restrictions as the potential. This is the best possible potential in our case. We efficiently extract these exact distances from a Contraction Hierarchy \cite{gssv-erlrn-12}, as described in \cite{strasser2019perfect}. Since our algorithm has to run until the queue is empty, we can not immediately terminate when we reach the destination. However, we get a tentative cost profile at the destination. This allows for effective pruning. Additionally, we do not need to insert a vertex $u$ into the queue when $t^{visit} + \pi_\ensuremath{z}(u) > t^{max}$ holds, that is, we cannot reach the destination from $u$ within the planning horizon. We employ pruning to avoid linking and merging when possible using the following rules: \begin{itemize} \item Consider a vertex $u$ that is visited at $t^{visit}$. Before relaxing any outgoing edges, we first check if $u$ can actually contribute to any optimal route to $\ensuremath{z}$. If $\mathcal{C}_u(t) + \pi_\ensuremath{z}(u) \cdot d > \mathcal{C}_\ensuremath{z}(t + \pi_\ensuremath{z}(u))$ for all $t$ with $t^{visit} \leq t < t^{max}$, $u$ can not contribute to an optimal route to $\ensuremath{z}$ and can thus be skipped. \item Let $\alpha(u) := \min\{t \mid \mathcal{C}_u(t) < \infty\}$ be the first point in time such that $u$ can be reached with finite costs and $\infty$ if no such point exists. For each vertex $u$, we maintain a lower bound $\beta(u) := \min_t\{\mathcal{C}_u(t)\}$ and an upper bound $\gamma(u) := \max_{t > \alpha(u)}\{\mathcal{C}_u(t)\}$ or $\infty$, if there are no finite costs. They can be updated efficiently during the merge operation. An edge $(u, v)$ only needs to be relaxed if $\beta(u) + \delta(u, v) \cdot d \leq \gamma(v)$ or $\alpha(u) + \delta(u, v) < \alpha(v)$. \item When all of the pieces of the cost profile of a vertex $u$ share the same parent vertex $v$ and $\rho(u) = 0$, the edge $(u, v)$ back to the parent does not need to be relaxed as loops can never be part of an optimal route unless they include waiting at a parking location. \end{itemize} \section{Experimental Evaluation} \label{sec:exp} Our algorithm is implemented in C++14 and compiled with Visual C++. For the CH-potentials, we build upon the Contraction Hierarchy implementation of RoutingKit\footnote{\url{https://github.com/RoutingKit/RoutingKit}}~\cite{dsw-cch-15}. All experiments were conducted on a Windows 10 Pro machine with an Intel i7-7600 CPU with a base frequency of 3.4\,GHz and 32\,GB of DDR4 RAM. The implementation is single-threaded. Our experimental setup is taken from~\cite{b-rptrc-18}. We perform experiments on a road network used in production by PTV\footnote{\url{https://ptvgroup.com}}. The network is adapted from data by TomTom\footnote{\url{https://tomtom.com}}. It covers Austria, France, Germany, Italy, Liechtenstein, Luxembourg, and Switzerland. It has 21.9 million vertices and 47.6 million edges. We use travel times, driving bans, and road closures for a truck with a gross combined weight of 40~tons. Driving bans were derived from the current legislation of the respective countries. This includes Sunday driving bans in all countries, a late Saturday driving ban in Austria and night driving bans in Austria, Liechtenstein and Switzerland. Additionally, there is a Saturday driving ban in Italy during the summer holidays. The dataset also includes several local road closures in city centers. Parking locations were taken from data by Truck Parking Europe\footnote{\url{https://truckparkingeurope.com}}. There is a total of 15\,317 vertices classified as parking locations in our data set. The dataset also contains the capacity of each parking location. We assign each parking location a rating between 1 and 5 depending on its capacity. Table~\ref{tab:parking_lots} shows the number of parking locations for each rating and our default waiting costs. We also evaluate different parameterizations. The waiting costs are calculated such that for an hour of waiting a detour of up to four minutes will be taken to get to a parking location rated better by one. For waiting at the source vertex of a query, we assign zero waiting costs regardless of the rating. \begin{table} \centering \caption{Rating and default waiting cost by capacity of parking locations. The driving cost is the same as the cost for waiting at unrated vertices.}\label{tab:parking_lots} \begin{tabular}{lrrrrrr} \toprule Capacity of parking locations & $\geq 80$ & $\geq 40$ & $\geq 15$ & $\geq 5$ & $\geq 1$ & - \\ \midrule Rating & 5 & 4 & 3 & 2 & 1 & 0 \\ Default waiting costs & 3 & 4 & 5 & 6 & 7 & 14 \\ Number of parking locations & 448 & 997 & 2\,664 & 5\,418 & 5\,748 & 21.9\,M \\ \bottomrule \end{tabular} \end{table} We generate two sets of source-destination pairs and combine them with different planning horizons. The first set is used to evaluate the practicality of our model. It is designed to make the algorithm cope with the night driving ban in Austria and Switzerland. We select 100 pairs of vertices. One vertex is randomly selected from the area around southern Germany. The other vertex is selected from the area around northern Italy. See Figure~\ref{fig:geofence_vis} for exact coordinates and a visualization. We store each pair in both directions. Hence, we have 200 vertex pairs in this set. The planning horizon starts at Monday 2018/7/2, 18:00 with length one day (query set A1) and two days (A2). Figure~\ref{fig:result_example} depicts an example query from A1. The second set is generated by selecting 100 source vertices uniformly at random. From each source vertex, we run Dijkstra's algorithm without a specific target ignoring any driving restrictions. Dijkstra's algorithm explores the graph by traversing vertices in increasing distance of the source vertex. We use the order in which vertices are settled to select destination vertices with different distances from the source. Every $2^i$th settled vertex with $i \in [12,24]$ is stored. We denote $i$ as the \emph{rank} of the query. This results in 1\,300 source-destination pairs. We combine these vertex pairs with four planning horizons: starting at Friday 2018/7/6, 06:00 for one day (denoted as query set B1), for two days (B2) and starting later that day at 18:00 for one day (B3) and for two days (B4). \begin{figure} \centering \includegraphics[width=.5\textwidth]{Figures/compareSimple.PNG} \caption{ Optimal paths of an example query from northwestern Austria to northern Italy, slightly south of Milano. The source is indicated by a red, the destination by a yellow marker. The other markers indicate the parking locations along the respective routes. The blue route in the east has the shortest driving time, around 10.5 hours, but the latest arrival. It schedules a waiting time of seven hours during the night driving ban at a parking location of rating 4 and afterwards takes the fastest route to the destination. The green route in the middle arrives an hour earlier at the destination but the driving time is over two hours longer. This route includes three hours of waiting at a parking location of rating 5. The black route in the west takes 16 hours to drive, includes only a few minutes of waiting and arrives six minutes before the green one. } \label{fig:result_example} \end{figure} \begin{table} \centering \caption{ Query statistics for different waiting cost parameters for query set A1. The first six columns show the waiting cost parameters. Waiting costs at the source are always set to zero. The waiting time columns depict the share of the time spent waiting at vertices with the respective rating summed up over all routes. The routes column gives the average number of optimal routes per query. The arrival time deviation column contains the average of the difference between earliest and latest arrival time among all optimal routes for all queries. Running times are also averaged. }\label{tab:cost_params} \begin{tabular}{r@{\hskip4pt}r@{\hskip4pt}r@{\hskip4pt}r@{\hskip3pt}r@{\hskip2pt}rr@{\hskip5pt}r@{\hskip5pt}r@{\hskip5pt}r@{\hskip5pt}r@{\hskip5pt}r@{\hskip5pt}r@{\hskip5pt}r@{\hskip5pt}r@{\hskip5pt}r@{\hskip5pt}r} \toprule {} & {} & {} & {} & {} & {} & {} & {} & {} & {} & {} & {} & {} & Optimal & Arrival time & Running \\ {} & {} & {} & {} & {} & {} & \multicolumn{7}{c}{Waiting time by rating [\%]} & Routes & deviation & time \\ \cmidrule(lr){7-13} $\cwait[5]$ & $\cwait[4]$ & $\cwait[3]$ & $\cwait[2]$ & $\cwait[1]$ & $\cwait[0] = d$ & $\ensuremath{s}$ & 5 & 4 & 3 & 2 & 1 & 0 & [\#] & [h:mm] & [ms] \\ \midrule 1 & 10 & 50 & 100 & 1000 & 10000 & 59.4 & 2.5 & 5.8 & 23.3 & 3.1 & 2.8 & 3.1 & 3.02 & 2:21 & 364.1 \\ 1 & 2 & 4 & 8 & 16 & 128 & 62.2 & 3.5 & 6.5 & 19.8 & 2.1 & 2.8 & 3.1 & 3.02 & 2:20 & 412.3 \\ 1 & 2 & 4 & 8 & 16 & 32 & 70.8 & 6.0 & 5.1 & 12.1 & 1.0 & 1.9 & 3.1 & 2.96 & 2:20 & 435.4 \\ 3 & 4 & 5 & 6 & 7 & 14 & 79.3 & 6.2 & 3.1 & 4.6 & 1.5 & 2.0 & 3.3 & 2.86 & 2:17 & 529.4 \\ 16 & 24 & 28 & 30 & 31 & 32 & 85.2 & 4.6 & 1.1 & 3.3 & 1.1 & 1.1 & 3.6 & 2.71 & 2:14 & 742.2 \\ \bottomrule \end{tabular} \end{table} We first investigate whether allowing waiting everywhere (albeit penalized) may lead to unwanted results in practice. On the one hand, routes with many stops are impractical. Our experiments indicate that this is not the case: Accross all routes for A1, there is at most one additional stop scheduled (0.2 on average). On the other hand, let us call a route \emph{precarious} if waiting is scheduled at an unrated location (other than the source vertex). For 187 of the 200 queries of A1, there is no precarious route in the Pareto set. For the other 13 queries, the Pareto set always contains more than one route, and it is always only the quickest route in the Pareto set that is precarious. So filtering out such routes in a postprocessing step does not make a query infeasible. On average, the second quickest route in the Pareto set arrives 422\,s later than the quickest but precarious route (minimum 38\,s, maximum 877\,s). We also evaluate the influence of different waiting cost parameterizations on the performance and the results of our algorithm. Table~\ref{tab:cost_params} depicts the results. We observe that the parametrization has only limited influence on the results of the algorithm. The average number of optimal routes and the arrival time deviation change only very little even between the two most extreme configurations. Since waiting at the source vertex costs nothing, the majority of the waiting in all configurations is scheduled there. When waiting at parking locations is much cheaper than driving, less waiting time will be scheduled at the source and more waiting at parking locations. Also, clear differences between the costs lead to a better running time, because cost profiles become less complex. \begin{table} \centering \caption{Query statistics for all six query sets. First, for all queries. Second, only for non-trivial queries. A query is denoted as trivial if there is exactly one optimal route which is also optimal when ignoring all driving restrictions. All numbers are averages unless reported otherwise. The arrival time deviation column contains the average of the difference between earliest and latest arrival time among all optimal routes for all queries. The routes column contains the number of optimal routes.}\label{tab:perf} \begin{tabular}{r@{\hskip4pt}r@{\hskip4pt}lrrrrrr} \toprule & & & Query & Optimal & Arrival time & \multicolumn{2}{c}{Running time} \\ \cmidrule(lr){7-8} & & & share & Routes & deviation & Avg. & Median \\ & Set & Planning horizon & [\%] & [\#] & [h:mm] & [ms] & [ms] \\ \midrule & A1 & Mon. 18:00, 1 day & 100.0 & 2.86 & 2:17 & 529.4 & 266.3 \\ & A2 & Mon. 18:00, 2 days & 100.0 & 3.54 & 3:19 & 648.1 & 405.6 \\ & B1 & Fri. 06:00, 1 day & 100.0 & 1.04 & 0:10 & 10.0 & 0.6 \\ & B2 & Fri. 06:00, 2 days & 100.0 & 1.08 & 0:16 & 79.5 & 0.7 \\ & B3 & Fri. 18:00, 1 day & 100.0 & 1.13 & 0:08 & 205.8 & 0.6 \\ & B4 & Fri. 18:00, 2 days & 100.0 & 1.32 & 0:20 & 1\,028.1 & 0.7 \\ \midrule \parbox[t]{3mm}{\multirow{6}{*}{\rotatebox[origin=c]{90}{Only non-trivial}}} & A1 & Mon. 18:00, 1 day & 67.5 & 3.82 & 3:13 & 764.1 & 560.6 \\ & A2 & Mon. 18:00, 2 days & 72.0 & 4.53 & 4:37 & 899.2 & 655.0 \\ & B1 & Fri. 06:00, 1 day & 4.1 & 2.19 & 4:10 & 42.5 & 6.6 \\ & B2 & Fri. 06:00, 2 days & 4.8 & 2.76 & 5:43 & 1\,105.6 & 35.8 \\ & B3 & Fri. 18:00, 1 day & 9.2 & 2.73 & 1:25 & 1\,359.0 & 475.2 \\ & B4 & Fri. 18:00, 2 days & 11.6 & 3.79 & 2:51 & 5\,819.4 & 1\,947.2 \\ \bottomrule \end{tabular} \end{table} We next investigate the algorithm's performance for each of the different query sets. We report the same numbers limited to non-trivial queries. A query is denoted as \emph{trivial} if there is exactly one optimal route which is also optimal when ignoring all driving restrictions. Table~\ref{tab:perf} depicts the results. Clearly, the query set has a strong influence on the running time of the algorithm. Average running times range from ten milliseconds to one second when looking at all queries. However, median query times are significantly smaller. The reason for this is that our algorithm can answer trivial queries in a few milliseconds or less. Due to the perfect potentials, the algorithm only traverses the optimal path. Once the destination is reached, because of the target pruning, all other vertices in the queue are skipped and the algorithm terminates. Excluding trivial queries, we get a clearer picture of the algorithm's performance when solving the harder part of the problem. For the query sets B1 and B2, only 4\% to 5\% of the queries have to deal with driving restrictions. This is mostly due to closures for individual roads in certain cities and not country-wide driving bans. When the planning horizon begins later at 18:00 (B3 and B4), we get around twice as many non-trivial queries. These are primarily caused by the night driving bans in Austria and Switzerland. Road closures and country-wide driving bans lead to different optimal routes. When there is a road closure on the shortest path ignoring any driving restrictions, we often have two optimal routes. One which takes a (small) detour around the closure, and one waiting at the source until the closed road opens and then taking that slightly shorter path. Thus, we have two routes with very similar driving times but (often vastly) diverging arrival times. When dealing with night driving bans, we get more optimal results with different trade-offs as in the example of Figure~\ref{fig:result_example}. Increasing the length of the planning horizon to two days leads to more non-trivial queries, more optimal routes per query, and a greater deviation in arrival time. The reason are routes with a travel time longer than 24 hours which were not valid for the shorter planning horizon. Even when we restrict ourselves to queries with non-trivial results, running times still vary depending on the query set. Average and median deviate not as strong as when considering all queries, but the distribution of running times is still skewed by a few long running queries, especially on set B4. The reason for this is that the running time heavily depends on the types and lengths of driving restrictions in the search space. The Saturday driving ban in Italy causes heavy outliers in B4 (but also B2 and B3), when the destination lies in an area blocked for most of the planning horizon. This causes the algorithm to explore large parts of the graph, until the driving ban is over. The worst of these queries took 49 seconds to answer. Nevertheless, when looking at query sets A1 and A2, we clearly see that the algorithm can answer queries affected by country-wide night driving bans in less than a second. \section{Conclusion} \label{sec:conclusion} We have introduced a variant of the shortest path problem where driving on edges may be forbidden at times, both driving and waiting entail costs, and the cost for waiting depends on the rating of the respective location. The objective is to find a Pareto set of both quickest paths and minimum cost paths in a road graph. We have presented an exact algorithm for this problem and shown that it runs in polynomial time if the cost for driving is the same as for waiting in an unrated location. With this algorithm, we can solve routing problems that arise in practice in the context of temporary driving bans for trucks as well as temporary closures of roads or even larger parts of the road network. Our experiments demonstrate that our implementation can answer queries with realistic driving restrictions in less than a second on average. There are a few slow outlier queries when the destination vertex lies in a blocked area. A promising angle to improve this could be to study bidirectional variants of our algorithm. We exploit Contraction Hierarchies to efficiently obtain good A* potentials. The algorithm can also be used in a dynamic (or live or online) scenario when combined with Customizable Contraction Hierarchies~\cite{dsw-cch-15}. A natural extension of our problem at hand is to consider time-dependent driving times or rules for truck drivers that enforce a break after a certain accumulated driving time. \input{temporary_road_closures.bbl}
{'timestamp': '2020-04-21T02:24:10', 'yymm': '2004', 'arxiv_id': '2004.09163', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09163'}
arxiv
\section{Introduction} Many natural phenomena can be modeled by graph processes, where each node of the graph is in a state (represented by a color), and each node can change its state based on the states of its neighbors. Such processes have been studied since the dawn of computer science, by, e.g., von Neumann, Ulam, and Conway. Among the numerous applications of these graph processes, the most eminent ones today are possibly neural networks, both biological and artificial. Two fundamental graph processes are majority and minority processes. In a \textit{majority process}, each node wants to switch to the most frequent color in its neighborhood. Such a process is a straightforward model of influence spreading in networks, and as such, it has various applications in social science, political science, economics, and many more \cite{MajApplic1, MajApplic2, MajApplic3, MajApplic4, MajApplic5}. In contrast, in a \textit{minority process}, each node wants to switch to the least frequent color in its neighborhood. Minority processes are used to model scenarios where the nodes are motivated to anti-coordinate with each other, like frequency selection in wireless communication, or differentiating from rival companies in economics \cite{KPRanticoor, MinApplic1, MinApplic2, MinApplic3, MinApplic4}. Majority and minority processes have been studied in several different models, the most popular being the synchronous model (where in each step, all nodes can switch simultaneously) and the sequential model (where in each step, exactly one node switches). Since in many application areas, it is unrealistic to assume that nodes switch at the exact same time, we focus on the sequential model in this paper. We are interested in the worst-case stabilization time of such processes, i.e. the maximal number of steps until no node wants to change its color anymore. Our main parameter describes how easily nodes will switch their color. Previously, the processes have mostly been studied under the basic switching rule, when nodes are willing switch their color for any small improvement. However, it is often more reasonable to assume a \textit{proportional switching rule}, i.e. that nodes only switch their color if they are motivated by at least, say, 70\% of their neighbors to do so. In general, we describe such proportional processes by a parameter $\lambda \in (0,1)$, and say that a node is switchable if it is in conflict with a $\frac{1+\lambda}{2}$ portion of its neighborhood. The stabilization time in such proportional processes (possibly as a function of $\lambda$) has so far remained unresolved. The reason we can analyze proportional majority and minority processes together is that both can be viewed as a special case of a more general process of propagating conflicts through a network, where the cost of relaying conflicts through a node is proportional to the degree of the node. This more general process could also be used to model the propagation of information, energy, or some other entity through a network. This suggests that our results might also be useful for gaining insights into different processes in a wide range of other application areas, e.g. the behavior of neural networks. In the paper, we provide a tight characterization of the maximal possible stabilization time of proportional majority and minority processes. We show that for maximal stabilization, a critical parameter is the portion $\varphi$ of the neighborhood that nodes use as `outputs', i.e. neighbors they propagate conflicts to. Based on this, we prove that the stabilization time of proportional processes follows a transition between quadratic and linear time, described by the non-elementary function \begin{equation} \label{eq:f} f(\lambda) := \max_{\varphi \in (0,\frac{1-\lambda}{2}]} \; \frac{\log\left( \frac{1-\varphi}{\lambda+\varphi} \right)}{\log\left( \frac{1-\varphi}{\varphi} \right)}. \end{equation} More specifically, for any $\epsilon > 0$, we show that on the one hand, $O(n^{1+f(\lambda)+\epsilon})$ is an upper bound on the number of steps of any majority/minority process, and on the other hand, there indeed exists a graph construction where the processes last for $\Omega(n^{1+f(\lambda)-\epsilon})$ steps. \section{Related Work} Various aspects of both majority and minority processes on two colors have been studied extensively. This includes basic properties of the processes \cite{Goles, Winkler}, sets of critical nodes that dominate the process \cite{MajApplic3, MajOther1, Dynamo3}, complexity and approximability results \cite{votingtime, approx0, influenceApprox}, threshold behavior in random graphs \cite {MajOther2, Ahad2018}, and the analysis of stable states in the process \cite{SGPclass1, SGPclass3, SGPclass4, SGPsurvey, noUGP, KPRanticoor}. Modified process variants have also been studied \cite{certainityMaj, switchOnce}, with numerous generalizations aiming to provide a more realistic model for social networks \cite{SocialGen1, SocialGen2}. However, the question of stabilization time in the processes has almost exclusively been studied for the basic switching rule (defined in Section \ref{sec:models}). Even for the basic rule, apart from a straightforward $O(n^2)$ upper bound, the question has remained open for a long time in case of both processes. It has recently been shown in \cite{majority} and \cite{minority} that both processes can exhibit almost-quadratic stabilization time in case of basic switching, both in the sequential adversarial and in the synchronous model. On the other hand, the maximal stabilization time under proportional switching has remained open so far. It has also been shown that if the order of nodes is chosen by a benevolent player, then the behavior of the two processes differs significantly, with the worst-case stabilization time being $O(n)$ for majority processes \cite{majority} and almost-quadratic for minority processes \cite{minority}. In weighted graphs, where the only available upper bound on stabilization time is exponential, it has been shown that both majority and minority can indeed last for an exponential number of steps in various models \cite{majorityW, minorityW}. The result of \cite{minorityW} is the only one to also study the proportional switching rule, showing that the exponential lower bound also holds in this case; however, since the paper studies weighted graphs with arbitrarily high weights, this model differs significantly from our unweighted setting. Stabilization time has also been examined in several special cases, mostly assuming the synchronous model. The stabilization of a slightly different minority process variant (based on closed neighborhoods) has been studied in special classes of graphs including grids, trees and cycles \cite{CA1, CA2, CA3}. The work of \cite{hedetniemi} describes slightly modified versions of minority processes which may take $O(n^5)$ or $O(n^6)$ steps to stabilize, but provide better local minima (stable states) upon termination. For majority processes, stabilization has mostly been studied from a random initial coloring, on special classes of graphs such as grids, tori and expanders \cite{MajOther2, Ahad2018}. Various aspects of majority processes have also been studied under the proportional switching rule, including sets of critical nodes that dominate the process, and sets of nodes that always preserve a specific color \cite{propDynamos1, propDynamos2}. However, to our knowledge, the stabilization time of the processes with proportional switching has not been studied before. \section{Model and Notation} \subsection{Preliminaries} We define our processes on simple, unweighted, undirected graphs $G(V,E)$, with $V$ denoting the set of nodes and $E$ the set of edges. We denote the number of nodes by $n=|V|$. The neighborhood of $v$ is denoted by $N(v)$, the degree of $v$ by $\text{deg}(v)=|N(v)|$. We also use simple directed graphs in our proofs. A directed graph is called a DAG if it contains no directed cycles. A \textit{dipartitioning} of a DAG is a disjoint partitioning ($V_1$, $V_2$) of $V$ such that each source node is in $V_1$, and all edges between $V_1$ and $V_2$ all go from $V_1$ to $V_2$. We refer to the set of edges from $V_1$ to $V_2$ as a \textit{dicut}. Given an undirected graph $G$ with edge set $E$, we also define the \textit{directed edge set} of $G$ as $\widehat{E}=\{ (u,v), (v,u) \: | \: (u,v) \in E \}$, i.e. the set of directed edges obtained by taking each edge with both possible orientations. A \textit{coloring} is a function $\gamma:V \rightarrow \{\text{black, white}\}$. A \textit{state} is a current coloring of $G$. Under a given coloring, we define $N_s(v)=\{ u \in N(v) | \gamma(v)=\gamma(u) \} $ and $N_o(v)=\{ u \in N(v) | \gamma(v) \neq \gamma(u) \} $ as the same-color and opposite-color neighborhood of $v$, respectively. We say that there is a \textit{conflict} on edge $(u,v)$, or that $(u,v)$ is a \textit{conflicting edge}, if $u \in N_o(v)$ in case of a majority process, and if $u \in N_s(v)$ in case of a minority process. In general, we denote the conflict neighborhood by $N_c(v)$, meaning $N_c(v) = N_o(v)$ and $N_c(v) = N_s(v)$ in case of majority and minority processes, respectively. We occasionally also use $N_{\neg c}(v)=N(v) \setminus N_c(v)$. If a node $v$ has more conflicts than a predefined threshold (depending on the so-called \textit{switching rule} in the model, discussed later) in the current state, then $v$ is \textit{switchable}. Switching $v$ changes its color to the opposite color. If edge $(u,v)$ becomes (ceases to be) a conflicting edge when node $v$ switches, then we say that $v$ has \textit{created} this conflict (\textit{removed} this conflict, respectively). A \textit{majority/minority process} is a sequence of steps (states), where each state is obtained from the previous state by a set of switchable nodes switching. In this paper, we examine sequential processes, when in each step, exactly one node switches. Such a process is \textit{stable} when there are no more switchable nodes in the graph. By \textit{stabilization time}, we mean the number of steps until a stable state is reached. \subsection{Model and switching rule} \label{sec:models} We study the worst-case stabilization time of majority/minority processes, that is, the maximal number of steps achievable on any graph, from any initial coloring. In other words, we assume the \textit{sequential adversarial model}, when the order of nodes (i.e., the next switchable node to switch in each time step) is chosen by an adversary who maximizes stabilization time. It only remains to specify the condition that allows a node to switch its color. The most straightforward switching rule is the following: \begin{rules}[\textbf{Basic Switching}] Node $v$ is switchable if $|N_c(v)| - |N_{\neg c}(v)| > 0$. \end{rules} An equivalent form of this rule is $|N_c(v)| > \frac{1}{2} \cdot \text{deg}(v)$. This rule is shown to allow up to $\widetilde{\Theta}(n^2)$ stabilization time for both majority \cite{majority} and minority \cite{minority} processes. However, it is often more realistic to assume a proportional switching rule, based on a real parameter $\lambda \in (0, 1)$: \begin{rules}[\textbf{Proportional Switching}] Node $v$ is switchable if $|N_c(v)| - |N_{\neg c}(v)| \geq \lambda \cdot \text{deg}(v)$. \end{rules} Since we have $|N_c(v)| + |N_{\neg c}(v)| = \text{deg}(v)$, this is equivalent to saying that $v$ is switchable exactly if $|N_c(v)| \geq \frac{1+\lambda}{2} \cdot \text{deg}(v)$. In the limit when $\lambda$ is infinitely small (or, equivalently, as $\frac{1+\lambda}{2}$ approaches $\frac{1}{2}$ from above), we obtain Rule I as a special case of Rule II. In case of Rule I, whenever a node $v$ switches, it is possible that the total number of conflicts in the graph decreases by 1 only. On the other hand, Rule II implies that the switching of $v$ decreases the total number of conflicts at least by $\lambda \cdot \text{deg}(v)$ (we say that $v$ \textit{wastes} these conflicts), so in case of Rule II, the total number of conflicts can decrease more rapidly, allowing only a smaller stabilization time. Our findings show that the maximal number of steps is different for every distinct $\lambda$. \subsection{On the $f(\lambda)$ function} While the processes have a symmetric definition on each edge by default, it turns out that in order to maximize stabilization time, each edge has to be used in an asymmetric way. The most important parameter at each node $v$ is the ratio of neighbors $v$ uses as `inputs' and as `outputs'. That is, the optimal behavior for each node $v$ is to select $\varphi \cdot \text{deg}(v)$ of its neighbors as outputs (for some $\varphi \in (0,1)$), and create all new conflicts on the edges leading to these output nodes, and similarly, mark the remaining $(1-\varphi) \cdot \text{deg}(v)$ neighbors as inputs, and only remove conflicts from the edges coming from these input nodes. Note that with Rule II, whenever a node switches, it can create at most $\left(1-\frac{1+\lambda}{2}\right) \cdot \text{deg}(v)=\frac{1-\lambda}{2} \cdot \text{deg}(v)$ new conflicts, so it is reasonable to assume $\varphi \in \left(0,\frac{1-\lambda}{2}\right]$. Our results show that if all nodes select $\varphi$ as their output rate, then the maximal achievable stabilization time is a function of \begin{equation} \label{eq:relay} \frac{\log\left( \frac{1-\varphi}{\lambda+\varphi} \right)}{\log\left( \frac{1-\varphi}{\varphi} \right)}. \end{equation} As such, the largest stabilization time can be achieved by maximizing this expression by selecting the optimal $\varphi$ value, as shown in the definition of $f$ in Equation \ref{eq:f}. We denote the optimal value of $\varphi$ (i.e., the $\text{arg} \text{max}$ of Equation \ref{eq:relay}) by $\varphi^*$. The function $f$ has no straightforward closed form, as such a form would require solving \[ (\lambda+1) \cdot \varphi \cdot \log\left( \frac{1-\varphi}{\varphi} \right) = (\lambda+\varphi) \log \left( \frac{1-\varphi}{\lambda+\varphi} \right), \] for $\varphi$, with $\lambda$ as a parameter. A more detailed discussion of $f$ is available in Appendix \ref{App:C}. \begin{figure} \captionsetup{justification=centering} \centering \includegraphics[width=0.6\textwidth]{proportionals_diff.eps} \caption{Plot of $f(\lambda)$ and $\varphi^*(\lambda)$ for $\lambda \in (0, 1)$} \label{fig:func} \end{figure} Figure \ref{fig:func} shows the values of $f$ and $\varphi^*$ as a function of $\lambda$. The figure shows that both $f(\lambda)$ and $\varphi^*(\lambda)$ are continuous, monotonically decreasing and convex. It is visible that $\lim_{\lambda \rightarrow 0}f(\lambda)=1$ and $\lim_{\lambda \rightarrow 1}f(\lambda)=0$. This is in line with what we would expect: the simple switching rule allows a stabilization time up to $\widetilde{\Theta}(n^2)$ \cite{majority, minority}, while even for any large $\lambda<1$, it is still straightforward to present a graph with $\Omega(n)$ stabilization time. Our main result is showing that $f(\lambda)$ describes the continuous transition between these two extremes. \section{General intuition behind the proofs} \label{sec:prop} Note that initially, each node $v$ can have at most $\text{deg}(v)$ conflicts on its incident edges, and each time when $v$ switches, it wastes $\lambda \cdot \text{deg}(v)$ conflicts. Therefore, if each node were to `use' its own initial conflicts only, then each node could switch at most $\frac{1}{\lambda}$ times, and stabilization time could never go above $O(n)$. Instead, the idea is to take the high number of conflicts initially available at high-degree nodes, and use these conflicts to switch the less wasteful low-degree nodes many times. Specifically, we could have a set of $\Theta(n)$-degree nodes that initially have $\Omega(n^2)$ conflicts altogether on their incident edges, and somehow relay these conflicts to another set of $O(1)$-degree nodes, which only waste $O(1)$ conflicts at each switching. However, due to the large difference both in degree and in the number of switches, it is not possible to connect these two sets directly; instead, we need to do this through a range of intermediate levels, which exhibit decreasing degree and increasingly more switches. In order to maximize stabilization time, our main task is to move conflicts through these levels as efficiently (i.e., wasting as few conflicts in the process) as possible. The formula of $f(\lambda)$ describes the efficiency of this process. The rate of inputs to outputs $\frac{1-\varphi}{\varphi}$ determines the factor by which the degree decreases at every new level. If $\varphi$ is chosen small, then $\frac{1-\varphi}{\varphi}$ is high, so we only have a few levels until we reach constant degree, and hence the number of switches is increased only a few times. On the other hand, the increase in the number of switches per level is expressed by $\frac{1-\varphi}{\lambda+\varphi}$, which is a decreasing function of $\varphi$. If $\varphi$ is too large, then although we execute this increase more times, each of these increases is significantly smaller. With a degree decrease rate of $\frac{1-\varphi}{\varphi}$, we can altogether have about $\log_{\frac{1-\varphi}{\varphi}}(n)$ levels until the degree decreases from $\Theta(n)$ to $\Theta(1)$. If we increase the number of switches by a factor of $\frac{1-\varphi}{\lambda+\varphi}$ each time, then the $O(1)$-degree nodes will exhibit \begin{equation} \label{eq:match} \left( \frac{1-\varphi}{\lambda+\varphi} \right)^{\log_{\frac{1-\varphi}{\varphi}}(n)} = n^{\frac{\log\left( \frac{1-\varphi}{\lambda+\varphi} \right)}{\log\left( \frac{1-\varphi}{\varphi} \right)}} \leq n^{f(\lambda)} \end{equation} switches, with an equation only if $\varphi=\varphi^*(\lambda)$. Having $\widetilde{\Theta}(n)$ nodes in the last level, this sums up to about $n^{1+f(\lambda)}$ switches altogether. \subsection{Conflict propagation systems} The upper bound on stabilization time is easiest to present in a general form that only focuses on this flow of conflicts in the graph. We define a simpler representation of the processes which only keeps a few necessary concepts to describe the flow of conflicts, and ignores e.g. the color of nodes or the timing of the switches at each node. In fact, we only require the number of times $s(v)$ each $v \in V$ switches, and the number $c(u,v)$ of conflicts that were created by node $u$ and then removed by node $v$, for each $(u,v) \in \widehat{E}$. For simplicity, given a function $c:\widehat{E} \rightarrow \mathbb{N}$, let us introduce the notation $c_{in}(v) := \sum_{u \in N(v)} c(u,v)$ and $c_{out}(v) := \sum_{u \in N(v)} c(v,u)$. \begin{definition}[\textbf{Conflict Propagation System, CPS}] Given an undirected graph $G$, a conflict propagation system is an assignment $s:V \rightarrow \mathbb{N}$ and $c:\widehat{E} \rightarrow \mathbb{N}$ such that \begin{enumerate} \item for each $v \in V$, we have $c_{in}(v) +\text{deg}(v) \geq \lambda \cdot \text{deg}(v) \cdot s(v) + c_{out}(v)$, \item for each $v \in V$, we have $c_{out}(v) \leq \frac{1-\lambda}{2} \cdot \text{deg}(v) \cdot s(v)$, and \item for each $(u,v) \in \widehat{E}$, we have $c(u,v) \leq s(u)$. \end{enumerate} \end{definition} With the choice of $s(v)$ and $c(u,v)$ described above, any proportional majority or minority process indeed satisfies these properties, and thus provides a CPS. Hence if we upper bound the stabilization time (i.e. the total number of switches $\sum_{v \in V} s(v)$) of any CPS, this establishes the same bound on the stabilization time of any majority/minority process. Condition 1 is the most complex of the three; it expresses the amount of `input conflicts' $c_{in}(v)$ required to switch $v$ an $s(v)$ times altogether. Every time after $v$ switches, it has at most $\frac{1-\lambda}{2} \cdot \text{deg}(v)$ conflicts on the incident edges, so it needs to acquire $\lambda \cdot \text{deg}(v)$ new conflicts to reach the threshold of $\frac{1+\lambda}{2} \cdot \text{deg}(v)$ and be switchable again; this results in the $\lambda \cdot \text{deg}(v) \cdot s(v)$ term. Moreover, if in the meantime, the neighboring nodes remove some of the conflicts from the incident edges (expressed by $c_{out}(v)$), then this also has to be compensated for by extra input conflicts. Finally, the extra $\text{deg}(v)$ term comes from the (at most) $\text{deg}(v)$ conflicts that are already on the incident edges in the initial coloring. For a detailed discussion of this condition, see Appendix \ref{App:A}. Condition 2 also holds, since each time when $v$ switches, it creates at most $\frac{1-\lambda}{2} \cdot \text{deg}(v)$ conflicts on the incident edges. Each time $u$ switches, it can only create one conflict on a specific edge, so condition 3 also follows. Hence any majority/minority process indeed provides a CPS. Finally, we need a technical step to get rid of the extra $\text{deg}(v)$ term in condition 1. Note that this term becomes asymptotically irrelevant as $s(v)$ grows; hence, our approach is to handle fewer-switching nodes separately, and require condition 1 only for nodes with large $s(v)$. More formally, we select a constant $s_0$, and we refer to nodes $v$ with $s(v) < s_0$ as \textit{base nodes}. We then consider \textit{Relaxed CPSs}, where, given this extra parameter $s_0$, condition 1 is replaced by: \renewcommand{\labelenumi}{\arabic{enumi}R.} \vspace{5pt} \begin{enumerate} {\setlength\itemindent{8pt} \item \textit{for each $v \in V$ with $s(v) \geq s_0$, we have $ c_{in}(v) \geq \lambda \cdot \text{deg}(v) \cdot s(v) + c_{out}(v)$,}} \end{enumerate} \vspace{6pt} This relaxation comes at the cost of an extra $\epsilon$ additive term in the exponent of our upper bound. \section{Upper bound proof} \label{sec:upper} We now outline the proof of the upper bound on the number of switches. A more detailed discussion of this proof is available in Appendix \ref{App:A}. \subsection{Properties of an optimal construction} We start by noting that since moving a conflict through a node is wasteful, it is suboptimal to have two neighboring nodes that both transfer a conflict to each other, or more generally, to move a conflict along any directed cycle. Therefore, in a CPS with maximal stabilization time, the conflicts are essentially moved along the edges of a DAG. To formalize this, given a CPS, let us say that a directed edge $(u,v) \in \widehat{E}$ is a \textit{real edge} if $c(u,v)>0$. \begin{lemma} There exists a CPS with maximal stabilization time where the real edges form a DAG. \end{lemma} \begin{proof} Among the CPSs on $n$ nodes with maximal stabilization time, let us take the CPS $P$ where the sum $\sum_{e \in \widehat{E}} c(e)$ is minimal. Assume that there is a directed cycle along the real edges of this CPS, and let $c(e_0)$ denote the minimal value of function $c$ along this cycle. Now consider the CPS $P'$ where the value of $c$ on each edge of this directed cycle is decreased by $c(e_0)$. Since in each affected node, the inputs and outputs have been decreased by the same value, $P'$ still satisfies all three conditions, and thus it is also a valid CPS. Moreover, $P'$ has the same amount of total switches as $P$. However, since $c(e_0)>0$, the sum of $c(e)$ values in $P'$ is less than in $P$, which contradicts the minimality of $P$. \qedhere \end{proof} Hence for the upper bound proof, we can assume that the real edges of the CPS form a DAG. In the rest of the section, we focus on this DAG composed of the real edges of the CPS. We first show that for convenience, we can also assume that each base node is a source in this DAG. \begin{lemma} \label{baseSource} There exists a CPS with maximal stabilization time where each base node is a source node of the DAG. \end{lemma} \begin{proof} Note that by removing an input edge $(u,v)$ of a base node $v$ (that is, setting $c(u,v)$ to 0), the remaining CPS is still valid, since node $v$ does not have to satisfy condition 1R, and in node $u$, only the sum of outputs was decreased. Therefore, we can remove all the input edges of each base node, and hence base nodes will all become source nodes of the DAG. \qedhere \end{proof} \begin{lemma} \label{lem:constbase} For each directed edge $(u,v)$ in the DAG where $u$ is a source node, $c(u,v)=O(1)$. More specifically, $c(u,v) \leq s_0$. \end{lemma} \begin{proof} If $u$ is a base node, then $s(u) \leq s_0$, so $c(u,v) \leq s_0$ due to condition 3. Otherwise, condition 1R must hold, and since $u$ has no input nodes, we get $0 \geq c_{out}(u) + \lambda \cdot \text{deg}(u) \cdot s(u)$, hence $c_{out}(u)=0$, so $c(u,v) = 0$ for every $v$. Thus $c(u,v) \leq s_0$. \qedhere \end{proof} \subsection{Edge potential} As a main ingredient of the proof, we define a way to measure how close we are to propagating conflicts optimally. \begin{definition}[\textbf{Potential}] Given a real edge $e \in \widehat{E}$, the potential of $e$ is defined as $P(e)=c(e)^{1/f(\lambda)}$. \end{definition} \noindent For simplicity of notation, we also use $P$ to denote the function $x \rightarrow x^{1/f(\lambda)}$ on real numbers instead of edges. Intuitively speaking, the potential function describes the cost of sending a specific number of conflicts through a single edge, in terms of the number of initial conflicts used up for this. Note that since $f(\lambda)<1$, the function $P$ is always convex. This shows that sending a high number of conflicts through a single edge is more costly than sending the same amount of conflicts through multiple edges. As the following lemma shows, the potential is defined in such a way that the total potential can never increase when passing through a node in the DAG; the best that a node can do is to preserve the input potential if it relays conflicts optimally. \begin{lemma} \label{preservePot} For any non-source node $v$ of the DAG, with input edges from $N_{in}(v)$ and output edges to $N_{out}(v)$, we have \[ \sum_{u \in N_{in}(v)} P(u,v) \geq \sum_{u \in N_{out}(v)} P(v,u) .\] \end{lemma} \begin{proof} If $v$ is not a source, then by Lemma \ref{baseSource} it is not a base node, and thus has to satisfy condition 1R. In our DAG, $c_{in}$ and $c_{out}$ correspond to $\sum_{u \in N_{in}(v)} c(u,v)$ and $\sum_{u \in N_{out}(v)} c(v,u)$, respectively. Assume that we fix the value of $c_{in}$ and $c_{out}$. Since the potential function $P$ is convex, the incoming potential (left side) is minimized if $c_{in}$ is split as equally among the input neighbors as possible. On the other hand, the outgoing potential (right side) is maximized if $c_{out}$ is split as unequally among outputs as possible, so all output edges present in the DAG have the maximal possible number of switches, meaning $c(v,u)=s(v)$ for every $u \in N_{out}(v)$. Assume that a fraction $\varphi$ of $v$'s incident edges are outgoing, i.e. $|N_{out}(v)|=\varphi \cdot \text{deg}(v)$ and $|N_{in}(v)|=(1-\varphi) \cdot \text{deg}(v)$. By condition 1R, we have $c_{in} \geq \lambda \cdot \text{deg}(v) \cdot s(v) + c_{out}$; with $c_{out}=\varphi \cdot \text{deg}(v) \cdot s(v)$, this gives $c_{in} \geq (\lambda+\varphi) \cdot \text{deg}(v) \cdot s(v)$. If split evenly among the $(1-\varphi) \cdot \text{deg}(v)$ inputs, this means \[ \frac{c_{in}}{|N_{in}(v)|} \geq \frac{(\lambda+\varphi) \cdot \text{deg}(v) \cdot s(v)}{(1-\varphi) \cdot \text{deg}(v)} = \left( \frac{\lambda+\varphi}{1-\varphi} \right) \cdot s(v) \] switches for each input node. The inequality on the potential then comes down to \begin{gather*} \sum_{u \in N_{in}(v)} P(u,v) \geq (1-\varphi) \cdot \text{deg}(v) \cdot \left( \frac{\lambda+\varphi}{1-\varphi} \cdot s(v) \right)^{1/f(\lambda)} \geq \\ \geq \varphi \cdot \text{deg}(v) \cdot s(v)^{1/f(\lambda)} \geq \sum_{u \in N_{out}(v)} P(v,u). \end{gather*} To show that the inequality in the middle holds, we only require \[ \left( \frac{\lambda+\varphi}{1-\varphi} \right)^{1/f(\lambda)} \geq \frac{\varphi}{1-\varphi}, \] or, put otherwise, \[ \frac{1}{f(\lambda)} \log \left( \frac{\lambda+\varphi}{1-\varphi} \right) \geq \log \left( \frac{\varphi}{1-\varphi} \right). \] Since $\frac{\varphi}{1-\varphi}<1$ (thus its logarithm is negative), we get \[ \frac{\log \left( \frac{\lambda+\varphi}{1-\varphi} \right)}{\log \left( \frac{\varphi}{1-\varphi} \right)} = \frac{\log \left( \frac{1-\varphi}{\lambda+\varphi} \right)}{\log \left( \frac{1-\varphi}{\varphi} \right)} \leq f(\lambda). \] This holds by the definition of $f(\lambda)$. Note that this also shows that equality can only be achieved if the output rate $\varphi$ is indeed chosen as the argmax value $\varphi^*(\lambda)$. \end{proof} Lemma \ref{preservePot} provides the key insight to the main idea of our proof: if we process the nodes of a DAG according to a topological ordering, always maintaining a dicut of outgoing edges from the already processed part of the DAG, then this potential cannot ever increase when adding a new node. \begin{lemma} \label{cutbound} Given a dicut $S$ of a dipartitioning in the DAG, we have \[ \sum_{e \in S} P(e) = O(n^2) .\] \end{lemma} \renewcommand{\proofname}{Proof (Sketch).} \begin{proof} Each dipartitioning can be obtained by starting from the trivial dipartitioning where $V_1$ only contains the source nodes of the DAG, and then iteratively adding nodes one by one to this initial $V_1$. The number of outgoing edges from this initial $V_1$ (the set of source nodes) is upper bounded by $|E|=O(n^2)$. According to Lemma \ref{lem:constbase}, the number of switches (and hence the potential) on each edge of the dicut is at most constant, so the sum of potential in this initial dicut is also $O(n^2)$. Now consider the process of iteratively adding nodes to this initial $V_1$ to obtain a specific dipartitioning. Whenever we add a new node $v$ to $V_1$, the incoming edges of $v$ are removed from the dicut, and the outgoing edges of $v$ are added to the dicut. According to Lemma \ref{preservePot}, the potential on the outgoing edges of $v$ is at most as much as the potential on the incoming edges, so the sum of potential can not increase in any of these steps. Therefore, when arriving at the final $V_1$, the sum of potential on the cut edges is still at most $O(n^2)$. \end{proof} \renewcommand{\proofname}{Proof} \subsection{Upper bounding switches} \label{sec:upperlast} Finally, we present our main lemma that uses the previous upper bound on potential in order to upper bound the number of switches in the CPS. \begin{lemma} \label{lem:upper} Given a CPS and an integer $a \in \{ 1, ..., n \}$, let $A=\{ v \in V \: | \: a \leq \text{deg(v) \textless \, 2a } \}$. For the total number of switches $s(A)=\sum_{v \in A} s(v)$, we have \[ s(A) = O \left( n^{1+f(\lambda)} \cdot a^{-f(\lambda)} \right). \] \end{lemma} \renewcommand{\proofname}{Proof (Sketch).} \begin{proof} If the input edges of the nodes in $A$ would form the dicut of a dipartitioning, then we could directly use Lemma \ref{cutbound} to upper bound the number of switches in $A$ through the potential of the input edges. However, the nodes of $A$ might be scattered arbitrarily in the DAG, and if there is a directed path from one node in $A$ to another, then the `same' potential might be used to switch more than one node in $A$. Thus we cannot apply Lemma \ref{cutbound} directly. Instead, our proof consists of two parts. 1. First, we define so-called responsibilities for the nodes in $A$. Given a node $v_0 \in A$, the idea is to devise two different functions: (i) a function $\Delta c(e)$, defined on each edge $e$ which is contained in any directed path starting from $v_0$, and (ii) a function $\Delta s(v)$, which is defined on any node $v$ that is reachable from $v_0$ on a directed path. Intuitively, we will consider the conflicts $\Delta c(e)$ and the switches $\Delta s(v)$ to be those that are indirectly `the effects of the switches of $v_0$'. More specifically, $\Delta c$ and $\Delta s$ are chosen such that if they are removed (subtracted from the CPS), then $v_0$ has no output edges in the DAG anymore, and the resulting assignment $s'(v)=s(v)-\Delta s(v)$ and $c'(e)=c(e)-\Delta c(e)$ still remains a valid CPS. Hence the subtraction results in a CPS where $v_0$ has no directed path to other nodes in $A$ anymore. This shows that we can keep on executing this step for each $v_0 \in A$ until no two nodes in $A$ are connected by a directed path, at which point we can apply Lemma \ref{cutbound} to the resulting graph. Whenever we process such a node $v_0 \in A$, we define the \textit{responsibility} of $v_0$ as $R(v_0):=s(v_0) + \sum \Delta s (v)$, where the sum is understood over all the nodes $v \in A$ that are reachable from $v_0$. The main idea is that we `reassign' these switches to $v_0$ from other nodes in $A$. This method is essentially a redistribution of switches in the CPS, so we have $\sum_{v \in A}s(v) = \sum_{v \in A} R(v)$ altogether. Furthermore, our definition of $\Delta s(v)$ will ensure that $R(v_0)=O(1) \cdot s(v_0)$. Intuitively, this can be explained as follows. Recall that with Rule II, the ratio of output to input conflicts is always upper bounded by a constant factor (below 1) at every node, since switching always wastes a specific proportion of conflicts. Hence, over any path starting from $v_0$, the number of outputs that can be attributed to $v_0$ forms a geometric series. As the ratio of the geometric series is below 1, the total amount of conflicts caused by $v_0$ this way is still within the magnitude of the input conflicts of $v_0$. Since each node in $A$ has similar degree (and thus requires similar number of input conflicts for one switching), these conflicts can only switch nodes in $A$ approximately the same number of times as $v_0$ can be switched by its own inputs. A more detailed discussion of this responsibility technique is available in Appendix \ref{App:A}. 2. For the second part of the proof, we show the claim in this modified CPS with no directed path between nodes in $A$. This implies that there exists a dipartitioning where the nodes of $A$ are in $V_2$, but all their input nodes are in $V_1$. This means that all the input edges of each node in $A$ are included in the dicut $S$ of the partitioning. Consider a node $v \in A$. Due to condition 1R, $v$ has at least $\lambda \cdot \text{deg}(v) \cdot s(v)$ input conflicts. Even if these are distributed equally on all incident edges of $v$ (this is the case that amounts to the lowest total potential, since $P$ is convex), this requires a total input potential of \[ \text{deg}(v) \cdot P(\lambda \cdot s(v)) = \text{deg}(v) \cdot s(v)^{1/f(\lambda)} \cdot \lambda^{1/f(\lambda)} \] at least. Recall that Lemma \ref{cutbound} shows that the total potential on all edges in $S$ is $O(n^2)$. Our task is hence to find an upper bound on $\sum_{v \in A} s(v)$, subject to \[ \sum_{v \in A} \text{deg}(v) \cdot s(v)^{1/f(\lambda)} \cdot \lambda^{1/f(\lambda)} = O(n^2) .\] Since the last factor on the left side is a constant, we can simply remove it and include it in the $O(n^2)$ term. Furthermore, the degree of each node in $A$ is at least $a$, so by lower bounding each degree by $a$, we get \[ \sum_{v \in A} s(v)^{1/f(\lambda)} = O(n^2) \cdot \frac{1}{a} .\] Given this upper bound on $\sum_{v \in A} P(s(v))$, since the function $P$ is convex, the sum of switches $\sum_{v \in A} s(v)$ is maximal when each node in $A$ switches the same amount of times (i.e. there is an $s$ such that $s(v)=s$ for every $v \in A$), giving \[ |A| \cdot s^{1/f(\lambda)} = O(n^2) \cdot \frac{1}{a} .\] With this upper bound, $|A| \cdot s$ is maximal if $|A|$ is as large as possible and $s$ as small as possible (again because $P$ grows faster than linearly). Clearly $|A| \leq n$, so assuming $|A|=n$, we get \[ s^{1/f(\lambda)} = O(n) \cdot \frac{1}{a} ,\] which means that \[ s = O(n^{f(\lambda)}) \cdot a^{-f(\lambda)} ,\] and thus for the total number of switches in $A$, we get \[ |A| \cdot s = O(n^{1+f(\lambda)}) \cdot a^{-f(\lambda)} . \qedhere \] \end{proof} \renewcommand{\proofname}{Proof} It only remains to sum up this bound for the appropriate intervals to obtain our final bound. Let us consider the intervals $[1,2)$, $[2,4)$, $[4,8)$, ..., i.e. $a=2^k$ for each factor of 2 up to $n$, which is a disjoint partitioning of the possible degrees. Note that for these specific values of $a$, the sum $ \sum_{k=0}^{\infty} (2^k)^{-f(\lambda)}$ converges to a constant according to the ratio test. In other words, the sum is dominated by the number of switches of the lowest (constant) degree nodes, and hence, the total number of switches in the graph can be upper bounded by $O(1) \cdot n^{1+f(\lambda)}$. Recall that since we work with Relaxed CPSs, we lose an $\epsilon$ in the exponent of this upper bound when we carry the result over to an original CPS. \begin{theorem} In any CPS with parameter $\lambda$, we have $\sum_{v \in V} s(v) =O(n^{1+f(\lambda)+\epsilon})$ for any $\epsilon>0$. \end{theorem} \noindent Since we have established that every majority/minority process provides a CPS, the upper bound on their stabilization time also follows. \begin{corollary} \label{the:upper} Under Rule II with any $\lambda \in (0,1)$, every majority/minority process stabilizes in time $O(n^{1+f(\lambda)+\epsilon})$ for any $\epsilon > 0$. \end{corollary} \section{Lower bound construction} \label{sec:lower} Having established the most efficient way to relay conflicts, the high-level design of the matching lower bound construction is rather straightforward, following the level-based idea described in Section \ref{sec:prop}. Given $\lambda$, we first determine the optimal output rate $\varphi=\varphi^*(\lambda)$. We then create a construction consisting of distinct levels, where each level has the same size, and each consists of a set of nodes that have the same degree. Since the degree should decrease by a factor of $\frac{\varphi}{1-\varphi}$ in each new level from top to bottom, we can add $L = \log_{\frac{1-\varphi}{\varphi}}(n)$ such levels to the graph. If each of these level has $\Theta(\frac{n}{\log{n}})$ nodes, then with the appropriate choice of constants, the total number of nodes is below $n$. Each node in the construction is only connected to other nodes on the levels immediately above or below its own. All conflicts are propagated down in the graph, from upper to lower levels, so the upper neighbors of a node are always used as inputs, while the lower neighbors are always used as outputs. For the optimal propagation of conflicts, each node $v$ must have the optimal input-output rate, i.e. an up-degree of $(1-\varphi) \cdot \text{deg}(v)$ and a down-degree of $\varphi \cdot \text{deg}(v)$. Thus each consecutive level pair forms a regular bipartite graph, with $\frac{\varphi}{1-\varphi}$ of the degree of the level pair above. The construction is illustrated in Figure \ref{fig:constr}. \begin{figure} \centering \captionsetup{justification=centering} \input{constr_sketch.tikz} \caption{Consecutive levels of the lower bound construction} \label{fig:constr} \end{figure} Our parameters $\lambda$ and $\varphi$ also determine that the number of switches should increase by a factor $\frac{1-\varphi}{\lambda+\varphi}$ on each new level. If we can always increase the switches at this rate, then each node on the lowermost level will switch \begin{equation*} \label{eq:match2} \left( \frac{1-\varphi}{\lambda+\varphi} \right)^{\log_{\frac{1-\varphi}{\varphi}}(n)} = n^{\frac{\log\left( \frac{1-\varphi}{\lambda+\varphi} \right)}{\log\left( \frac{1-\varphi}{\varphi} \right)}} = n^{f(\lambda)}, \end{equation*} times, where the last equation holds because we are using $\varphi=\varphi^*(\lambda)$. Since there are $\widetilde{\Theta}(n)$ nodes on the lowermost level, the switches in this level already amount to a total of $\widetilde{\Theta}(n^{1+f(\lambda)})$, matching the upper bound. However, note that when $\varphi^*(\lambda)$ or $\frac{1-\varphi}{\lambda+\varphi}$ is irrational, we can only use close enough rational approximations of these values. This comes at the cost of losing a small $\epsilon$ in the exponent. \begin{theorem} \label{the:lower} Under Rule II with a wide range of $\lambda$ values, there is a graph construction and initial coloring where majority/minority processes stabilize in time $\Omega(n^{1+f(\lambda)-\epsilon})$ for any $\epsilon > 0$. \end{theorem} This level-based structure describes the general idea behind our lower bound construction. However, the main challenge of the construction is in fact designing the connection between subsequent levels. In particular, this connection has to make sure that conflicts are indeed always relayed optimally, i.e. no potential is wasted between any two levels. Recall from the proof of Lemma \ref{preservePot} that this is only possible if between any two consecutive switches of a node $v$, it is exactly a $\frac{\lambda+\varphi}{1-\varphi}$ fraction of $v$'s upper neighbors that switch. Moreover, these switching $\frac{\lambda+\varphi}{1-\varphi} \cdot \text{deg}(v)$ upper neighbors always have to be of the right color, i.e. they need to switch to the opposite of $v$'s current color in case of majority processes, and to the same color in case of minority processes. Since the upper neighbors of $v$ are in the same level, we also have to ensure that throughout the entire process, each upper neighbor switches the same number of times altogether. These conditions impose heavy restrictions on the possible ways to connect two subsequent levels. If the conditions hold for a node $v$ (i.e. the sequence of switches of $v$'s upper neighbors can be split into $\frac{\lambda+\varphi}{1-\varphi} \cdot \text{deg}(v)$-size consecutive appropriate-colored subsets, in an altogether balanced way), then we say that $v$'s upper neighbors follow a valid \textit{control sequence}. On the other hand, in order to argue about levels in general, we want each level to behave in a similar way. The easiest way to achieve this is to have a one-to-one correspondence between the nodes of different levels, and ensure that each level repeats the same sequence of steps periodically, but in a different pace. That is, we want to connect the levels in such a way that when a level exhibits a specific pattern of switches, then this allows the nodes of the next level to replicate the exact same pattern of switches, but more times. Thus the key task in our lower bound constructions is to develop a so-called \emph{control gadget}, which is essentially a bipartite graph that fulfills these two requirements: it admits a scheduling of switches such that (i) the upper neighborhood of each lower node follows a valid control sequence, and (ii) while the upper level executes a sequence $s$ times, the lower level executes the same sequence $\frac{1-\varphi}{\lambda+\varphi} \cdot s$ times. Given such a control gadget, we can connect the subsequent level pairs of our construction using this gadgets. This allows us to indeed increase the number of switches by a $\frac{1-\varphi}{\lambda+\varphi}$ factor in each new level, resulting in a total of $\widetilde{\Theta}(n^{1+f(\lambda)})$ switches as described above. However, developing a control gadget is a difficult combinatorial task in general: it depends on many factors including divisibility questions, and whether our parameters can be expressed as a fraction of small integers. A detailed discussion of control gadget design and the $\lambda$ values covered by Theorem \ref{the:lower} is available in Appendix \ref{App:B}. In particular, we present a method which allows us to develop a control gadget for every small $\lambda$ value below a threshold of approximately $0.476$ (more specifically, as long as $\frac{\lambda + \varphi}{1-\varphi} \leq \frac{3}{5}$). The same technique also provides a control gadget for some larger $\lambda$ values above the threshold, but only when the corresponding switch increase ratio $\frac{1-\varphi}{\lambda+\varphi}$ can be expressed as a fraction of relatively small integers. Furthermore, Appendix \ref{App:B} also describes a simpler solution technique to the control gadget problem; this leaves a slightly larger gap to the upper bound, but it works for any $\lambda$ without much difficulty. \newpage
{'timestamp': '2020-04-21T02:24:42', 'yymm': '2004', 'arxiv_id': '2004.09185', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09185'}
arxiv
\section{Introduction} \label{intro} Evolutionary Computing (EC) as a subfield of artificial intelligence, can be defined as a representative form of a family of algorithms inspired by the theory of biological evolution. Among the EC schemas, a number of works have been presented based on meta-heuristic algorithms like Partial Swarm Optimization (PSO), Ant Colony Optimization (ACO), Krill Herd Algorithm (KHA) \cite{Ref55,Ref56,Ref57,Ref58,Ref68,Ref70} and Black Hole Algorithm(BHA) \cite{Ref69} which can be mentioned. Ref.\cite{Ref64,Ref65,Ref66,Ref67} are including works have focused on the Artificial immune system (AIS) field which is hot research topic for those issues where security is critical. AIS has most capabilities and give us required motivation to use its methods in some complex problems. It is defined as a computational paradigm that inspired by theoretical immune based principles and techniques. Capability of pattern recognition of immune system is used to distinguish between foreign cells entering the body, known as non-self-elements, and the body own cells, known as the self-elements. This process called “self and non-self-theory”. It is noted that Immune inspired methods cannot produce the same high performance as the human immune system. Hence, a newer immunological, named the Danger Theory (DT) as 2nd generation of AIS has been proposed. The DT is based on behavior of specific immune cells called Dendritic cells (DCs). It clarifies that the immune system looks for danger producing elements and events instead of discriminating between self and non-self. So, an inspiration from the behavior of DCs caused to development of a new bio-inspired algorithm named Dendritic Cell Algorithm (DCA). The DCA was successfully applied to a wide range of applications in literature. \\ Many researchers have caught their attention to investigate behavior of DCs so as to led to a variety of DCA versions aiming at improving the standard version of the DCA \cite{Ref15,Ref16,Ref17,Ref28,Ref32}. Hence, this area is hot for research. In this paper, we have focused on building dynamism for the migration threshold of DCs and so propose a method for good sampling antigens by DCs to finally generate a novel semi-supervised classifier. Also, the problem of requirement for making antigen set in form of preordered to process Danger Signals has been solved. We followed two main goals in this paper: First one is to utilize the CSM signal to make MT variable cycle by cycle so as to provide a primary formula. Second one is to adopt a novel strategy for radius of presenting by DCs to sample multiplied antigens non-randomly. \\ The rest of the paper is organized as follows: Section 2 reviews literatures. In the next section, preliminaries about the methods which we basically worked on have been introduced. Section 4, presents our proposed system. Analyzing the effectiveness of the proposed schema has been verified in Section 5 through experiments. Last section draws a summary of this research paper and propose future works. \\ \section{Related works} In recent proceedings of research studies, using AIS methods, especially the dendritic cell algorithm (DCA), includes intrinsic capabilities so as to be a solution for anomaly detection problems \cite{Ref3,Ref15,Ref12}. Various versions of the DCA has already been presented in some works that each one has different pros and cons depending on the type of problem \cite{Ref16,Ref17,Ref19}. Some investigations show that the DCA has potential properties so as to be utilized for binary classification problems. In Ref.\cite{Ref16}, Chelly and Elouedi deeply study on summarizing the powerful characteristics of the DCA and its applications. In this work, we see some advantages: first, almost all of approaches for the DCA improvements and its limitations are evaluated and addressed well, and second, it is good to utilize as a baseline for proposed hybrid methods. The classical DCA has in excess of 10 parameters that employs many stochastic elements making it difficult to analysis. So, deterministic version of the DCA (dDCA) \cite{Ref17} is another option is formulated to help gain better insight into the underlying mechanism of the DC. The dDCA, consists of a controllable number of parameters. Main disadvantage of that is its failure on elevating deterministic performance at conditions that time slices between attacks tend to be low. On the other hand, the dDCA shouldn’t be used in networks with highly attacks. In this work, we used UNSW-NB15 dataset that is much better than KDDCup99. This benchmark dataset consists of a various range of attacks and normal traffics that rate of attacks to normal is balance. \\ Santanelli and et al in Ref.\cite{Ref15}, work on problematic issue of input signals assessment on the DCA. They optimize the probabilities of safe and danger signals using the GA. The goal is to calculate $p_{safe}$ and $p_{danger}$ values for the DCA that is their advantage. The most important drawback is that the dataset is outdated. In Ref.\cite{Ref33} which is a dissertation, authors investigate all of the key features of the DCA from two aspects of theoretical and practical for its development. In this work, a base foundation for investigating the signals calculation problem and preprocessing phase has been introduced. This work gives us a good view for generating input signals manually through dataset attributes which known as Knowledge of Experts (KoE). They also study KoE to attempt to provide new functions by analyzing features of NSL-KDD so as to find out three input signals, though stability on effectiveness of KoE is not approved. For an instance, permutation of three values of $count$, $src_{bytes}$ and $dst_{bytes}$ from KDDCup99 can be set to three input signals: safe signal (SS), PAMP signal and danger signal (DS). It can help us to inspire to provide ideas in signal assessment phase of the DCA. In our work, we have used IG method for signal generation from dataset. Our default approach to process three input signals (PAMP, SS and DS) is based on two mean or median criteria were also been analyzed. \\ A Cloud based algorithm presented for intrusion detection in Ref.\cite{Ref32} inspires of decentralized behavior of dendritic cells to implement the DCA on cloud. The goal is to make a decentralized mechanism for DC so as to model its activities completely similar to DCs activities. The important advantage of this work is that cloud environment can be very beneficial for developing DCA basis functionalities which is a challenge due to the demands of huge memory capacity. In Ref. \cite{Ref44}, author focuses on dendritic cell algorithm limitation when coping with very large datasets. She proposes a distributed version of the DCA based on MapReduced framework. In Ref.\cite{Ref75}, an efficient distributed DCA is proposed based on partitioning the DCA processes into elementary tasks, and tested with 360 million antigens. In Ref.\cite{Ref74}, the challenge of the context assessment phase is obviated by integrating the K-means algorithm to the DCA in order to map the DCA cumulative semi-mature and mature context values into two clusters. Although used dataset (KDDCup99) is very old, the proposed approach is competitive compared with other commonly used classifiers. However, its performance is not guaranteed especially when traffic is online and change rapidly overtime. \\ Ref.\cite{Ref73} is very significant because it focuses on input signal generation challenge. It utilizes fuzzy logic to map from the input space to the output space. In this work, KDDCup99 is applied for input signal generation. Selected features for each DCA input signal (input space) are as follows: count and srv count for Danger Signal, logged in, srv different host rate and dst host count for Safe Signal and serror rate, srv serror rate, same srv rate, dst host serror and dst host rerror rate for PAMP. This article gives us a good instance of how to get input signals from originally dataset. In work \cite{Ref46}, they work on optimizing weight function of the DCA that is a problem. They use genetic algorithm to generate optimized set of weights. For knowing how the DCA works, Ref.\cite{Ref17} as a prerequisite can be very beneficial. Regarding literature, neither of works introduce ideas to do preordering of antigen set, or to work on non-random data sampling. So, we addressed it well in our work. In the proposed IDS, dataset as antigen set is firstly divided into some sections known as the cell tissues based on two nominal attributes of protocol-service. In each cell tissue, each DC presents antigens (network traffic records) which have overlapping with them into its coverage. Each DC may cover one or more antigens and vice versa. \\ \section{Preliminaries} \subsection{\label{2.1}Dendritic cell algorithm} The Danger Theory (DT) as the latest immunological theory firstly proposed by Matzinger in 1994 \cite{Ref15}. The DT is an inspiration from the behavior of special immune cells inside body called the dendritic cells (DCs). Mediators of various immune responses, they are actually rapid messengers between innate and adaptive IS. Similar to NSA, the DT is also capable of discriminating between self-and non-self, but the main difference is that it looks for danger-producing elements and circumstances by assessing signals reflected from healthy cell tissues (safe) or injured ones. (Fig.\ref{Fig.1} ) Thus, the DT declares distinguishing antigens as “safe” and “non-safe” by IS while also as “self” and “non-self”. \\ \begin{figure}[h] \centering \includegraphics[scale=0.5]{DT} \caption{\label{Fig.1} Dendritic cells migration procedure} \end{figure} \\ The DCA is an abstract model of behavior of DCs. It is a kind of AIS that is based on the DT concept. Its process includes four phases: preprocessing, detection, context assessment, classification (Fig.\ref{Fig.2}). Alg.4 at appendix also shows its original pseudo code. But, how does it work? In body organism, each cell informs its safety status to nearest dendritic cells by signaling. They are absolutely like guardians that their task is to oversee tissues that means checkup \footnote{In computational perspective, checking up is accomplished by four functions: $Get_{antigens}$, $Get_{signals}$, $Calculate_{inter}$, $Update_{cumul}$}, not surgery. When an antigen ($Ag_{i}$) breaches to cell tissues by skin, it probably harms them that its outcome leads to destruction. Injured and dead cells send danger/PAMP signals to immature DCs for assessment. This process called “signal assessment” is one of serious phases of the DCA. Signals sent from healthy/injured cells (considered as suspicious antigens) are received by some of DCs ({$DC_{j}={DC_{1},DC_{2},...,DC_{m}}$}). On the other hand, $n$ antigens with signals from all categories (SS, DS, and PAMP \footnote{Respectively safe, danger and PAMP signals}) must be presented by population of $m$ dendritic cells \footnote{That is a many to many relations} (distributed data sampling phase). The process of calculating input signals has been described in Ref. \cite{Ref16} in details. Calculating the cumulative output signals is also accomplished by presenter DCs. When pervaded $Ag_{i}$ is sampled by a subset of DCs, they are stimulated into rest which have no chance for monitoring it. These stimulations lead to the assignment of cell-contexts to DCs. At the end, immature $DC_{j}$ will have two cumulative values include semi-mature and mature in addition to cumulative CSM value that cause $DC_{j}$ to be able to stop monitoring and migrate if CSM exceeds MT; Otherwise, immature $DC_{j}$ continues sampling antigens. Migrated DCs go to activate lymphocytes so that captured antigens are operated so better than past. \\ \begin{figure}[h] \centering \includegraphics[scale=0.3]{DCAProcess} \caption{\label{Fig.2} The DCA process, taken by Ref.\cite{Ref16}} \end{figure} \\ According to Fig.\ref{Fig.2}, the preprocessing phase involves two primary steps: At first, the most important attributes from the gold data (train set) are selected and then, each attribute is mapped to an appropriate signal category. An immunological definition for input signals has been stated by Ref.\cite{Ref16}. Two current methods to assess input signals are feature selection and knowledge of experts (KoE). Both of them have key challenges. Dimensional reduction deals with selecting the best optimum subset among $2^{n}$ possible subsets of features that is an NP-hard problem, and success of the second technique also relies on the traffic flow and how to be analyzed by information security scientists so as to find most significant features to map to signals categorization. So, we can say that success of the DCA has a direct relationship with obtained signals, and this is an open problem. The weighted sum equation illustrates how the input signals are processed. It is defined as follows: (Taken by Ref.\cite{Ref16}): \\ \begin{equation}\label{m1} \footnotesize\ C = \frac{[(W_{PAMP}\times\sum_{i}{PAMP_{i}})+(W_{SS}\times\sum_{i}{SS_{i}})+(W_{DS}\times\sum_{i}{DS_{i}})]}{(W_{PAMP}+W_{SS}+W_{DS})}\times\frac{1+Inf}{2} \end{equation} \\ Where, $C_{|CSM,smDC,mDC|}$ , Inf is the inflammation signal which is assumed “1”, and weights are also gotten by an expert. Actually, each DC samples $i$ antigens. Main weights matrix supposed by main work which has been made by Greensmith. Ref.\cite{Ref28} are used in research. It is defined as below: \\ \begin{equation}\label{mtrx} \footnotesize\ Weight\,\,coefficient\,\,matrix\,\,(WCM) =f \begin{vmatrix} Signals & PAMP& SS & DS \\ CSM & 2 & 1 & 2 \\ smDC & 0 & 0 & 2 \\ mDC & 2 & 1 & -2 \end{vmatrix} \end{equation} \\ The DC cumulative output signals (CSM, smDC, mDC) perform two roles: first, to decide what is an antigen type, and to suppress sampling the data. Furthermore, the MCAV is calculated by dividing the number of DCs in mature context that $Ag_{i}$ has caused migrating them, by the total number of presented DCs have sampled to $Ag_{i}$ when no immature DC didn’t remain in population. \\ \begin{equation}\label{MCV} \footnotesize\ MCAV=\frac{No.\,\,of\,\,mature\,\,DCs}{Total\,\,No.\,\,of\,\,DCs} \end{equation} \\ The degree of anomaly of a given antigen is assessed by the MCAV. Antigens MCAV values are compared with a determined anomalous threshold (at). It is defined as below: \\ \begin{equation}\label{at} \footnotesize\ at=\frac{No.\,\,of\,\,anomalious\,\,data\,\,items\,\,(an)}{Total\,\,No.\,\,of\,\,data\,\,items (tn)} \end{equation} \\ Those antigens have MCAV values greater than this threshold, and are classified into anomalous category while the others will be normal. The determination of this can be obtained by calculating reflection of the potential danger rate in distribution of incoming data between normal class and abnormal one. Besides, the MCAV values are discrete; 0 or 1, so it creates problem in our hybridization idea. In next sections, we have observed that some of these above equations do not have minimum proficiency to be used to contiguous problems like “network anomaly detection”. \\ \section{Proposed system} In order to propose a semi-supervised classifier based on the DT concept, we improved the DCA original version proposed in Ref.\cite{Ref16}. Although, it is not tailored to ID problem by default, it does not have some complexities of “process strategy” against the most of meta-heuristic algorithms like ACO, BHA, PSO, GA and etc. All of them solve ID problem by a centralized approach \cite{Ref59,Ref60,Ref61,Ref62,Ref63,Ref76,Ref77}; to search for finding the best optimum centroids among candidate solutions. Tests have accomplished in Sec.5 confirm this fact. The immune inspired DCA’s decentralized processing method in the binary classification is the reason why we adopted it as a defense shield and a good option for our purpose. To identify attacks at least with a tolerable false positive error is promising. Calculating the DS has been done differently from two other signals in Ref.\cite{Ref16}. It needs the incoming data be pre-ordered on class column while entails to a challenge. Thus, the danger signal processing is very important since it has a direct relevancy to pass false negative errors. When greater number of antigens are incorrectly recognized to normality, the possibility of FNR will be higher. In our mind, both of normal and abnormal samples of the train set (self) in addition of new labeled antigens which can be easily used to address this problem if we disregard the analysis of these innate features from traffic flow. \\ \paragraph{\textbf{An idea }} We used self-data in order to obviate challenge of being preordered. At first, minimum Euclidean distances between each antigen and all normal and abnormal selves are calculated separately. Then, antigen will be labeled to abnormal and added it to self-abnormal set if its minimum distance from the self-normal set is more than its minimum distance from the self-abnormal (Alg.2), and vice versa. Also, as stated in Sec\ref{2.1}, calculated CSM signal can be a good measure to check migration terms of DCs since it is computed through weighted sum equation (Eq.\ref{m1}). Thus, the MT value must be predetermined in each run cycle of algorithm. But, it has usually a constant value in all phases of the DCA runs. So, some questions may raise as follows: \\ \paragraph{\textbf{Question }} Could the MT be merely dependent on the subset of attributes mapped to the input signals and be dynamically provided meantime each running cycle of the DCA? If so, will it impress classification performance? \\ \paragraph{\textbf{An idea }} Flexibility for determining the MT. In Alg.2 (Fig.5 at appendix), a constant MT value which is determined by user in range of [0, 1] for all run cycles, is requisite for migration of DCs. It will take place only if the CSM values exceed MT. As regards, the CSM calculation relies on input signals based on weight coefficients and also each dendritic cell has a different CSM value, it seems that the MT mostly takes effect from processed input signals which are variable cell by cell and cycle by cycle. Therefore, necessity of the MT‘s flexibility is required. So, Eq.\ref{mt} is proposed to compute the MT value dynamically. Its proof for practicality is performed in experiment section. It is defined as below: \\ \begin{equation}\label{mt} \footnotesize\ mt=[(F(P_{PAMP}) \times 2)+(F(P_{SS}))+(F(P_{DS}) \times 2)] \end{equation} \\ Where, $P_{PAMP} , P_{SS} , P_{DS}$ are probabilities of three input signals for immature DCs in real range of [0, 1]. Also, either mean or median criteria can be taken for F function. Coefficients are respectively 2, 1 and 2 refer to WCM (Eq.2) \\ \paragraph{\textbf{An idea }} Procedure of sampling multiplied antigens vector \footnote{Vector are created from network traffic samples}. According to the Sec\ref{2.1} , DCs settle on positions of traffic samples when they want to inspect. Though, no strategy or idea has been adopted on the $Get_{Antigen()}$ function but randomly sampling entails the DCA to provide undesirable results in several cycles in each time. This leads to uncertainty. Whereas it must be accomplished by biological behaviors of DCs in tissues, we proposed a novel strategy which exactly acts based on its immunological functionalities of dendritic cells as below. Its proof for practicality is performed in the experiment section. It is defined as below, Calculating radiuses of coverage: \\ \begin{eqnarray}\label{DCEq} \begin{gathered} \footnotesize\ Present_{radiusDC} = [\frac{Size_{of}Vector(j)}{max(Size_{of}Vector(j))}] \times F(dist(DC_{j},i)) \\ Size_{of}Vector(j) = [Rand(minCloneRange, maxCloneRange) \times \\ Size_{of}tissues_{j}] + Size_{of}tissues_{j} \end{gathered} \end{eqnarray} \\ Where, $Size_{of}tissues_{j}$ is number of antigens into ${j}^{th}$ tissue; $j \in [1,number\,of\,ce\\ll,tissues]$, i is ${i}^{th}$ antigen per n exist into ${j}^{th}$ tissue, F can be either mean or median, $Size_{of}Vector(j)$ is also $Clone_{vector}$ rate as to ${j}^{th}$ tissue includes n antigens to specify $Antigen_{vector}$. Clone indicator really means maximum length that vector can possess. Fig.\ref{Fig.3} shows how each antigen is multiplied. Eq.\ref{DCEq} gives us a value that we can consider it as hyper shape radius which creates area about DC. So, sampling antigens by one DC depends on cell coverage. The determination of radius of coverage depends on two things: (1) measuring Euclidian distance between inspector DC to other pervaded antigens, (2) The rate of multiplication for that inspected antigen. Actually, DC must sample antigens which have overlapping with them into its coverage. Fig.\ref{Fig.3} clearly illustrates our strategy for sampling. \begin{figure}[h] \centering \includegraphics[scale=0.35]{DCsampling} \caption{\label{Fig.3} An illustration for non-randomly sampling antigens by DC on ${i}^{th}$ tissue, DC locates on $Ag_{6}$’s position and begins to check up coverage by sampling} \end{figure} \\ \paragraph{\textbf{An example }} Assume that we have 10 tissues and the second one includes three types of antigens. Min and max ranges of antigen clone are also between 0.15 and 0.35. So, $Clone_{vector}$ is calculated as below: \begin{eqnarray} \begin{gathered} \footnotesize\ Size_{of}tissue(2) \leftarrow 3, \nonumber \\ Clone_{vector}(j=2) \leftarrow [Rand(0.15, 0.35) \times 3] + 3, \nonumber \\ \underrightarrow{yields}\ \ [\underbrace{Rand(0.15, 0.35)}_{0.25} \times 3] + 3 \rightarrow 3.75 \approx 4; \ \ \ 3 \le Clone_{vector}(2) \le 6 \nonumber \end{gathered} \end{eqnarray} Now, Distributing $Size_{of}Vector(i)$ into antigens: \begin{eqnarray} \begin{gathered} \footnotesize\ IF\, \left\{\begin{array}{lr} dist(Ag_{1}\,to\,Ag_{2}) \leftarrow 0.17 \\ dist(Ag_{1}\,to\,Ag_{3}) \leftarrow 0.36 \\ dist(Ag_{2}\,to\,Ag_{3}) \leftarrow 0.59 \end{array}\right. \Rightarrow \left\{\begin{array}{lr} Present_{radius}DC1 = [\frac{4}{6}] \times \overbrace{mean}^{F}(0.17, 0.36) \rightarrow 0.1767 \\ Present_{radius}DC2 = [\frac{4}{6}] \times mean(0.17, 0.59) \rightarrow 0.2534 \\ Present_{radius}DC3 = [\frac{4}{6}] \times mean(0.36, 0.59) \rightarrow 0.6334] \end{array}\right. \nonumber \\ \underrightarrow{yields} \ \left\{\begin{array}{lr} \{Ag_{2}. Ag_{3}. Ag_{3}. Ag_{3}\}\,are\,sampled\,by\,DC_{1} \\ \{Ag_{1}. Ag_{3}. Ag_{3}. Ag_{3}\}\,are\,sampled\,by\,DC_{2} \\ \{Ag_{1}. Ag_{1}. Ag_{1}. Ag_{2}\} \,are\,sampled\,by\,DC_{3} \end{array} \right.\nonumber\\ \underrightarrow{yields} \ \left\{\begin{array}{lr} r_{Ag2} \leftarrow \frac{(0.1767-0.17)}{[(0.1767-0.17)+(0.1767-0.36)]} \times 0.17 \rightarrow 0.006, \\ r_{Ag1} \leftarrow \frac{(0.2534-0.17)}{[(0.2534-0.17)+(0.2534-0.59)]} \times 0.17 \rightarrow 0.0337, \\ r_{Ag1} \leftarrow \frac{(0.6334-0.36)}{[(0.6334-0.36)+(0.6334-0.59)]} \times 0.36 \rightarrow 0.3107, \end{array} \right. \nonumber\\ ; \left\{\begin{array}{lr} r_{Ag3} \leftarrow \frac{(0.1767-0.36)}{[(0.1767-0.17)+(0.1767-0.36)]} \times 0.36 \rightarrow 0.347 \\ r_{Ag3} \leftarrow \frac{(0.2534-0.59)}{[(0.2534-0.17)+(0.2534-0.59)]} \times 0.59 \rightarrow 0.472 \\ r_{Ag2} \leftarrow \frac{(0.6334-0.59)}{[(0.6334-0.36)+(0.6334-0.59)]} \times 0.59 \rightarrow 0.081 \end{array} \right. \nonumber\\ \end{gathered} \end{eqnarray} \\ According to Alg1. line of 4, antigen set is divided into cell tissues. Two nominal attributes of protocol and service of UNSW-NB15 dataset are utilized for this purpose. They have been highlighted on Tab.7 at appendix. \\ \begin{algorithm}[H] \caption{The proposed pseudo code for data sampling } \algsetup{linenosize=\tiny} \scriptsize\begin{algorithmic}[1] \STATE\textbf{Input:} S=$Antigen_{Set}$ . Mn=minAgCloneSz . Mx=maxAgCloneSz . Sg=Signal . Pr=$Probabilities_{of}InputSignalValues$ . MT=$Migration_{Threshold}$ \STATE\textbf{Output:} E=$Set_{of}MigratedCells$ . U=$Set_{of}UnmigratedCells$ . C=$Cell_{Context}$ {\color{blue}\STATE $/*$ Detection Phase $*/$} \STATE $tissues$=$divide$ $S$ $to$ $cell$ $tissues$ $based$ $on$ $Protocol-Service$ $attributes$ \FOR {\textbf{each} tissues} \STATE $Size_{of}Vector(i)=[RANDOM(Mn,Mx) \times Size_{of}tissues(i)]+Size_{of}tissues(i)$ \FOR {\textbf{each} selected DC into tissues(i)} \STATE $-$ $Get$ $the$ $Antigen:$ $Distance$ $Antigens$ $to$ $DC$ $\gets$ $Determine$ $Euclidian$ $distance$ $DC$ $from$ $antigens$ $into$ $tissue(i).$ \STATE $-$ $Distributing$ $Size_{of}Vector(i)$ $into$ $antigen$ $is$ $toward$ $DC$ $coverage,$ $its$ $clone$ $rate$ $will$ $be$ $higher$ $and$ $vice$ $versa.$ \STATE $R \gets Calculate$ $DC$ $radiuses$ $utilizing$ $\textbf{Eq.6}$ {\color{blue}\STATE $/*$ Preprocessing antigens by DC $*/$} \FOR {\textbf{each} antigens of tissues(i)} {\color{blue}\STATE $/*$ Overlapping between DC $\&$ Ag $*/$} \IF {$(R+r_Ag(i)) > Dist(DC from Ag(i))$} {\color{blue}\STATE $/*$ Signal Assessment $*/$} \STATE $-$ $Get$ $the$ $Sg$ \STATE $-$ $Calculate$ $interim$ $output$ $signals$ $(\textbf{Eq.1})$ \STATE $-$ $Update$ $the$ $cumulative$ $output$ $signals$ $(\textbf{Eq.1})$ {\color{blue}\STATE $/*$ requisite for migration $*/$} \IF {$cumulative$ $CSM$ $>$ $MT$} \STATE $-$ $Remove$ $the$ $DC$ $population$ \STATE $-$ $Assign$ $the$ $C$ $to$ $DC$ {\color{blue}\STATE $/*$ Context assessment phase $*/$} \IF {$cumulative Semi \leq cumulative Mat$} \IF{$Cell_{Context} \geq 0.50$} \STATE $-$ $Add$ $DC$ $to$ $E.Mat_{cells}$ \ENDIF \ELSE \IF {$Cell_{Context} < 0.50$} \STATE $-$ $Add$ $DC$ $to$ $E.Semi_{cells}$ \ENDIF \ENDIF \STATE $-$ $Termination$ $the$ $DC$ $and$ $Add$ $a$ $naive$ $DC$ $to$ $the$ $population$ \ELSE \STATE $-$ $Add$ $DC$ $to$ $U$ $to$ $sample$ $again$ \ENDIF \STATE $-$ $DC$ $back$ $to$ $population$ \ENDIF \ENDFOR \ENDFOR \ENDFOR \end{algorithmic} \end{algorithm} \begin{algorithm}[H] \caption{The proposed pseudocode to make antigen set preordered} \algsetup{linenosize=\tiny} \scriptsize \begin{algorithmic}[1] \STATE\textbf{INPUT:} S=$Antigen_{Set}$ . SN=$Self_{Normal}$ . SA=$Self_{Abnormal}$ \STATE\textbf{OUTPUT:} $O=PreOrdered_{Antigen_{Set}}$ \FORALL {$Ag_{i} \in S$} \STATE $Candidate_{distN}=min_{Euclidian\,distance}(Ag_{i}\,from\,SN)$ \STATE $Candidate_{distA}=min_{Euclidian\,distance}(Ag_{i}\,from\,SA)$ \IF {$Candidate_{distN} > Candidate_{distA}$} \STATE $Ag_{i}LABLE \leftarrow Abnormal$ \STATE $Add\,Ag_{i}\,to\,SA$ \ELSE \STATE $Ag_{i}LABLE \leftarrow Normal$ \STATE $Add\,Ag_{i}\,to\,SN$ \ENDIF \ENDFOR \STATE $O=SORT\,\,'S'\,\,based\,on\,Class labels$ \STATE $RETURN\,O$ \end{algorithmic} \end{algorithm} \ \\ According to Alg.2, unlabeled antigens with labeled ones are used to make antigen set as preordered. Therefore, two candidate distance values are calculated based on Euclidian distance between $Ag_{i}$ from self-sets. We need this process to generate danger signal by Information Gain (IG) method (Line 5 from Alg.3). In tests, we adopted IG to compute input signals. Two SS and PAMP signals are obtained in the same way, but the DS has a difference strategy. Ref.\cite{Ref16} has been precisely described how to compute these three input signal values through IG. We subsequently proposed our improved DCA. \\ \\ \begin{algorithm}[H] \caption{Pseudocode of the proposed DCA} \algsetup{linenosize=\tiny} \scriptsize \begin{algorithmic}[1] \STATE\textbf{Input:} S=$Antigen_{Set}$ . T=$Train_{Set}$ . $Mn=minAgCloneSz$ . $Mx=maxAgCloneSz$ . $Weight_{Matrix}$ . $Sg=Signal$ . Pr=$Probabilities_{of}InputSignalValues$ . MT=$Migration_{Threshold}$ \STATE\textbf{Output:} E=$Set_{of}MigratedCells$ . MCAV {\color{blue}\STATE $/*$ Preprocessing $*/$} \STATE $-$ $Sort$ $S$ $to$ $make$ $it$ $preordered$ \textbf{(Alg.2)} \STATE $-$ $Select$ $best$ $method$ $to$ $compute$ $input$ $signals.$ $i.e.$ $the$ $information$ $Gain$ $(IG)$ \STATE $-$ $Compute$ $MT$ $adopting$ $Pr$ $and$ $Weight$ $Coefitients$ $(\textbf{Eq.2}$ $and$ $\textbf{Eq.5})$ {\color{blue}\STATE $/*$ Detection Phase $*/$} \WHILE {U is not empty} \STATE $[E, U, C] \leftarrow Sampling\,Antigens(S, Mn, Mx, Sg, Pr, MT)\,\textbf{Alg.1}$ {\color{blue}\STATE $/*$ Classification phase $*/$} \FORALL {$E.Semi_{cells}$} \STATE $Semi_{DCs}(Ag_{i}) \leftarrow \frac{Semi_{cells}(Ag_{i})-min(Semi_{cells})}{max(Semi_{cells})-min(Semi_{cells})}$ \ENDFOR \FORALL {$E.Mat_{cells}$} \STATE $Mat_{DCs}(Ag_{i}) \leftarrow \frac{Mat_{cells}(Ag_{i})-min(Mat_{cells})}{max(Mat_{cells})-min(Mat_{cells})}$ \ENDFOR \FORALL {$member of E$} \IF {$C(i) \geq 0.50$} \STATE $MCAV(i) \leftarrow mean(\frac{Mat_{DCs}(i)}{Mat_{DCs}(i)+Semi_{DCs}(i)},\frac{E(i).Present}{E(i).Clone})$ \ELSE \STATE $MCAV(i) \leftarrow mean(\frac{Semi_{DCs}(i)}{Mat_{DCs}(i)+Semi_{DCs}(i)},\frac{E(i).Clone-E(i).Present}{E(i).Clone})$ \ENDIF \ENDFOR \ENDWHILE \end{algorithmic} \end{algorithm} Regarding Alg.3, there are seven input and two output parameters. In each iteration cycle of the algorithm, we have two calls related with algorithms 1 and 2 on lines 4 and 9 that algorithm 1 (sampling antigens function) takes a number of input parameters. Among these parameters, the MT and the input signal probabilities are calculated as variables in each run cycle and have some dynamic value. We also made changes to the MCAV calculation that are observable. In the case of parameter setting, MT, minAgCloneSz and maxAgCloneSz parameters are single values where the MT value is dynamically changed according to the size of the CSM signal in each run cycle of the whole algorithm. A significant point is clone size of antigens which we can determine a range for them. If this range is [a,b] that a is minAgCloneSz and b is maxAgCloneSz, this means that a hypothetical antigen’s clone rate can be random variable between a and b. In addition, the parameter of Pr determines the probability of input signals in the range [0,1] as a percentage in Algorithm 1. At the output of the Sampling antigens function, the three parameters E, U, C respectively specify the values of the migrated, non-migrated cells and the context values for the cells. Algorithm 3 continues until the size of the set U is zero and all cells migrate, so the number of execution cycles depends on the size of this parameter. Fig.4 illustrates the general procedure of the proposed method. \\ \begin{center} \footnotesize\ \includegraphics[scale=0.47]{Architecture} \\ \textbf{Fig.4} General procedure of the proposed method \\ \end{center} \section{Experimental and Results} In order to evaluate our proposed defensive shield, in this section, the required simulation was accomplished with traffic samples uniformly random derived from a reliable network intrusion dataset, the UNSW-NB15 dataset provided by University of New South Wels \cite{Ref31}. The involved attacks of the UNSW-NB15 data set were categorized into nine types as following: Fuzzers, Analysis, Backdoor, DoS, Exploit, Generic, Reconnaissance, Shellcode, and Worm. Table.7 at appendix shows its attributes in details. Also, the involved features of this dataset are classified into six groups as follows: flow, basic, time, additional generated and labelled features. And in total, it has 49 attributes. It is one of the newest IDS datasets which has been recommended to use in ID problems instead of the former datasets like KDDCup99. Our proposed technique is simulated with a classic computer Intel® Core ™ i5-3230M CPU @ 2.60Hz, 4.00 GB Ram equipped with the MATAB R2018b environment. \subsection{\label{4.1} Evaluation criteria} Following performance measures were utilized for evaluating the proposed method: The Detection rate (DR), False Positive Rate (FPR), False Negative Rate (FNR), and Accuracy Rate (ACC) and complements of them in addition to Correlation Coefficient (cc) and CID which relatively appears unfamiliar in this case \cite{Ref36}. \begin{eqnarray} \footnotesize \begin{gathered} DR=\frac{No\,of\,attacks\,that\,are\,correctly\,classified\,as\,attack}{Total\,No.\,of\,attacks\,in\,the\,test\,dataset} \times 100 \\ FPR=\frac{No.\,of\,normal\,that\,are\,uncorrectly\,classified\,as\,attack}{Total\,No.\,of\,normal\,in\,the\,test\,dataset} \times 100\\ FNR=\frac{No.\,of\,anomaly\,that\,are\,uncorrectly\,classified\,as\,normal}{Total\,No.\,of\,anomaly\,in\,the\,test\,dataset} \times 100\\ ACC=\frac{No.\,of\,correctly\,classified\,as\,samples}{Total\,No.\,of\,samples\,in\,the\,test\,dataset} \times 100\\ cc=\frac{(TP\times TN)-(FP \times FN)}{\sqrt{(TP+FN)\times (TP+FP)\times (TN+FP)\times(TN+FN)}} \\ \end{gathered} \end{eqnarray} \\Where, $cc \in [-1, 1]$. The cc value closer to -1 indicates that the predictive rate for the classification performance is inconsistent with reality. According to the information theory-based equations given on Ref.\cite{Ref36}, Simplification of CID depends on three NPV \footnote{Negative predictive value, $P(\lnot I|\lnot A)$ is the chance that there is no intrusion, $\lnot I$, when an IDS does not output an alarm, $\lnot A$} , PPV \footnote{Positive predictive value, $P(I|A)$ is the chance that an intrusion, $I$ is present when an IDS output an alarm $A$ } and Base (B \footnote{Base rate, $P(I)$ is the probability that there is an intrusion in the observed audit data, $B$ rate is consider $10^{-5}$ by default}) rates. \\ \begin{eqnarray} \footnotesize \begin{gathered} PPV \leftarrow P(I|A)=\frac{P(I, A)}{P(A)}+\frac{P(I)P(A|I)}{P(I)P(A|I)+P(\lnot I)P(A|\lnot I)} \\ NPV \leftarrow P(\lnot I|\lnot A)=\frac{(1-B)(1-\alpha)}{(1-B)(1-\alpha)+B\beta}\\ \end{gathered} \end{eqnarray} Where, I and A are respectively intrusion and alarm, $\alpha , \beta$ are FP and FN. By replacing quantities to these relations, we simplified them as bellows to be utilizable: \begin{center} \begin{eqnarray} \footnotesize \begin{gathered} PPV=\frac{B. TP}{B. TP+\bar{B}. FP},\ \ \ NPV=\frac{(1-B).(1-FP)}{(1-B)(1-FP)+B. FN}\\ \\ C_{ID}=-B(1-\beta)log(PPV)-B(1-\beta)log(1-NPV)-\\(1-B)(1-\alpha)log(NPV)-(1-B)\alpha log(1-PPV) \\ \end{gathered} \end{eqnarray} \end{center}\ \\But, CID was still able to be simplified more: \begin{center} \begin{eqnarray}\label{Eq13} \footnotesize \begin{gathered} C_{ID}=-B(1-FN)log(\frac{B. TP}{B. TP+\bar{B}. FP})-\\ B(1-FN)log(1-\frac{(1-B).(1-FP)}{(1-B)(1-FP)+B. FN})-\\(1-B)(1-FP)log(\frac{(1-B).(1-FP)}{(1-B).(1-FP)+B.FN})-\\(1-B)FPlog(1-\frac{B. TP}{B. TP+\bar{B}. FP}) \end{gathered} \end{eqnarray} \end{center} \paragraph{\textbf{Preparation of dataset}} We extracted subsets with sizes of 2110 and 20000 network traffic records from UNSW-NB15 respectively for test and train phases in our experiments. In order that traffic samples would be selected uniformly random, we used the MATLAB environment. Moreover, the min-max normalization technique was applied due to the nominal features which can be turned into the numerical ones and normalized in range of [0,1]. Besides, we embedded a number of unseen attacks (4.075 percentage means 86 records) into test subset so as to try unseen detection rates in our proposed system.\\ \subsection{\label{4.2} Simulating the behavior of DCs} This part mainly studies on improvement of the standard DCA as a new semi supervised method in ID problem adopting the proposed ideas. In previous section, it is mentioned that meta-heuristic techniques aren’t appropriate to be used in binary classification of anomalous traffic due to their detection strategy which is centroid based. As real traffic samples often make entangled clusters with a high density in problem n-dimensional space causes the binary classification is impossible. So, incoming data can be divided into multiple normal and abnormal clusters for doing non-binary classification. In most cases, non-linear methods cannot ever do this task effectively unlike claim posed in Ref.\cite{Ref34}. According to performed tests in this section, this claim will not be true in case of “network anomaly detection”. Hence, utilizing the AIS distributed methods can be very beneficial. In continue, yields have gotten by comparisons indicate this fact. Following test stages show improvement procedure of our proposed algorithm to make this defensive shield against intrusion. \\ \begin{center} \footnotesize\textbf{Table.1} Allocate input parameters of the standard DCA (Fig.8 at appendix), a used-defined MT and random sampling in 8 times of run cycles \footnotesize\renewcommand{\arraystretch}{0.85} \begin{longtable}{|c|c|ccccc|} \hline {\textbf{No.}}&{\textbf{Selected features}}&{\textbf{mt}}&{\textbf{at}}&{\textbf{runtime (s)}}&\rotatebox{90}{\textbf{minAgClone}}&\rotatebox{90}{\textbf{maxAgClone}}\\\hline 1&All&50&50&26.4219&5&10\\ 2&All&40&40&26.4219&5&15\\ 3&All&40&50&17.143&5&25\\\hline 4&Best Features: 8.9.30.33.41.42 by ref\cite{Ref31}&50&50&15.8608&5&10\\ 5&''&35&25&15.3479&10&40\\\hline 6&Middle ranked features:&50&50&26.7069&5&10\\ &4-6.10-11.15.18-26.31-32.40 by ref\cite{Ref31}&&&&&\\ 7&''&35&35&16.1472&10&40\\\hline 8&Achieved by CFA method (ref\cite{Ref37})&40&40&19.0889&3&10\\ &1-6.8-11.14.18-24.30.32.33.41.42&&&&&\\\hline \end{longtable} \footnotesize\textbf{Table.2} Perf. of the standard DCA (Fig.8 at appendix) in 8 times of run cycles\\ \begin{longtable}{|c|ccccccc|} \hline &&&&&misClassification&Correct&Correct\\ Run.&DR&FPR&FNR&ACC&rate&prediction&prediction\\ &&&&&&normal&attack\\\hline 1&51.4&46.5&48.6&52.0&48.0&33.4&70.8\\ 2&48.2&34.8&51.8&53.5&46.5&36.4&75.2\\ 3&46.3&33.9&53.7&52.5&47.5&35.9&75.0\\ 4&51.0&34.1&49.0&55.6&44.4&38.0&76.7\\ 5&39.4&24.5&60.6&50.7&49.3&36.2&77.9\\ 6&54.3&42.3&45.7&55.4&44.6&36.5&73.9\\ 7&45.9&27.9&54.1&54.1&45.9&37.7&78.3\\ \textbf{8}&\textbf{62.6}&\textbf{44.5}&\textbf{37.4}&\textbf{60.4}&\textbf{39.6}&\textbf{40.3}&\textbf{75.5}\\ \hline \end{longtable} \end{center} According to Alg.3 (line of 6), we utilized Eq.5 for computing variable MT by 20 running cycles. So, the best configuration of input parameters of Alg.3 is obtained as follows:” Mean” for F in Eq.5 to compute MT, features of ”1-6, 8-11, 14, 18-24, 30, 32-33, 41-42” for selected optimum features by utilizing CFA, 50 for 'at' parameter, [5, 15] for range of antigen clone sizes. Results of running Alg.3 through this configuration is within Tab.8. In general, we tested four approaches of the proposed DCA have been specified by four colors. (Fig.7) \\ \ \\ \begin{center} \footnotesize\textbf{TABLE 3.} Yields for the proposed DC algorithm \begin{longtable}{p{0.7cm}|p{0.5cm}p{0.5cm}p{0.5cm}p{0.5cm}p{0.5cm}p{0.5cm}p{0.5cm}p{0.5cm}p{0.5cm}p{0.5cm}p{0.5cm}p{0.5cm}p{0.5cm}p{0.5cm}} \hline \rotatebox[origin=c]{270}{\textbf{Meth. (as Color)}}&\rotatebox[origin=c]{270}{\textbf{DR}}&\rotatebox[origin=c]{270}{\textbf{FPR}}&\rotatebox[origin=c]{270}{\textbf{FNR}}&\rotatebox[origin=c]{270}{\textbf{TP}}&\rotatebox[origin=c]{270}{\textbf{FP}}&\rotatebox[origin=c]{270}{\textbf{FN}}&\rotatebox[origin=c]{270}{\textbf{Accuracy}}&\rotatebox[origin=c]{270}{\textbf{Error}}&\rotatebox[origin=c]{270}{\textbf{F-measure}}&\rotatebox[origin=c]{270}{\textbf{Precision rate}}&\rotatebox[origin=c]{270}{\textbf{Attack corrected prediction rate}}&\rotatebox[origin=c]{270}{\textbf{Normal corrected preiction rate}}&\rotatebox[origin=c]{270}{\textbf{Attack in corrected prediction rate }}&\rotatebox[origin=c]{270}{\textbf{Normal in corrected prediction rate}}\\\hline Green&95.0&56.4&5.0&65.3&17.6&3.4&79.0&21.0&85.74&78.77&78.7&80.0&21.3&20.0\\ Blue&\textbf{86.2}&\textbf{20.3}&\textbf{13.8}&\textbf{59.2}&\textbf{6.4}&\textbf{9.6}&\textbf{84.2}&\textbf{15.8}&\textbf{88.17}&\textbf{90.24}&\textbf{90.3}&\textbf{72.5}&\textbf{9.7}&\textbf{27.6}\\ Red&65.7&37.4&34.3&45.14&25.70&10.72&64.7&35.3&64.70&63.72&45.4&79.4&54.6&20.6\\ Violet&94.5&57.0&5.5&64.9&17.8&3.8&78.4&21.6&85.74&78.48&78.5&78.0&21.5&22.0\\ Light Blue&\textbf{95.5}&\textbf{55.2}&\textbf{4.5}&\textbf{65.6}&\textbf{17.3}&\textbf{3.1}&\textbf{79.7}&\textbf{20.3}&\textbf{84.54}&\textbf{79.13}&\textbf{79.2}&\textbf{82.0}&\textbf{20.8}&\textbf{18.0}\\ Orange&62.6&44.5&37.4&43.0&13.9&25.7&60.4&39.6&68.47&75.57&75.5&40.3&24.5&59.7\\ \hline \end{longtable} \footnotesize\textbf{TABLE 4.} Yields for the proposed DCA (Alg.3) by enhancing size of the AG set ten times \footnotesize\begin{longtable}{p{0.8cm}p{0.7cm}|p{1.2cm}p{0.6cm}p{0.6cm}p{0.6cm}p{1.2cm}p{0.6cm}p{0.6cm}p{1.3cm}p{1.3cm}} \hline &\textbf{Test Size}&\textbf{Runtime (S)}&\textbf{Dr}&\textbf{FP}&\textbf{FN}&\textbf{No. of false negative records}&\textbf{ACC}&\textbf{ERR}&\textbf{Total rate of unseen attacks (TP)}&\textbf{Non-detected unseen attacks (FN)}\\\hline Light blue&20000&41.007&94.7&16.6&5.3&77&79.8&20.2&98.76&37 records\\ Curve&2110&28.368&94.5&57.0&5.5&86&78.4&21.6&79.07&18 records\\ \hline \end{longtable} \end{center} At first, we simulated the standard DCA (Fig.5), and then tested it eight times under UNSW-NB15 dataset with 43 attributes on MATLAB environment. Details can be found on Tab.6 at appendix. In running cycles, the effectiveness of dimensional reduction on final performance was also analyzed. Although, it is tried to modify some of weight coefficients in WCM (Eq.\ref{mtrx}), it didn’t comprise good yields.\\ As it can be considered, obtained results (Tab.2) aren’t acceptable. Setting best input values are as follows: 40 for user-defined $mt$, 50 for 'at', and 5 and 10 respectively for min and max clone rates for antigen vector, as well as all of attributes are selected. \begin{center} \footnotesize\ \includegraphics[scale=0.4]{Chart4} \\ \textbf{Fig.5} Yields from three tests with applying Eq.\ref{DCEq} as radius strategy for sampling in non-randomly way. Function in a) is max b) is mean c) is median\\ \end{center} By analyzing tests, we employed “median” which can be a becoming standard for measuring coverage radius of dendritic cells. Details are available at Tab.6 at appendix. So, betterment in sampling is observable from (a) to (c) in Fig.5. We enforced another test, at this time by utilizing the CFA \cite{Ref37} with ANN as learner classifier which is a powerful feature selection method inspired by cuttlefish mechanism presented by Sabry Eesa and et al. (Fig.6)\\ Here, it is necessary to provide an explanation of the values of the input parameters in Tab.6 and its effect on the output performance of the proposed system. Whatever the radius of presenting of DCs (rows 1 and 2 in Tab.6) be higher, the false positive error will be increased. As an instance, in row 2 of this table, the two maximum and mean criteria are respectively selected for the two parameters of radius of presenting of DCs and dynamic migration threshold, which its result is increase in detection rate and a significant decrease in false negative rate and an increase in accuracy and positive rates. Although the increase in false negative is highly undesirable, the classifier is successful when both of its false positive and false negative rates is low. Therefore, care must be taken in selecting the criterion type for these two sensitive input parameters. \begin{center} \includegraphics[scale=0.22]{Chart7} \\ \footnotesize\ \textbf{Fig.6} Curves belong to experiment of the proposed DCA (Alg.3) by utilizing Eq.\ref{DCEq} (F was median) and values from Tab.3\\ \end{center} Notice that the “mean” was selected for F parameter in Eq.\ref{mt}. DCA Classification phase is finally performed by checking status of all migrated DCs. This means that it is checked for each AG and how many mature/semi-mature migrated cells have sampled it during DCA processes in detection phase. If number of mature cells be greater than semi-mature ones, it is likely that AG possesses anomalous pattern (attack). This probability will be higher when the difference between the number of mature and semi-mature cells is a lot. \\ Hitherto, we showed the effectiveness of our proposed ideas in Sec.4. Fig.7 comprehensively exposes efficacy rate of proposed ideas in improvements of the original DC mechanism while sampling antigens are accomplished in both random and non-random ways (Eq.\ref{DCEq}) as compared to centroid based approaches like the Black hole clustering algorithm. It is proposed by Hatamlou and is actually inertia version of PSO which is widely used in classification problems. Curves with and without using the dimensional reduction method (CFA) also provide a better detection rate in condition of any prior training deficiency while this rate for BHA was 65.7. Whereas it is shown the DR of blue curve (86.2) is clearly a few lower than other approaches which Eq.\ref{DCEq} has been used for them. Chromatic blue curve belongs to the condition that non-random sampling was adopted. In like manner, the violet, green and light blue belong to simulated Alg.3. As shown from following Chart, it must be worked on distributed sampling proposed on Eq.\ref{DCEq}, especially blue curve, better than before.\\ So as to analyze unseen data detection rates (UDR), we enhanced the size of test subset from 2110 to 20000 records (tenfold). At gained set, the number of embedded unseen attacks were 3000 records (15 percentage). In test of light blue curve, UDR was 79.07 means just 18 from total 87 unseen anomalies which have been detected under previous test set that was not so ideal. According to Tab.4, 37 samples were detected as unseen anomalies from total 77 samples which wrongly were classified as normal profiles (FNR). Ordinarily, error rate due to detected unseen anomalies (UFNR) will be raised meantime increasing time and cost complexities while test size was increased. So, we showed raising UDR from 79.07 to 98.76 in Tab.4.\\ \begin{center} \footnotesize\ \includegraphics[scale=0.45]{MainChartDCA} \\ \textbf{Fig.7} Comparative results obtained from final experiment of the improved DCA (Alg.3)\\ \end{center} \paragraph{\textbf{Analysis by CID criterion}} There is a criterion called “Capability of Intrusion Detection” that firstly was proposed in Ref.\cite{Ref36} and strongly recommended to be used in evaluations. It is used in cases that ROC curves cross each other like Fig.7, in such cases, both TP and FP are raised or reduced together so it is impossible to analyze which one of curves has better performance. It is defined in Eq.\ref{Eq13}. Though it is based on information theory, we simplified it as follows so as to be more useable:\\ The probability of intrusion presence on test set, Base rate $B=10^{-5}$ by default. Depending on Tab.5, the blue and the light blue with respectively 3.6443 and 10.4493 scores, are most capable among other methods. The use of CFA as the feature selection phase shows its influence on the superiority of the Light blue approach to green. In approaches with blue and violet colors, there is no method for sampling and it is random by default. The impact of the use of CFA on both green and light blue approaches has been positive in terms of CID rates. As contest between methods with violet, light blue and green colors and the influence of CFA usage in light blue curve compared with green ones is observable.\\ \begin{center} \footnotesize\textbf{Table.5} Competitive analysis of the DCA approaches \\ \footnotesize\begin{tabular}{c|c} Method (by Color)&Capability of Intrusion Detection\\ \hline Green&3.5753\\ \textbf{Blue}&\textbf{10.4493}\\ Red&2.3315\\ Violet&3.5311\\ \textbf{Light Blue}&\textbf{3.6443}\\ Orange&1.1769\\\hline \end{tabular} \\ \end{center} \section{Conclusion and future directions} In this research, we deeply studied improving the immune based DCA mechanism in anomaly detection problem. Its immunological background helped us much to inspiration. At this proposed semi-supervised classifier, DCs present antigens siting on their coverages non-randomly. Mobility of migration threshold, non-random antigen sampling and necessity for antigen set to be preordered are among problems that were addressed well. Concerning the results of the experiments, although the detection rate of the proposed approach using the non-random sampling idea was high, its intrusion detection capability is weaker than the default case of random sampling. However, detection rate of unseen attacks in the proposed method was also promising. But technically, achieving higher CID with higher DR is feasible, and this depends more on the application of the sampling criteria type (mean, median, etc.) as well as the correct evaluation of the input signals in the signal assessment phase. It shows that the proposed system still needs to be worked on and can complementary be a future plan for research. \\ \section*{Acknowledgment } \footnotesize This work derived from approved M.Sc. Thesis, is supported by Malek-Ashtar University of Technology (MUT), IRAN. \\ \section*{Compliance with Ethical Standards} \footnotesize\textbf{Conflict of interest:} On behalf of all authors, the corresponding author states that there is no conflict of interest. \\ \footnotesize\textbf{Funding:} This study is not funded by a specific project grant.\\ \footnotesize\textbf{Ethical approval:} This article does not contain any studies with human participants or animals performed by any of the authors.\\ \footnotesize\textbf{Informed consent:} Informed consent was obtained from all individual participants included in the study.
{'timestamp': '2020-04-21T02:26:56', 'yymm': '2004', 'arxiv_id': '2004.09274', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09274'}
arxiv
\section{Introduction} \label{intro} The R package \textit{SamplingStrata} \citep{barcaroli:2020} is an instrument for the optimization of stratified sampling. It has been described in detail in \cite{GB14}, \cite{BB16} and \cite{barcaroli:2020a} \footnote{Detailed information on the package is in \url{https://barcaroli.github.io/SamplingStrata/} }. The first release of the R package \textit{SamplingStrata} was made available on the CRAN in July 2011. At the time, the package was being used only internally in the Italian Institute of Statistics (Istat), in particular for agricultural surveys. Since then, as far as we know, \textit{SamplingStrata} has been used in the New Zealand Statistical Institute, tested at Statistics Denmark and considered for evaluation at Statistics Canada. Eurostat used \textit{SamplingStrata} for designing its 2018 LUCAS survey \citep{ballin:2018}. Bank of Italy, supported by Istat, adopted \textit{SamplingStrata} to re-design its Survey on Households Income and Wealth. Also World Bank adopted \textit{SamplingStrata} and embedded it in its SurveySolutions SamplingTools integrated application. Very recently, the NOAA Alaska Fisheries Science Center adopted SamplingStrata for its survey on fish populations in the Gulf of Alaska. Figure \ref{SamplingStrataRank} illustrates the relative importance among all packages in the CRAN: rank in terms of downloads is such that SamplingStrata comes before the 82\% of the about 18,000 packages, despite its highly specific character. \begin{figure}[h!] \centering \includegraphics[width=0.6\textwidth]{./images/SamplingStrataRank.png} \caption{Rank of SamplingStrata in terms of downloads from the CRAN} \label{SamplingStrataRank} \end{figure} This interest is also due to the improvements that in last two years have been produced by new developments aimed to \begin{itemize} \item increase the processing performance of the optimization step; \item extend the applicability of the instrument. \end{itemize} With regard to performance, in many occasions the processing time required to perform the optimization step in \textit{SamplingStrata} has been a point of weakness of the package. Compared to the seconds taken by package \textit{stratification} to perform the same task, the minutes (or even hours) required by \textit{SamplingStrata} have been a relevant problem for users. The answers to this problem were: \begin{enumerate} \item the adoption of a variant of the Genetic Algorithm at the basis of function \textit{optimizeStrata}, i.e. the Grouping Genetic Algorithm; \item the development of a completely new optimization algorithm, which does not operate by aggregating atomic strata, but by randomly cutting the domain of each (continuous) stratification variable. \end{enumerate} As for the applicability, the following extensions have been implemented in the package: \begin{enumerate} \item the possibility to model the relationships between auxiliary variables available in the frame and the variables of interest, in order to correctly estimate the variance of the latter (\textit{anticipated variance}); \item the opportunity to consider the geographical localization of the units in the frame and hence to take into account their \textit{spatial auto-correlation}, in order to correctly determine the best stratification in \textit{spatial sampling}. \end{enumerate} The increasing availability of georeferenced or geocoded sampling frames makes this second point extremely important. For instance, in the Italian Statistical Institute this availability is guaranteed by the \textit{Registro Statistico di Base dei Luoghi, RSBL} (Base Statistical Register of Places). We remind that RSBL offers different levels of geolocation of the statistical units: punctual (coordinates), irregular polygons (sections, municipalities, etc.), regular polygons (EU grids) accompanied by the corresponding geographic files necessary for determining spatial relations. In order to extend the applicability of \textit{SamplingStrata} to spatial sampling using the methodology suggested by \cite{degruijter2015}, two additional functionalities have been implemented consisting in: \begin{enumerate} \item to extend the possibility to handle the anticipated variance to cases in which a \textit{Spatial Linear Model} is applicable (\textit{full parametric approach}); \item to make available a different approach that requires as input for each point both prediction and prediction errors (\textit{non parametric approach}). \end{enumerate} In the \textit{parametric} approach, the parameters of a Spatial Linear Model are explicitly supplied, while in the \textit{non parametric} approach only the parameter related to the \textit{range} of spatial correlation must be supplied. In both cases, geographical coordinates have to be supplied for each unit in the frame. In order to ensure continuity with previous applications, the old optimization functions (as \textit{optimizeStrata} and \textit{optimizeStrata2} remain in the package, but a new generic optimization function, namely \textit{optimStrata}, has been made available, with a specific parameter, \textit{method}, that indicates the type of algorithm that will be used in the optimization step: \begin{enumerate} \item method = "atomic" implies the use of the old algorithm implemented in \textit{optimizeStrata}; \item method = "continuous" implies the use of the algorithm applicable in case of all continuous stratification variables; \item method = "spatial" implies the use of the new algorithm implementing the non parametric approach for spatial sampling. \end{enumerate} This paper is structured as follows. In Section \ref{optimization} a description of improvements in the optimization step is given, with some details on the adoption of the Genetic Grouping Algorithm to increase the performance of the already available optimization step, the development of the new function \textit{optimizeStrata2} covering the optimization step, and the handling of anticipated variance. In Section \ref{spatial} the general approach followed to extend the applicability of the package to spatial sampling is illustrated. In Section \ref{case1} is reported an application of the non parametric approach to a widely used example (dataset \textit{meuse}). Section \ref{case2} reports an application of both approaches to the case of optimization of the stratification of a frame where the selection units are Census Enumeration Areas. Finally, in Section \ref{conclusions} some conclusions are given, together with indications on future developments. The R scripts together with data necessary to replicate the two case studies are available at the link \url{https://github.com/barcaroli/R-scripts}. The version of \textit{SamplingStrata} including developments here illustrated is downloadable from the link \url{https://github.com/barcaroli/SamplingStrata}. \section{Improvements in the optimization algorithms} \label{optimization} The initial version of the \textit{SamplingStrata} optimization function (\textit{optimizeStrata}) (now \textit{optimStrata} with method = "atomic") was based on the use of a plain Genetic Algorithm (GA). The starting point was the construction of the \textit{atomic stratification}, obtained as the Cartesian product of the stratification variables, all rigorously categorical (if continuous, a discretization step was required). Every possible given stratification was obtained as an aggregation of atomic strata. In this setting, each stratification is represented by a vector of labels, whose length is equal to the number of atomic strata: atomic strata that share the same label in the vector are collapsed in an aggregate stratum. For each stratum (atomic or aggregate) mean and standard deviation of target variables are calculated by considering their values (or the values of related proxy variables) in the sampling frame. For each stratification, required sample size (and related cost) is calculated by applying the Bethel algorithm \citep{bethel:1989}, under given precision constraints on target estimates. In the GA approach, each vector representing a stratification is considered an (\textit{individual}) in a (\textit{generation}), and its (\textit{fitness}) is measured by the associated sample cost. The usual GA operators (\textit{mutation}) and (\textit{crossover}) are applied in order to produce a new generation from the current one. After a given number of iterations, the best solution represents the stratification with the associated minimum sample cost, compliant with precision constraints. \subsection{Changes to GA operators \textit{selection} and \textit{crossover}} The optimization step previously described is formalized in Algorithm \ref{algorithm1}. \\ \begin{algorithm}[H] \SetAlgoLined \SetKwData{Left}{left} \SetKwData{This}{this}\SetKwData{Up}{up} \SetKwFunction{Union}{Union} \SetKwFunction{FindCompress}{FindCompress} \SetKwInOut{Input}{input} \SetKwInOut{Output}{output} \Input{sampling frame, precision constraints, atomic strata} \Output{optimal stratification of the sampling frame} \BlankLine \nlset{REM} generate first population pop[1,]\;\label{generate first} \For{$j\leftarrow 1$ \KwTo $popSize$} { generate randomly a vector pop[1,j] of integers (from 1 to maxstrata)\; aggregate atomic strata using pop[1,j] vector\; calculate sample.cost(pop[1,j]) applying Bethel algorithm on resulting aggregate strata\; store pop[1,j] with min(sample.cost) as bestSolution\; } \nlset{REM} generate next populations pop[i,]\;\label{generate next} \For{$i\leftarrow 2$ \KwTo $iterations$} { apply selection and crossover operators to population pop[i-1,]\; generate individuals in pop[i,]\; apply mutation operator to pop[i,]\; \For{$j\leftarrow 1$ \KwTo $popSize$} { aggregate atomic strata using pop[i,j] vector\; calculate sample.cost(pop[i,j]) applying Bethel algorithm on resulting aggregate strata\; \lIf{sample.cost(pop[i,j] $<$ sample.cost(bestSolution)} {bestSolution $\leftarrow$ pop[i,j]} } } \caption{Function 'optimStrata' algorithm (method = "atomic")} \label{algorithm1} \end{algorithm} As previously mentioned, using the conventional GA operators the convergence towards the best solution can be exceedingly slow. Following some of the indications contained in \cite{oluing:2017} and \cite{oluing:2019}, two of the three GA operators were modified, i.e. \textit{selection} and \textit{crossover}, accordingly to the Grouping Genetic Algorithm (GGA) approach (the \textit{mutation} operator remained unchanged). As for \textit{selection}, instead of selecting parents for breeding completely at random, a probability of selection has been defined by means of a fitness function, in order to privilege most promising individuals. As for \textit{crossover}, instead of mixing chromosomes in an undifferentiated way, groups of them in one parent (representing already aggregated strata) are attributed to the other parent when generating a child, preserving their composition. The introduction of these innovations since release 1.2 allowed to substantially increase the performance of the optimization function. \subsection{New optimization algorithm} We recall that the version of optimization so far described is applicable only to categorical stratification variables: were they not categorical, they have to be discretized, obtaining categorical ordinal variables. A criticism of survey managers is that strata in the optimal solution are of difficult interpretation, as values of stratification variables in a given stratum in general are not contiguous. This problem is relevant when stratification variables are of the continuous type: as already said, they have to be discretized, and there is no warranty that in each resulting optimized stratum the values of this variables are contiguous, i.e. without "holes". \\ In order to overcome this problem, a new optimization algorithm, still making use of the Genetic Algorithm, has been implemented. This new version, first implemented in the function \textit{optimizeStrata2}, now in \textit{optimStrata} with method = "continuous", is applicable only when all the stratification variables are of the continuous type. Instead of building the atomic strata previously to the optimization step and proceeding to aggregate them, with this new function an individual in a population (a given stratification) is generated by randomly cutting the domains of definition of each stratification variable, and by producing the stratification by applying the Cartesian product to the so obtained discretized values. Then, the optimization proceeds as formalized in Algorithm \ref{algorithm2}. Under this new approach, the genoma of a solution is given by the sequence of cuts for the different stratification variables. \\ As a result, the obtained strata are "7-shaped" like the ones reproduced in Figure \ref{7_shape}. It can be seen that strata are characterized by given non overlapping intervals of values for each stratification variable. \\ Moreover, in many situations the convergence to the optimal solution can be much quicker with this new algorithm than with the previous one. The suggestion is to try both and analyze the different results in order to choose the best. \begin{figure}[H] \centering \includegraphics[width=1.0\textwidth]{./images/7_shape.png} \caption{Example of 7-shaped strata obtained with \textit{continuous} method} \label{7_shape} \end{figure} \begin{algorithm}[H] \SetAlgoLined \SetKwData{Left}{left} \SetKwData{This}{this}\SetKwData{Up}{up} \SetKwFunction{Union}{Union} \SetKwFunction{FindCompress}{FindCompress} \SetKwInOut{Input}{input} \SetKwInOut{Output}{output} \Input{sampling frame, precision constraints} \Output{optimal stratification of the sampling frame} \BlankLine \nlset{REM} generate randomly first population pop[1,]\;\label{generate first} \For{$j\leftarrow 1$ \KwTo $popSize$} { \For{$k\leftarrow 1$ \KwTo $numVar$} { generate randomly n cuts (n = nStrata -1) in the definition domain of stratification variable k\; concatenate the n cuts to the vector pop[1,j]\; } generate strata using pop[1,j] vector\; calculate sample.cost(pop[1,j]) applying Bethel algorithm on resulting aggregate strata\; store pop[1,j] with min(sample.cost) as bestSolution\; } \nlset{REM} generate next populations pop[i,]\;\label{generate next} \For{$i\leftarrow 2$ \KwTo $iterations$} { apply selection and crossover operators to population pop[i-1,]\; generate individuals in pop[i,]\; apply mutation operator to pop[i,]\; \For{$j\leftarrow 1$ \KwTo $popSize$} { generate strata using pop[i,j] vector\; calculate sample.cost(pop[i,j]) applying Bethel algorithm on resulting aggregate strata\; \lIf{sample.cost(pop[i,j] $<$ sample.cost(bestSolution)} {bestSolution $\leftarrow$ pop[i,j]} } } \caption{Function 'optimStrata' algorithm (method = "continuous")} \label{algorithm2} \end{algorithm} \subsection{Anticipated variance} When optimizing the stratification of a sampling frame, it is assumed that the values of the target variables Y’s are available for the generality of the units in the frame, or at least for a sample of them, by means of which it is possible to estimate means and standard deviations of Y’s in atomic strata. Of course, this assumption is seldom expected to hold. A much more common situation is the one where Y's are proxy variables of the real target variables (named Z). In these cases, there is no guarantee that the final stratification and allocation can ensure the compliance to the set of precision constraints for the real target variables. The importance of considering anticipated variance has been clearly evidenced in \cite{lisic2018}. In order to take into account this problem, and to limit the risk of overestimating the expected precision levels of the optimized solution, it is possible to carry out the optimization by considering, instead of the expected coefficients of variation related to proxy variables, the anticipated coefficients of variation (ACV) that depend on the model that is possible to fit on couples of real target variables and proxy ones. In the current implementation, only models linking continuous variables can be considered. The definition and the use of these models is the same that has been implemented in the package stratification \citep{baillargeon:2014}. In particular, the reference here is to two different models, the linear model with heteroscedasticity: \\ $ Z = \beta Y + \epsilon $ \\ where \\ $ \epsilon \sim\ N(0, \sigma^2 Y^{2 \gamma}) $ \\ (in case $\gamma$ = 0 the model is homoscedastic) \\ and the loglinear model: \\ $ Z = exp(\beta log(Y) + \epsilon) $ \\ where \\ $ \epsilon \sim\ N(0, \sigma^2) $ \\ In the case of the linear model the anticipated variance (AV) on a total is given by the following expression \citep{lisic2018}: \\ $AV(\hat{T}_{j}) = \sum_{h=1}^{H} (1- \dfrac{n_{h}}{N_{h}}) \dfrac{N_{h}^2}{n_{h}} ( \sum_{i=1}^{N_{h}} Y_{i,j}^{2\gamma} \sigma^{2} + \sum_{i=1}^{N_{h}} (y_{i}\beta_{j} - \Bar{y}_{h}\beta_{j})^{2} ) $ \\ Using a linear model, in case of presence of heteroscedasticity ($\gamma > 0$) in residuals distribution, a crucial point is in correctly quantifying it. The problem of how to estimate a measure of heteroscedasticity has been dealt with by different authors (\cite{henry:2006} and \cite{knaub:2019}). A simple and quick solution has been implemented in a new function \textit{computeGamma} in \textit{SamplingStrata}. This function receives in input the distribution vectors respectively of residuals and of the explanatory variable, and yields a heteroscedasticity index value together with the value of model variance to be used as values of corresponding parameters. An example of application is in \cite{barcaroli:2020b}. \section{Extension to spatial sampling} \label{spatial} Let us suppose we want to design a sample survey with $k$ $Z$ target variables, each one of them correlated to one or more of the available $Y$ frame variables. When frame units are georeferenced of geocoded, the presence of spatial auto-correlation can be investigated. This can be done by executing for instance the Moran test on the target variables: if we accept the null hypothesis in the Moran test (absence of spatial auto-correlation) then we can search for the optimal stratification with the method based on the calculation of anticipated variance, described in the previous section, or other methods offered by the package functions. If the null hypothesis is rejected then we have to proceed in a different way taking into account also this variance component. Two alternative instruments to handle spatial auto-correlation have been implemented in \textit{SamplingStrata}: \begin{enumerate} \item a multivariate version of the methodology proposed by \cite{degruijter2015} has been implemented in a completely new optimization function, i.e. \textit{optimizeStrataSpatial}; \item in handling anticipated variance, a new model type has been introduced, namely the \textit{Spatial Linear Model}: parameters of this model can be given as input to the \textit{optimizeStrata2} function, that provides to calculate variance in the strata taking into account also the spatial component. \end{enumerate} The first method (the one we call \textit{non parametric}) requires that predicted values together with prediction error variance must be provided for each unit in the frame, by using any kind of model. The second (called \textit{parametric}) requires the explicit indication of the parameters of a \textit{Spatial Linear Model} linking target Z and Y frame variables: \\ $$Z = Y \beta_{1} + W Y\beta_{2} + u Y^{\gamma} $$ \\ where the residuals $u$ can be auto-correlated, and the autocovariance is assumed to be exponential. $W$ is the \textit{weighted contiguity or distance matrix}. The values obtained as product of the Y values and W matrix must be given for each unit in the frame, together wit the values of the parameters of the model. \\ Moreover, this method explicitly handles the heteroscedasticity $\gamma$ in residuals. \\ Both methods consider the spatial component in the estimation of the variance in the strata by using the formulas illustrated in \cite{degruijter2015} and \cite{degruijter2019}. In case $Z$ is the target variable, omitting as negligible the \textit{fpc} factor, the sampling variance of its estimated mean is: \begin{equation} \label{eq1} V(\hat{\bar{Z}}) = \sum_{h=1}^{H}(N_{h}/N)^{2} S_{h}^{2}/n_{h} \end{equation} We can write the variance in each stratum $h$ as: \begin{equation} \label{eq2} S_{h}^{2} = \dfrac{1}{N_{h}^{2}} \sum_{i=1}^{N_{h-1}}\sum_{j=i+1}^{N_{h}}(z_{i}-z_{j})^{2} \end{equation} The optimal determination of strata is obtained by minimizing the quantity $O$: \begin{equation} \label{eq3} O = \sum_{h=1}^{H} \dfrac{1}{N_{h}^{2}} \{ \sum_{i=1}^{N_{h-1}} \sum_{j=i+1}^{N_{h}} (z_{i}-z_{j})^{2}\}^{1/2} \end{equation} Obviously, values $z$ are not known, but only their predictions, obtained by means of a regression model. So, in Equation \ref{eq3} we can substitute $(z_{i}-z_{j})^{2}$ with \begin{equation} \label{eq5} D_{ij}^{2} = \dfrac{(\tilde{z}_{i}-\tilde{z}_{j})^{2}}{R^{2}} + V(e_{i}) + V(e_{j}) - 2Cov(e_{i},e_{j}) \end{equation} where $R^{2}$ is the squared correlation coefficient indicating the fitting of the regression model, and $V(e_{i})$, $V(e_{j})$ are the model variances of the residuals. The spatial auto-correlation component is contained in the term $Cov(e_{i},e_{j})$. \\ The joint optimization of both strata bounds and sample units allocation can be carried out by software \textit{Ospats} (available at the link \url{https://github.com/jjdegruijter/ospats}) minimizing the expression defined in Equation \ref{eq3} by means of an iterative re-allocation obtained by repeatedly transferring grid points from one stratum to another once verified that these transfers have a positive effect in terms of reduction of the overall variance. \\ In particular, the quantity $D_{ij}$ is calculated in this way: \begin{equation} \label{eq6} D_{ij}^{2} = \dfrac{(\tilde{z}_{i}-\tilde{z}_{j})^{2}}{R^{2}} + (s_{i}^{2} + s_{j}^{2}) - 2 s_{i} s_{j} e^{-k (d_{ij}/range)} \end{equation} where $ d_{ij} $ is the Euclidean distance between two units i and j in the frame (calculated using their geographical coordinates), and $s_{i}^{2}$ is an estimate of the prediction variance in the single point and \textit{range} is the maximum distance below which spatial auto-correlation can be observed among points. The value of \textit{range} can be determined by an analysis of the spatial \textit{variogram}. \\ To summarize, when frame units can be geo-referenced, the proposed procedure is the following: \begin{enumerate} \item acquire coordinates of the geographic location of the units in the population of interest; \item fit a model between the Y variable(s) available in the frame and the Z variable(s) of interest; \item verify the presence of spatial correlation by executing the Moran auto-correlation test on residuals; \item if the test ascertains the presence of spatial correlation, perform a spatial analysis based on the variogram in order to determine the values of the parameters of interest for next steps (in particular, the value of \textit{range}); \item apply one or both of the two available methods to perform optimization and determine both best stratification and allocation; \item when the \textit{non parametric} method is used (with the function \textit{optimizeStrataSpatial}), preliminary steps are: \begin{enumerate}[label=\alph*)] \item fit a \textit{Kriging} model (or any other spatial model) on data for each couple $Y$ and $Z$ and obtain predicted values together with associated errors for each unit in the frame; \item associate predicted values and prediction errors to each unit in the frame; \end{enumerate} \item instead, when the \textit{parametric} method is used (with the function \textit{optimizeStrata2}), preliminary steps are: \begin{enumerate}[label=\alph*)] \item build the spatial \textit{weighted contiguity matrix} $W$ for each $Y$; \item fit a \textit{Spatial Linear Model} for each couple $Y$ and $Z$; \item indicate its parameters in the model information frame; \item associate values $Y \times W$ for each $Y$ to units in the frame; \item in case of heteroscedasticity (verified with a Breusch-Pagan test) calculate the value of related index. \end{enumerate} \end{enumerate} \section{Applications} \label{applications} In the following, two case studies will be illustrated. \\ In the first one it will be shown that \textit{optimizeStrataSpatial} and \textit{Ospats} are substantially equivalent in the univariate case, while \textit{optimizeStrataSpatial} can be used also in the multivariate (and multidomain) more general case. \\ In the second case study three different optimization strategies will be compared, differentiating by making use of: \begin{enumerate} \item the anticipated variance calculated by means of a simple linear model without spatial auto-correlation (\textit{optimizeStrata2} with model type = 'linear'); \item use of kriging model with the \textit{non parametric} method (\textit{optimizeStrataSpatial}); \item the anticipated variance calculated by means of a Spatial Linear Model (\textit{parametric} method with \textit{optimizeStrata2}). \end{enumerate} In the case studies we will make use of a number of R packages specifically dealing with spatial modeling, namely \textit{gstat}, \textit{sp} and \textit{automap}. For a general description of this packages see \citep{pebesma2004}, \citep{pebesma2005}, \citep{graler2016} and \citep{himiestra2008}. \subsection{Case study 1: Meuse river territory} \label{case1} The two datasets "meuse.grid" and "meuse" are provided by the R package \textit{gstat}. We can consider "meuse.grid" as the frame of 3,103 points (each one of approximately 15 m x 15 m) in a flood plain along the river Meuse in the Netherlands, from which a simple random sample of 155 points have been selected in order to observe the concentration of the four metals (see Figure \ref{meuse}). \begin{figure}[H] \centering \includegraphics[width=0.8\textwidth]{./images/meuse.png} \caption{Distribution of meuse.grid and meuse points} \label{meuse} \end{figure} Dataset "meuse" contains 155 measurements of four heavy metals (cadmium, copper, lead, zinc) measured in the top soil, together with some covariates (elevation, distance from the river, soil type, land use) and coordinates x and y. Dataset "data.grid" contains basic information (coordinates x and y plus distance from the river and soil type) on a grid of 3,103 points laying in the same zone. The objective is to produce estimates on the total amount of metals concentrations in the whole area, by adopting an optimized stratified sampling design. In order to do that, the following steps are to be performed: \begin{enumerate} \item making use of the available random sample of already observed points, estimate a model for each target variable (metal concentration); \item predict values of metal concentration for each point in the area; \item determine the best stratification of the frame in order to minimize the size of the sample required to be compliant to precision constraints on the target estimates. \end{enumerate} In the following, we will first consider the univariate case, where only one target estimate will be taken into consideration. This will enable us to compare two different approaches, the one implemented in \textit{SamplingStrata}, the other one implemented in the software \textit{Ospats}. After showing the equivalence of the two methods, we will consider the multivariate case, where only \textit{SamplingStrata} is applicable. We consider first the univariate case, and select "lead concentration" as the only target variable. First, we use \textit{kriging} in order to model the relations bewteen \textit{lead concentration} with the covariates \textit{dist} and \textit{soil}. It is a three-step process as suggested by \cite{pebesma:2019}: \begin{enumerate} \item first we initialize the parameter \textit{psill}, \textit{range} and \textit{nugget} with the function \textit{autofitVariogram} (see the obtained variogram in Figure \ref{variogram_lead}), \item then we fit the model by using the \textit{gstat.lmc} and \textit{fit.lmc} functions; \item finally, we predict the the values of \textit{lead concentration} in all the 3,103 points. \end{enumerate} \begin{lstlisting}[language=R] library(automap) library(gstat) data(meuse) coordinates(meuse) = c("x", "y") data(meuse.grid) coordinates(meuse.grid) = c("x", "y") v <- variogram(lead ~ dist + soil, data=meuse) fit.vgm <- autofitVariogram(lead ~ elev + soil, meuse, model = c("Exp")) plot(v, fit.vgm$var_model) fit.vgm$var_model # model psill range # 1 Nug 1524.895 0.0000 # 2 Exp 8275.431 458.3303 g <- gstat(NULL,"Lead", lead ~ dist + soil, meuse) g vm <- variogram(g) vm.fit <- fit.lmc(vm, g, vgm(psill=fit.vgm$var_model$psill[2], model="Exp", range=fit.vgm$var_model$range[2], nugget=fit.vgm$var_model$psill[1])) preds <- predict(vm.fit, meuse.grid) names(preds) # [1] [1] "Lead.pred" "Lead.var" \end{lstlisting} \begin{figure}[H] \centering \includegraphics[width=0.4\textwidth]{./images/variogram_lead.png} \caption{Variogram of lead concentration} \label{variogram_lead} \end{figure} We are now able to perform the optimization step with \textit{SamplingStrata}, having set a precision constraint equal to 5\% on the Cv of the mean of \textit{lead concentration}: \begin{lstlisting}[language=R] df <- NULL df$Lead.pred <- preds@data$Lead.pred df$Lead.var <- preds@data$Lead.var df$dom1 <- 1 df <- as.data.frame(df) df$id <- meuse.grid$id df$lon <- meuse.grid$x df$lat <- meuse.grid$y frame <- buildFrameSpatial(df=df, id="id", X=c("Lead.pred"), Y=c("Lead.pred"), variance=c("Lead.var"), lon="lon", lat="lat", domainvalue="dom1") set.seed(1234) solution <- optimStrata(method="spatial", errors=cv, framesamp=frame, nStrata = 3, fitting = 1, range = fit.vgm$var_model$range[2], kappa = 1, gamma = 0) \end{lstlisting} \begin{figure}[H] \centering \includegraphics[width=0.5\textwidth]{./images/lead_optim.png} \caption{Optimization step for lead concentration with 3 strata} \label{lead_optim} \end{figure} In listing~\ref{strata} the structure of the optimized strata is reported. The total sample size is 128. \lstinputlisting[float=h,frame=tb,caption=\textit{SamplingStrata} optimized strata,label=strata]{./output/ss_strata.txt} \lstinputlisting[float=h,frame=tb,caption=\textit{Ospats} optimized strata,label=ospatsStrata]{./output/ospats_strata.txt} If we run Ospats on the same input, we obtain a solution that, suitably elaborated in order to be comparable, is reported in listing~\ref{ospatsStrata}. It can be seen that strata are slightly overlapping (when the strata obtained by SamplingStrata are never). The total sample size is 129, practically equivalent to the one determined by \textit{SamplingStrata}. Also the allocations in the strata are almost the same. \\ We run both softwares a second time with a different number of strata (5). Increasing the number of strata does not change the substantial equivalence of the two approaches in terms of allocation (it is 112 for SamplingStrata and 115 for Ospats), but the resulting stratifications are noticeably different, as it can be seen by Figure \ref{solutions}. \\ \begin{figure}[h!] \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1.2\linewidth]{SamplingStrata_3strata} \caption{\textit{SamplingStrata} stratification (3 strata)} \label{solutions:sfig1} \end{subfigure}% \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1.2\linewidth]{Ospats_3strata} \caption{\textit{Ospats} stratification (3 strata)} \label{solutions:sfig2} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1.2\linewidth]{SamplingStrata_5strata} \caption{\textit{SamplingStrata} stratification (5 strata)} \label{solutions:sfig3} \end{subfigure}% \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1.2\linewidth]{Ospats_5strata} \caption{\textit{Ospats} stratification (5 strata)} \label{solutions:sfig4} \end{subfigure} \caption{Comparison of \textit{SamplingStrata} and \textit{Ospats} stratifications} \label{solutions} \end{figure} The extension from the univariate to the multivariate case is straightforward. We now consider four different target estimates, i.e. the total concentration of all metals (cadmium, copper, lead and zinc) in the Meuse area. After producing variograms and models for each one of the target cariables, we are able to predict their concentration for each point in the grid, together with the error prediction, obtaining this work dataframe: \begin{lstlisting}[language=R] df <- NULL df$cadmium.pred <- preds.cadmium$cadmium.pred df$cadmium.var <- preds.cadmium$cadmium.var df$copper.pred <- preds.copper$copper.pred df$copper.var <- preds.copper$copper.var df$lead.pred <- preds.lead$lead.pred df$lead.var <- preds.lead$lead.var df$zinc.pred <- preds.zinc$zinc.pred df$zinc.var <- preds.zinc$zinc.var # df$dom <- meuse.grid@data$soil df$dom <- 1 df <- as.data.frame(df) df$id <- meuse.grid$id head(df) # cadmium.pred cadmium.var copper.pred copper.var lead.pred lead.var # 7.917987 7.007012 65.64426 331.6897 265.9674 7043.944 # 8.308433 6.482721 69.01170 308.4855 267.2160 6403.047 # 7.898212 6.661317 66.93037 319.6262 260.5370 6574.794 # 7.281627 6.828875 63.61440 326.8032 248.9653 6770.737 # 8.824362 5.748581 74.34104 245.6440 269.2219 5744.181 # 8.333077 6.009188 71.27280 278.8897 261.5889 5909.198 # zinc.pred zinc.var # 898.3354 67350.56 # 918.6911 59349.98 # 877.8272 61860.84 # 818.0511 64442.07 # 949.7147 49761.03 # 899.6006 52859.14 \end{lstlisting} We can now proceed with the optimization step in \textit{SamplingStrata}. As preliminary steps we prepare the precision constraints and sampling frame dataframes: \begin{lstlisting}[language=R] cv # DOM CV1 CV2 CV3 CV4 domainvalue # 1 DOM1 0.05 0.05 0.05 0.05 1 frame <- buildFrameSpatial(df=df, id="id", X=c("cadmium.pred","copper.pred","lead.pred","zinc.pred"), Y=c("cadmium.pred","copper.pred","lead.pred","zinc.pred"), variance=c("cadmium.var","copper.var","lead.var","zinc.var"), lon="lon", lat="lat", domainvalue="dom") \end{lstlisting} The parameter \textit{range} is now a vector of values: \begin{lstlisting}[language=R] range <- c(fit.vgm.cadmium$var_model$range[2], fit.vgm.copper$var_model$range[2], fit.vgm.lead$var_model$range[2], fit.vgm.zinc$var_model$range[2]) \end{lstlisting} In order to "explore" what would be a suitable number of strata in the final solution, we execute the function \textit{KMeansSolutionSpatial}, that applies a kmeans-based clustering method in order to find a quick solution in correspondence of different numbers of strata, starting from 2 ending to a 10: \begin{lstlisting}[language=R] kmeans <- KmeansSolutionSpatial(frame, fitting=c(1,1,1,1), range=range, kappa=1, gamma=0, errors=cv, maxclusters = 10) \end{lstlisting} \begin{figure}[H] \centering \includegraphics[width=0.7\textwidth]{./images/meuse_kmeans.png} \caption{Kmeans solutions up to 10 strata} \label{meusekmeans} \end{figure} As shown in Figure \ref{meusekmeans} there is no sensible reduction in sample size after 5 strata, so we choose to set nStrata equal to 5 in the optimization step. \begin{lstlisting}[language=R] set.seed(4321) solution <- optimStrata ( method="spatial", errors=cv, framesamp=frame, iter = 50, pops = 10, nStrata = 5, fitting = c(1,1,1,1), range = range, kappa = 1, writeFiles = FALSE, showPlot = TRUE, parallel = FALSE ) \end{lstlisting} \begin{figure}[H] \centering \includegraphics[width=0.5\textwidth]{./images/multi_optim.png} \caption{Optimization step for 4 metals concentration with 5 strata} \label{multi_optim} \end{figure} In listing~\ref{ssmulti} the structure of the optimized strata is reported. The total sample size is 219. The first target estimate (cadmium concentration) is the one that contributes most to the overall sample size: in fact its expected CV is just on the limit of 5\% set by the precision constraints. \begin{lstlisting}[language=R] expected_CV(solution$aggr_strata) # cv(Y1) cv(Y2) cv(Y3) cv(Y4) # 0.05 0.028 0.033 0.033 \end{lstlisting} \lstinputlisting[basicstyle=\tiny,float=h,frame=tb,caption=\textit{SamplingStrata} optimized strata (multivariate case),label=ssmulti]{./output/ssmulti.txt} The resulting strata are visualized in Figure \ref{meusemulti} \begin{figure}[H] \centering \includegraphics[width=0.7\textwidth]{./images/meuse_multi.png} \caption{Final strata in multivariate case} \label{meusemulti} \end{figure} \subsection{Case study 2: Census Enumeration Areas Frame} \label{case2} In this case study we will consider a sampling frame containing Census Enumeration Areas (EA's) as selection units: in particular, the 2,234 EA's included in Italian Municipality of Bologna. In this basic application, we consider as associated information only the total amount of population and of foreign residents. Population P is continuously updated by the Population Register, but here we use the last 2011 Population Census data. Territorial distribution is shown in Figure \ref{Bologna_P1}. \begin{figure}[h!] \begin{subfigure}{.54\textwidth} \centering \includegraphics[width=1\linewidth]{distr_population.png} \caption{Population} \label{Bologna_P1:sfig1} \end{subfigure}% \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1\linewidth]{distr_foreign.png} \caption{Foreign residents} \label{Bologna_P1:sfig2} \end{subfigure} \caption{Territorial distribution in the 2,234 Bologna EA's} \label{Bologna_P1} \end{figure} The setting for the study is the following: \begin{itemize} \item the aim is to design a sample survey whose target is to produce estimates on the size of a given sub-population in the same Bologna territory, i.e. those of the foreign residents; \item data on sub-populations are available with a temporal lag (for instance, at the last Census) or on a subset of EA's (by means of a non optimized sample): in this case, we consider the second option, in line with the Istat Permanent Census, and will draw a simple random sample with sampling rate equal to 0.2; \item using data on total population (P1) and foreign residents (ST1) for the EA's where they are jointly available, it is possible to estimate different models, in particular: \begin{enumerate} \item Linear Model; \item Kriging; \item Spatial Linear Model; \end{enumerate} \item having set precision constraints on one or more target estimates of the sub-population of interest, the best stratification of the frame is obtained by running three different optimization steps, one for each of the above models; \item a compared evaluation of the three different solutions is obtained by simulating the selection of 1,000 samples, calculating for each of them the target estimates and finally deriving the coefficients of variation. \end{itemize} \subsubsection{Application on real data} \textit{Linear Model} \\ \begin{lstlisting}[language=R] lm_1 <- lm(ST1 ~ P1,data=spoints_samp) summary(lm_1) \# Coefficients: \# Estimate Std. Error t value Pr(>|t|) \# (Intercept) -0.053350 0.982107 -0.054 0.957 \# P1 0.118006 0.004238 27.844 <0.0000000000000002 *** \# --- \# Residual standard error: 15.41 on 465 degrees of freedom \# Multiple R-squared: 0.6251, Adjusted R-squared: 0.6243 \end{lstlisting} \begin{figure}[h!] \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1\linewidth]{lm1_real_1} \caption{} \label{lm1:sfig1} \end{subfigure}% \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1\linewidth]{lm1_real_2} \caption{} \label{lm1:sfig2} \end{subfigure} \caption{Linear model between foreign residents sub-population and total population} \label{lm1_real} \end{figure} As for the distribution of residuals, see Figure \ref{lm1_real}. It is quite evident the presence of heteroscedasticity and the non-normality of residuals distribution. For this reason, we proceed to compute the heteroscedasticity index and related variance for each one of the three different models, and give corresponding values as input to the optimization steps. We calculate the heteroscedasticity index and related variability accordingly to the Linear Model (see Figure \ref{gamma}): \begin{lstlisting}[language=R] gamma_sigma_1 <- computeGamma(e=summary(lm_1)$residuals, x=spoints_samp@data$P1,nbins=6) gamma_sigma_1 # gamma sigma r.square # 0.6146480 0.6210120 0.9662238 \end{lstlisting} where the first value is the heteroscedasticity index, and the second is the standard deviation \\ \begin{figure}[h!] \centering \includegraphics[width=0.8\linewidth]{gamma_plots} \caption{} \caption{Distribution of residuals and heteroscedasticity model} \label{gamma} \end{figure} \newpage We build the sampling frame in this way: \begin{lstlisting}[language=R] id X1 Y1 domainvalue lon lat ST1 P1 1164 64 64 1 686797.2 4928305 8 64 300 192 192 1 686739.8 4932537 42 192 1791 190 190 1 684180.3 4929655 27 190 309 350 350 1 687154.7 4932146 131 350 895 0 0 1 682919.1 4931359 0 0 1750 599 599 1 690758.9 4929418 107 599 \end{lstlisting} that is, both stratification variable X1 and target variable Y1 have been set equal to the population total P1. Having fixed a precision constraint of 3\% on the target variable, the first optimization is the one making direct use of the linear model, using the method \textit{continuous}: \begin{lstlisting}[language=R] model <- NULL model$type[1] <- "linear" model$beta[1] <- summary(lm_1)$coefficients[2] model$gamma[1] <- gamma_sigma_1[1] model$sig2[1] <- gamma_sigma_1[2]^2 model <- as.data.frame(model) model # type beta gamma sig2 # 1 linear 0.1180064 0.614648 0.3856559 set.seed(1234) solution1 <- optimStrata ( method="continuous", errors=cv, framesamp=frame, model=model, nStrata = 5) \end{lstlisting} This solution yields a sample size of 400. We now proceed to draw 1,000 samples and calculate the real CV for both the Y1 variable and for the real target variable, ST1: \begin{lstlisting}[language=R] framenew <- solution1$framenew outstrata <- solution$aggr_strata framenew$Y2 <- framenew$TARGET val1 <- evalSolution(framenew, outstrata, nsampl=1000) val1$coeff_var # CV1 CV2 dom # 1 0.0094 0.029 DOM1 \end{lstlisting} The CV related to P1 is much lower that the required 3\%, but we see that the CV related to our true target variable (ST1) is compliant (2.9\%). \\ \textit{Kriging} \\ We move now to the approach based on the use of Kriging. First, we obtain the model in this way: \begin{lstlisting}[language=R] # Variogram v <- variogram(ST1 ~ P1, data=spoints_samp, cutoff=3000, width=3000/30) # Estimation of psill, range and nugget with automap fit.vgm = autofitVariogram(ST1 ~ P1, spoints_samp, model = c("Exp", "Sph", "Mat" )) plot(v, fit.vgm$var_model) fit.vgm$var_model # model psill range kappa # 1 Nug 114.3363 0.000 0.0 # 2 Mat 135.2903 1232.796 0.2 # Prediction g <- gstat(NULL, "v", ST1 ~ P1, spoints_samp) v <- variogram(g) v.fit <- fit.lmc(v, g, vgm(psill=fit.vgm$var_model$psill[2], model=fit.vgm$var_model$model[2], range=fit.vgm$var_model$range[2], nugget=fit.vgm$var_model$psill[1])) preds <- predict(v.fit, Comune_BO_geo) \end{lstlisting} We calculate the heteroscedasticity index and standard deviation of errors in this way: \begin{lstlisting}[language=R] gamma_sigma_2 <- computeGamma(e=lm_pred$residuals[camp], x=frame1$P1[camp], nbins=6) gamma_sigma_2 # gamma sigma r.square # 0.5100489 0.9401730 0.9394493 \end{lstlisting} and calculate prediction errors in this way: \begin{lstlisting}[language=R] frame$var1 <- gamma_sigma_2[2]^2 * (frame1$P1^(2*gamma_sigma_2[1])) \end{lstlisting} Once assigned to the frame the predicted values and the prediction errors to each unit in the frame, we calculate the fitting of the model in this way: \begin{lstlisting}[language=R] # Compute fitting lm_pred <- lm(ST1 ~ pred,data=frame) summary(lm_pred)$r.squared # [1] 0.6351977 \end{lstlisting} We can now proceed with the optimization step using the method \textit{spatial}: \begin{lstlisting}[language=R] frame$var1 <- preds$v.var solution2 <- optimStrata ( method="spatial", errors=cv, framesamp=frame, nStrata = 5, fitting = summary(lm_pred)$r.squared, range = fit.vgm$var_model$range[2], kappa = 1) \end{lstlisting} The sample size is now 330, much lower than the previous one, and the expected CV on the target variable is slightly above the desired 3\%, as it is 3.2\%. Once equalized (that is, once increased the sample size to the same one of the \textit{Linear Model}) it reduces to 2.85\%. \\ \textit{Spatial Linear Model} \\ Finally, we make use of third approach, the one based on the Spatial Linear Model: \begin{lstlisting}[language=R] lm_2 <- lm(ST1 ~ P1 + P1W, data=frame[camp,]) summary(lm_2) # Coefficients: # Estimate Std. Error t value Pr(>|t|) # (Intercept) 0.231107 1.457822 0.159 0.874 # P1 0.118487 0.004616 25.667 <0.0000000000000002 *** # P1W -0.002018 0.007638 -0.264 0.792 # Residual standard error: 15.42 on 464 degrees of freedom # Multiple R-squared: 0.6251, Adjusted R-squared: 0.6235 \end{lstlisting} We observe that the value of the coefficient related to P1W is very small, thus indicating a limited presence of spatial auto-correlation. We calculate heteroscedasticity and variability: \begin{lstlisting}[language=R] gamma_sigma_3 <- computeGamma(e=(frame$target[camp] - predict(lm_2,data=frame[camp,])), x=spoints_samp@data$P1,nbins=6) # gamma sigma r.square # 0.6132473 0.6257764 0.9654370 \end{lstlisting} and calculate the value of the range: \begin{lstlisting}[language=R] v2 <- variogram(res_spatial ~ 1, data=spoints_samp) fit.vgm2 = autofitVariogram(res_spatial ~ 1, spoints_samp, model = c("Exp","Sph","Mat")) fit.vgm2$var_model # model psill range kappa # 1 Nug 114.3825 0.000 0.0 # 2 Mat 135.2430 1232.444 0.2 \end{lstlisting} We can now proceed with the optimization step: \begin{lstlisting}[language=R] model # type beta beta2 sig2 range gamma fitting # 1 spatial 0.1184873 -0.002018293 0.3915961 1232.444 0.6132473 0.6251384 solution3 <- optimStrata ( model="continuous", errors=cv, framesamp=frame, model=model, nStrata = 5) \end{lstlisting} obtaining a total allocation of 393. As in the case of the Linear Model, the expected CV on the target is compliant with the precision requirement. Once equalized, it reduces to 2.89\%. As an example of a resulting stratification, we report the one obtained with the Kriging Model in Figure~\ref{bologna_real}, together with the 330 sampled EA's. \begin{figure}[H] \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=0.7\linewidth]{bologna_real_spatial} \caption{Stratified EA's} \label{bologna_real:sfig1} \end{subfigure}% \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=0.7\linewidth]{bologna_real_sampled} \caption{Sampled EA's} \label{bologna_real:sfig2} \end{subfigure} \caption{Stratification obtained with the Kriging Model} \label{bologna_real} \end{figure} The structure of the obtained strata, in terms of boundaries, together with allocation and sampling rate, is reported in Listing~\ref{reportRealPop}. \lstinputlisting[float=h!,frame=tb,caption=Results of the application of the three models,label=reportRealPop]{./output/reportRealPop.txt} \subsubsection{Simulation} The results obtained in the application to real data indicate that: \begin{itemize} \item both \textit{Linear Model} and \textit{Spatial Linear Model} are compliant with the precision requirement of 3\%, while \textit{Kriging} is slightly over; \item conversely, in terms of sample size, the \textit{Kriging} is the one with the minimum; \item once equalized (that is, after rendering equal all the sample sizes of the three solutions), the expected CVs are about the same, with a minimum for the \textit{Kriging}; \item the structure of the obtained optimized strata varies from one solution to another, both in terms of strata boundaries and allocations. \end{itemize} The substantial equivalence of the results obtained with three models is probably due to a weak spatial correlation of the variable of interest. \\ In order to analyse the contribution of spatial component in the overall variance to results obtainable by different models, we decided to carry out a simulation by generating for each EA in the frame an artificial variable $Z$, characterized by a high spatial correlation, by making use of the following equation: \\ $Z = Y \beta_{1} + W Y \beta_{2} + u\cdot Y^{\gamma}$ \\ In our case $Y$ is the population P1 in each EA, $\beta$ has been set equal to 1, $W$ is the weighted contiguity matrix, and the errors $\epsilon$ are spatially correlated and affected by heteroscedasticity. The error term $u$ has been generated as a \textit{Gaussian random field}, whose parameters are the following: \begin{enumerate} \item the covariance model is exponential; \item the error variance has been set equal to 2000; \item the range of spatial correlation has been set to 2000; \item the values of heteroscedasticity index ($\gamma$) ranges from 0 to 0.7 with a step equal to 0.05. \end{enumerate} In Table \ref{sim_res} and in Figure~\ref{simulations} the results of the simulation are reported. \begin{table}[H] \centering \begin{tabular}{||c|c|c|c|c|c|c|c|c|c||} \hline \cline{3-10} & & \multicolumn{2}{|c|}{Linear} & \multicolumn{3}{|c|}{Kriging} & \multicolumn{3}{|c||}{Spatial} \\ Run & Heter.lev.& n & CV & n & CV & CV eq. & n & CV & CV eq. \\ \hline 1 & 0 &319 &0.0167 & 36 &0.0399 &0.0125 &105 & 0.0299 &0.0162\\ 2 &0.05 &254 &0.0192 & 37 &0.0407 &0.0148 &110 & 0.0300 &0.0192\\ 3 &0.10 &275 &0.0188 & 37 &0.041; &0.0139 &120 & 0.0304 &0.0187\\ 4 &0.15 &297 &0.0305 & 34 &0.0435 &0.0131 &134 & 0.0286 &0.0186\\ 5 &0.20 &338 &0.0297 & 38 &0.0411 &0.0126 &156 & 0.0300 &0.0195\\ 6 &0.25 &395 &0.0282 & 44 &0.0397 &0.0128 &188 & 0.0300 &0.0194\\ 7 &0.30 &462 &0.0281 & 67 &0.0365 &0.0128 &230 & 0.0301 &0.0194\\ 8 &0.35 &530 &0.0278 & 78 &0.0366 &0.0127 &276 & 0.0292 &0.0200\\ 9 &0.40 &591 &0.0270 & 95 &0.037; &0.0124 &341 & 0.0297 &0.0206\\ 10 &0.45 &653 &0.0220 &119 &0.0361 &0.0135 &402 & 0.0287 &0.0220\\ 11 &0.50 &690 &0.0255 &146 &0.0352 &0.0137 &456 & 0.0286 &0.0220\\ 12 &0.55 &707 &0.0234 &171 &0.0349 &0.0146 &505 & 0.0299 &0.0241\\ 13 &0.60 &709 &0.0238 &196 &0.036; &0.0149 &467 & 0.0336 &0.0250\\ 14 &0.65 &695 &0.0255 &223 &0.0349 &0.0173 &478 & 0.0344 &0.0279\\ 15 &0.70 &676 &0.0268 &240 &0.0368 &0.0184 &483 & 0.0353 &0.0287\\ \hline \end{tabular} \caption{Simulation results.} \label{sim_res} \end{table} We see that: \begin{enumerate} \item as for the overall sample sizes required by the three models (see Figure \ref{simulations:sfig1}), those obtained by the \textit{Kriging} are always the minimum, followed by the \textit{Spatial Linear Model}, while the \textit{Linear Model} is characterized by very high levels of smple size; \item in terms of resulting expected coefficient of variation on the target variable (Figure \ref{simulations:sfig2}), the \textit{Spatial Linear Model} is the only one whose expected CV are in line with the precision requirement; the \textit{Linear Model} is the one that yields the minimum values, while the \textit{Kriging} produces the highest values; \item finally, considering the equalized expected CV (the CV that is obtained when the sample size of \textit{Kriging} and \textit{Spatial Linear Model} are increased to the one of the \textit{Linear Model}), the \textit{Kriging} is always the best, while the other two are characterized by near the same values. \end{enumerate} As a first indication, we can conclude that: \begin{itemize} \item if the aim is to minimize the overall sample size, \textit{Kriging} is the right choice: there is no warranty that the precision constraint will be respected, but the efficiency of the solution is maximized; \item if conversely we want to stick to the precision constraint, the \textit{Spatial Linear Model} should be preferred, because it has to be expected that the sample size is the one actually needed in order to be compliant. \end{itemize} \begin{figure}[H] \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1.2\linewidth]{bologna_simul_1} \caption{Performance in terms of sampling size} \label{simulations:sfig1} \end{subfigure}% \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1.2\linewidth]{bologna_simul_2} \caption{Performance in terms of CV on target variable} \label{simulations:sfig2} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=1.5\linewidth]{bologna_simul_3} \caption{Performance in terms of equalized CV on target variable} \label{simulations:sfig3} \end{subfigure} \caption{Results of simulation} \label{simulations} \end{figure} \section{Conclusions and future work} \label{conclusions} The functionalities of the package \textit{SamplingStrata} have been enriched by new developments, having the aim to increase its effectiveness and efficiency, and to extend its applicability. The changes in the Genetic Algorithm when method "\textit{atomic}" is used, respond to the need of increasing its computational performance. The new method "\textit{continuous}" allows to produce strata that are more interpretable and manageable, and in some cases also more efficient. The handling of \textit{anticipated variance} permits to compute variance in strata in a more correct way, taking into account the difference between available variables in the frame, and the variables that are the real target of the sampling survey. Very important to this aim is the consideration of heteroscedasticity of residuals, and the new function \textit{computeGamma} allows to estimate its value. The extension to the case where units in the frame can be georeferenced or geocoded covers the more and more important field of spatial sampling. The two alternatives provided, i.e. (i) the extension of model types to the 'spatial' linear model in the handling of anticipated variance, and (ii) the development of a method, "\textit{spatial}", both allow to take into account the spatial auto-correlation when calculating variance in strata, thus increasing the correctness and efficiency of optimized solutions. In the reported case studies, the applicability of these new functionalities has been illustrated, though there is not yet a clear evidence of what may be the best one. In our opinion, we need to investigate better the use of the different variants of the \textit{Spatial Linear Model}. Another required development will concern sample selection techniques peculiar of spatial sampling. Once optimal strata have been defined, it would be important to select units inside them by using techniques (as, for instance, grid sampling), that ensure to harness the spatial auto-correlation at the maximum extent. \section*{Acknowledgement} We would like to thank Mervyn O’Luing, Steven Prestwich and S. Armagan Tarim for their proposals for improving the efficiency of the Genetic Algorithm at the basis of the optimization step; and Jaap De Gruijter for his clarifications regarding variance calculation including spatial co-variance. \pagebreak \baselineskip 10pt
{'timestamp': '2020-04-21T02:28:57', 'yymm': '2004', 'arxiv_id': '2004.09366', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09366'}
arxiv
\section*{ABSTRACT} Complex scheduling problems require a large amount computation power and innovative solution methods. The objective of this paper is the conception and implementation of a multi-agent system that is applicable in various problem domains. Independent specialized agents handle small tasks, to reach a superordinate target. Effective coordination is therefore required to achieve productive cooperation. Role models and distributed artificial intelligence are employed to tackle the resulting challenges. We simulate a NP-hard scheduling problem to demonstrate the validity of our approach. In addition to the general agent based framework we propose new simulation-based optimization heuristics to given scheduling problems. Two of the described optimization algorithms are implemented using agents. This paper highlights the advantages of the agent-based approach, like the reduction in layout complexity, improved control of complicated systems, and extendability. \section{SCHEDULING ALGORITHMS} We developed different optimization algorithms for our reference problem. Of these algorithms, Particle-Swarm-Optimization and Central Complex are implemented as separate agent systems. Fundamentally the approaches fall into two categories -- sequencing and partitioning algorithms. Partitioning considers the assignment of jobs to a certain machine, while sequencing is about finding an adequate processing order of jobs on one machine (see Fig. \ref{fig: p1} and \ref{fig: p2}). Both, sequencing and partitioning, are performed in order to find a schedule that leads to a minimal makespan ($C_{max}$). Both subproblems are NP-Hard and interlock with each other. \begin{figure}[htbp] \centering \begin{minipage}[b]{6,5 cm} \includegraphics[width=\textwidth]{fig/sequence_machine_problem.png} \caption{Sequencing Problem.} \label{fig: p1} \end{minipage} \qquad \begin{minipage}[b]{8,5 cm} \includegraphics[width=\textwidth]{fig/paralle_machine_problem.png} \caption{Parallel Machine Problem.} \label{fig: p2} \end{minipage} \end{figure} We consider two distinct approach to partition jobs. The basic approach attempts to discern an overall sequence of jobs, that is cut into equisized chunks. The resulting subsequences are assigned to the respective machines. The advanced approach is to use dynamic partitioning where the partitions are no longer require to be equisized. Dynamic partitioning is especially usefully for problems with multiple different machines and if you consider constraints like different processing speeds depending on the machine or machine qualifications \subsection{Random Down Swing} The first proposed algorithm is a stochastic hill climbing approach with optional reinitialization. This Random Down Swing (RDS) approach is a simple sequencing algorithm -- for problems with multiple machines we uses the basic cutting approach to generate sequences. It starts with a randomized initial sequence and iteratively tries to improve the schedule by swapping two jobs in the sequence. The two jobs are selected randomly. A swap is accepted, if it leads to an improvement. The algorithm resets with a new initial sequence when a certain number of swaps were tried without improving the schedule. The limit before reinitialization is used, should be adapted to a given problem instance, for our scenarios we use an empirical found value of 700. The optimization terminates after a fixed number of steps and returns the best found schedule. \subsection{Simplex Method} The Simplex Method is a popular algorithm for linear programming and was developed by \cite{WM11}. It is part in the CPLEX library from IBM \cite{CPLEX10}. This optimization algorithm is specialized for the search in constrained solution spaces. The simplex method start at any vertices of constraints and walk along edges of the constructed polytope to extreme points with better objective values, until it reaches the optimum. It is based on the assumption that the global optimum is part of the constructed polytope, so the algorithms searches only on the edges of the constraints. But the algorithms has performance problems with multi-dimensional and multi-modal spaces, because of the high variability. Other disadvantages are the adaption to the application area as well as the worst-case complexity with exponential time \cite{Klee72}.\\ \subsection{Particle-Swarm-Optimization} The Particle-Swarm-Optimization (PSO) was originally proposed by \citeN{BS07} and is inspired by bird flocks. We adapted it to our problem and the discrete search space. Each particle is modeled as an individual intelligent agent. Therefore the resulting PSO is itself a MAS. Initially particles are spread randomly across the search space. We allow only positions that correspond to valid solutions and assign the respective fitness value to them. Each particle contains a sequence of jobs to encode a certain schedule. A single step to move in the search space is realized by swapping two jobs. With respect to the fundamental movement rules used in PSO, i.e., move towards global/local optimum or move randomly, we choose a suitable swap of two jobs for each particle. Based on the agent approach, it is very simple to extend and improve the classical PSO. Additional agents are added to the algorithm as pseudo particle. These additional particle do not according to the classical PSO rules. These special particles encapsulate a traditional optimization heuristics, however the it can be influenced by the swarm and can in return influence the swarm. For example the special agents may perform local optimization on solutions found by a moving particle and then provide the optimization results as guidance for other particles. The MAS implementation of PSO has some interesting advantages. The main benefit is the asynchronous distributed optimization. Particle agents explore and evaluate solutions largely independently and therefor may be distributed in a network of multiple computers. Asynchronous exchange of information between agents allows a timely update of discovered global optima. Asynchronous communication can obviously lead to outdated information regarding the global optimum persisting in certain parts of particle swarm. We however observed no negative influence resulting from the obsolete communication artifacts. \subsection{Central Complex} The Central Complex (CC) algorithm is a combination of partitioning and sequencing algorithms. The RDS algorithm is used to generate sequences for each machine. Partitioning is approached dynamically, starting from a random set of partitions. For each iteration RDS determines a good sequence for a given machine. Then a random job is shifted from the machine with the highest makespan to the machine with the lowest one. Shifting is managed in a way to avoid assigning jobs to unqualified machines. After shifting a job from one machine to another machine, the RDS optimizes the sequences again. Reinitialization is used to repeatedly start from different initial partitioning sets. A Meta-Optimization calculates appropriate parameters for the algorithm, e.g., number of reinitializations and iterations used for RDS. \section{APPLICATION AREA} We evaluate our approach applying it to a combinatorial sequence-dependent problem. This problem considers the scheduling of job for cluster tools in the production line of semiconductor manufacturing \cite{Unbehaun07}. Cluster tools can process jobs in parallel, however the processing time varies dependent on the processing of the jobs. Our objective is to minimize the completion time of the entire sequence to maximize the throughput. Figure \ref{fig: processing} illustrates the global improvement of processing jobs in parallel at the cost of slowing down the individual jobs due to shared resource. Discerning the optimal processing sequence correspond to the problem of finding the most fitting permutation of jobs with given recipes ($ R_{ i }$). The amount of permutations ($S_{all}$) can be calculated with formula \ref{permutation}. Using Stirlings approximation illustrates the exponential growth of the resulting search space depending on the queue length (L). \begin{figure}[htb] { \centering \includegraphics[width=0.55\textwidth]{fig/compare_processing.png} \caption{Comparison of sequential and parallel processing.\label{fig: processing}} } \end{figure} \begin{equation} S_{all} = \frac{ L! }{ \prod^{ r }_{ i=1 }{ R_{ i }! } } = \frac{ L! }{ R_{ 1 }! \cdot R_{ 2 }! \cdot ... \cdot R_{ r }!} \qquad \qquad L! \approx \sqrt{ 2 \cdot \pi \cdot L } \cdot \left(\frac{ L }{ e }\right)^{ L } \label{permutation} \end{equation} The problem we face is a NP hard with a multidimensional and multimodal search space. An extended problem we consider employs parallel cluster tools, resulting a multi-step problem, which is still NP-hard, since the partitioning and sequencing influence each other. \subsection{Architecture of the MAS Lagoon} Our system is separated into a server and a client application to address the distributed processing (see Fig. \ref{Lagoon}). This enables the construction of a private or open cluster combining the power of multiple host-systems for intensive computations. \begin{figure}[htb] { \centering \includegraphics[width=0.95\textwidth]{fig/mas.png} \caption{Architecture of the MAS. The blue colored agents are part of the server application and the orange colored agents belong to the client version of the MAS. Communication interfaces are shown in rhomboids.} \label{Lagoon} } \end{figure} Every agent we use relies on three basic behavior schemes. The \textbf{Initial-behavior} is run only once upon creation of an agent. The agent registers with his role at the listing-service and performs basic setup operations. After initialization the agent is either working or communicating. During \textbf{Working-behavior} the actual tasks are processed. The tasks arrive via messages. The \textbf{Messaging-behavior} relies on an incoming and an outgoing queue for messages. Each incoming task will be queued according to its priority. Control instructions are processed immediately. Other tasks are buffered for the Working-behavior. Outgoing messages will be send whenever the receiver is reachable and able to accept them. Working and messaging are processed in parallel with a separate thread for each behavior. \subsection{Communication of the agents} Communication in the MAS is realized using data packages based on the ACL (Agent Communication Language). Our messaging concept is simpler than the complete ACL architecture, but nevertheless remains universally applicable. We use wrapped objects that conform with the ACL, called \textbf{Coat-Package}. The idea is inspired by the OSI model and effectively decouples messaging in the MAS from the problem dependent parts in the tasks. A Coat-Package may transport any task and contains information not standardized by the ACL. Additionally to the specification it holds control parameters for the MAS, like priority or selected output channel. Each package has a unique identifier and a log for tracking purposes. All information with problem dependent bits is kept in an \textbf{Task-Package}. For our scenario we use a Scheduling-Task-Package. It contains a test setup including all required parameters and the desired objective function. It also holds a list of necessary processing steps to generate a valid solution. A \textbf{Collection-Package} can be used to bundle multiple Task-Packages. Problem independent \textbf{Control-Packages} enable the user to regulate the MAS during run time. Every agent has the required logic to process incoming control packages that should effect them. For example a control-package may be used to shutdown the MAS or activate debugging in agents. Valid targets for control packages are certain agents, all agents of the MAS or other packages. During run time, the MAS is dynamic, e.g., client can join or leave the MAS. Therefore it is necessary to track all task, to avoid losing some of them. Managing agents keep a copy of a task until the receive a notice that a certain procedure has actually been complete by a worker agent. In case of failures, like connection losses, task are resubmitted to other available agents. Furthermore, it is possible to migrate agents from one system to another one during run time. This concept supported by the JADE framework guarantees failure safety based on redundancy. This approach is scalable and guarantees the redundancy to successfully operate in a dynamic environment. \section{CONCEPT OF THE MAS} Our concept relies on two types of agents. General applicable agents to realize the MAS and special agents with a problem dependent implementation. Instead of using a hierarchical structure we employ independent agents that cooperate using a kind of artificial intelligence. The MAS follows an model-view-controller principle. The following section will illustrate the architecture of the MAS and describe the agents and its roles and functionality. Subsequently the agent communication and the processing of tasks is explained. Our agents register in a MAS by putting their name and role into a central listing-service. This is realized as a role of the agent and is an integral part of the environment. For the implementation, we use the framework JADE \cite{jade}. It offers a basic agent environments and agent functionalities. The simulation of the cluster tool is done using the SAGE framework. SAGE is an inhouse software solution including a discrete event simulator for typical scheduling problems and several optimization heuristics. \section{INTRODUCTION} There is a rising interest in agent-based software development since it promises efficiency paired with a high mobility while approaching complex problems. Intelligent software agents are tools which handle their tasks independently within a larger context. These agents collectively operate in a multi-agent software (MAS) architecture, solving tasks by common endeavor. This paper introduces a concept of a highly flexible multi-agent system, that is applicable in various problem domains. Our approach is evaluated using a combinatorial sequential scheduling problem and compared to traditionally object and component based approaches. We show, that using agents supports the development, by providing a better overview and thereby assist in handling the system complexity. With agents dependencies become visible and we obtain an impression at the phenomena of emergence. Emergence refers to occurrence of new structures or properties, resulting from the cooperation of single elements in a complex system. These structures are not directly obvious and only arise from the interaction between the elements of the system \cite{UP10}. The common endeavor of more or less specialized directives surpasses the accumulated capability of all individual system elements \cite{Fer99}. The Micro-Macro-problem from the domain of distributed artificial intelligence illustrates this challenge very well \cite{Hil99}. Well known emergent systems are ant colonies and particle swarms. They have been adapted for optimization problems. There are two basic approaches to model the cooperation and organization in agent systems. We employ the role model which, in contrast to the service model, relies on describing the capabilities of an agent to perform a task instead of binding a fixed task to an agent. Currently there is, however, no standardized concept for these architectures \def\citeauthoryear##1##2##3{##2, ##3}\@internalcite{RWL95,Usbeck10}. In Section 2 we describe the requirements we try to address using the MAS approach. Subsequently we provide a short overview of related work. In Section 4, we present our MAS concept. Section 5 and 6 outline the application area and the simulation-based optimization algorithms used for the evaluation in Section 7. \section{BACKGROUND AND RELATED WORK} There is a plethora of agent architectures, however not single standard has emerged so far. The most common architecture is called reference model, which describes the general construction of a MAS. This reference is provided by the FIPA, a nonprofit group of various companies. This working group deals with the communication, interaction and management of agents as well as transport of agent messages and interoperability with different network architectures. Other well known agent architectures include: BDI-Modell \def\citeauthoryear##1##2##3{##2, ##3}\@internalcite{Wooldridge99}, PAGE-Modell \cite{Russell09}, InteRRaP \def\citeauthoryear##1##2##3{##2, ##3}\@internalcite{Oluyomi} and ACT-R \cite{Anderson96}. These architectures focus mainly on the description of agents, while providing only little information considering the cooperation and organization of multiple agents. A common but not necessarily optimal approach is using hierarchical structure to manage agents \cite{Sch00}. Consequently one agent controls multiple helper agents, which unfortunately often leads to the occurrence of bottlenecks. The realized system FABMAS \def\citeauthoryear##1##2##3{##2, ##3}\@internalcite{Moench03} come close to our requirements and has strong influence on our design. But it has a hierarchical production control scheme. The system is also specific for semi conductor factories and maps their structure to the agent approach. The ideas in \cite{Yilamz09} describe a similar vision, but an implementation and feasibility evaluation are missing. We want to promote a flexible MAS with independent agents, focusing on cooperation instead of simple delegation. It is therefor mandatory that these intelligent agents exhibit autonomic behavior. For the interaction and communication, the agents use the agent communication language (ACL) from FIPA \cite{Ode11b}. This language is very abstract and it relies on a intricate ontology service \def\citeauthoryear##1##2##3{##2, ##3}\@internalcite{BCG07}. Based on the ACL, this paper presents a new concept to simplify and customize this aspect while keeping the flexibility. \section{REQUIREMENTS} Agents are used in many different application areas, e.g., in information retrieval for automatic filtering, in electronic commerce for transactions \cite{XJ11}, in network management systems to detect intrusions \cite{Golling13}, or in simulations of entire hospitals \cite{Her07}. Usually a MAS is used when a single agent cannot meet all necessary requirements. Generally, the most important requirements are the following: \begin{itemize} \item Handle complex systems and challenges in a practicable way, relying on emergence \cite{BZW98}. \item Guarantee flexibility by being extendible and adaptable, generally applicable, and platform independent. \item Provide a client-server environment for cluster systems enabling distributed calculation, parallelism, and dynamic load balancing. \end{itemize} Figure \ref{Abstract} presents the overall concept of our approach relying on agents on different levels. The interaction of generally applicable and specialized agents guarantees an extendible approach. \begin{figure}[htb] { \centering \includegraphics[width=0.6\textwidth]{fig/Abstract.png} \caption{Abstract architecture of the MAS.} \label{Abstract} } \end{figure} \section{SIMULATION AND ASSESSMENT} We put our concept to the test, using ``Lagoon'' a prototypic implementation to optimize a set of scheduling problems. We chose a set of test setups reflecting typical real world challenges (see Table \ref{test-setups}). The performance of the algorithms stagnate at around 10k simulation calls. \begin{table} [htbp] \begin{center} \caption{Parameters of test setups. } \label{test-setups} \begin{tabular}{|l!{\vrule width 1.0pt}r|} \hline \multicolumn{2}{|c|}{Test Setups} \\ \hline \hhline{--} Machines & 1..4\\ \hline Machine Types & uniform or mixed\\ \hline Job Count & 16..60\\ \hline Job Types & 3..10 recipes\\ \hline Simulation Calls & 1k, 10k or 100k\\ \hline Repetitions & 100\\ \hline \end{tabular} \end{center} \end{table} Figure \ref{fig: sim11} and \ref{fig: sim12} summarize the results of our study. For two of the test problems we were able to calculate an optimal solution using a distributed brute force approach for an adapted single machine test setup. Generally a Monte Carlo (MC) optimization approach serves as a reference. It simply tests a random candidate solution for each iteration. An effective approach should obviously return better results than repeatedly guessing a solution. \begin{figure}[htbp] \centering \begin{minipage}[b]{8,0 cm} \centering \includegraphics[width=1.00\textwidth]{fig/parallel_machines_1000.png} \caption{Simulation results using 1.000 iterations. machines.\label{fig: sim11}} \end{minipage} \quad \begin{minipage}[b]{8,0 cm} \centering \includegraphics[width=1.00\textwidth]{fig/parallel_machines_10000.png} \caption{Simulation results using 10.000 iterations. machines.\label{fig: sim12}} \end{minipage} \end{figure} As we expected our approaches exceeded the performance of MC. Random Down Swing (RDS) consistently provided the best results for all test setups when given enough calculation time (10k iterations). On the other hand the Central Complex method returned acceptable results with fewer iterations (1k). For test setup 5, a setup with a mixed set of machines and unequal quantity of job types, slightly outperformed RDS even for test using more iterations. Overall the quality of results was satisfying and came close to the optimum for the instances where brute force was used. In addition to the numerical results we did observe the expected advantages of an MAS. It enabled us to effectively distribute the processing across multiple servers (mixed architecture containing N servers), significantly shortening the calculation time. During the development process we successively added new features benefiting from the flexibility and extendability of the approach. We conclude our survey with a comparison of our approaches in contrast to the simplex method. Table \ref{tab1} and \ref{tab2} show typical results for this comparison -- both of them are comparable in complexity. The theoretical value for the simplex method results from the calculated simplex tableau. In contrast the practical value is reached when we construct an actual solution based on the tableau. For test setup 2 the simplex method clearly outperformed the other approaches, returning a better overall result while needing less computation time. Regarding test setup 1 however, the simplex method fell short. The practical result did not come close to the predicted theoretical value and it took a relatively large amount of time to generate the solution. For this scenario even MC outperformed the simplex approach while the best results were achieved by RDS. \begin{table}[hbtp] \centering \begin{minipage}[b]{7,8 cm} \caption{Simulation of test setup 2} \label{tab1} \begin{tabular}{|l !{\vrule width 1.0pt} r|r|r|r|} \hline \multicolumn{1}{|l !{\vrule width 1.0pt}}{Algorithms} & \multicolumn{1}{l|}{Max} & \multicolumn{1}{l|}{Mean} & \multicolumn{1}{l|}{Min} & \multicolumn{1}{l|}{Time} \\ \hline \hhline{-----} Simplex-theo. & - & 371 & - & - \\ \hline Simplex-prac. & - & 385 & - & 0.03 s\\ \hline MC & 417 & 405 & 388 & 0.25 s\\ \hline RDS & 413 & 394 & 379 & 0.25 s\\ \hline \end{tabular} \end{minipage} \qquad \begin{minipage}[b]{7,8 cm} \caption{Simulation of test setup 1} \label{tab2} \begin{tabular}{|l !{\vrule width 1.0pt} r|r|r|r|} \hline \multicolumn{1}{|l !{\vrule width 1.0pt}}{Algorithms} & \multicolumn{1}{l|}{Max} & \multicolumn{1}{l|}{Mean} & \multicolumn{1}{l|}{Min} & \multicolumn{1}{l|}{Time} \\ \hline \hhline{-----} Simplex-theo. & - & 365 & - & - \\ \hline Simplex-prac. & - & 421 & - & 26 s\\ \hline MC & 436 & 416 & 396 & 0.26 s\\ \hline RDS & 417 & 398 & 375 & 0.27 s\\ \hline \end{tabular} \end{minipage} \end{table} \section{CONCLUSION AND OUTLOOK} We reached a productive cooperation of agents without relying on a hierarchical structure or fixed grouping. The concept of role models supports the developer while organizing the intelligent agents. The combination of agents, role model and wrapped communication packages enables an orthogonal implementation of single components based on the model-view-control principle. Algorithms and other agents can be added to the MAS dynamically. Several users can send tasks to the MAS in parallel. We observed a reduction in layout complexity and improved control regarding complex systems. In contrast to traditional object-oriented and component-based approaches the agent concept is more flexible -- especially during runtime -- and supports distributed computation. Furthermore, the design of our MAS allows us to easily adapt it to various problem domains. This paper provides an approach that overcomes the biggest challenge of MAS, which is the need of an elaborate organization of agents. With regard to the scheduling domain our evaluation showed that computation intensive tasks can be solved efficiently using the developed MAS and the proposed simulation-based algorithms. Both RDS and CC algorithms reach reliably good results. \section*{ACKNOWLEDGMENTS} This work was partly funded by FLAMINGO, a Network of Excellence project (ICT-318488) supported by the European Commision under its Seventh Framework Programm.\\ \section*{\abstractname}} {\par} \newdimen\labelwidthi \newdimen\labelwidthii \settowidth{\labelwidthi}{M} \settowidth{\labelwidthii}{(d)} \leftmargini=1.2cm \leftmarginii=4ex \leftmarginii=4ex \def\@listi{\leftmargin\leftmargini \rightmargin0pt \parsep 0\p@ \topsep 10\p@ \itemsep0\p@} \let\@listI\@listi \@listi \def\@listii{\leftmargin\leftmarginii \rightmargin0pt \labelsep 1ex \parsep 0\p@ \topsep 0\p@ \itemsep0\p@} \let\@listII\@listii \@listii \def\@listiii{\leftmargin\leftmarginiii \rightmargin0pt \parsep 0\p@ \topsep 0\p@ \itemsep0\p@} \let\@listIII\@listiii \@listiii \labelsep=.25in \setlength \labelwidth{\leftmargini} \addtolength\labelwidth{-\labelsep} \renewcommand\labelenumi{\rlap{\rm\theenumi.}} \renewcommand\labelitemi{\rlap{\textbullet}} \def\@seccntformat#1{\hbox to .25in{\csname the#1\endcsname\hss}\relax} \def\@sect#1#2#3#4#5#6[#7]#8{% \ifnum #2>\c@secnumdepth \let\@svsec\@empty \else \refstepcounter{#1}% \protected@edef\@svsec{\@seccntformat{#1}\relax}% \fi \@tempskipa #5\relax \ifdim \@tempskipa>\z@ \begingroup #6{% \@hangfrom{\hskip #3\relax\@svsec}% \interlinepenalty \@M #8\@@par}% \endgroup \csname #1mark\endcsname{#7}% \addcontentsline{toc}{#1}{% \ifnum #2>\c@secnumdepth \else \protect\numberline{\csname the#1\endcsname}% \fi #7}% \else \def\@svsechd{% #6{\hskip #3\relax \@svsec #8}% \csname #1mark\endcsname{#7}% \addcontentsline{toc}{#1}{% \ifnum #2>\c@secnumdepth \else \protect\numberline{\csname the#1\endcsname}% \fi #7}}% \fi \@xsect{#5}} \deftable{table} \long\def\@makecaption#1#2{% \ifx\@captypetable \vskip3pt \else \vskip\abovecaptionskip\fi \sbox\@tempboxa{#1: #2}% \ifdim \wd\@tempboxa >\hsize #1: #2\par \else \global \@minipagefalse \hb@xt@\hsize{\hfil\box\@tempboxa\hfil}% \fi \vskip\belowcaptionskip} \renewcommand\section{\@startsection {section}{1}{\z@}% {-12pt}% {6pt}% {\hyphenpenalty10000\normalfont\normalsize\bfseries}} \renewcommand\subsection{\@startsection{subsection}{2}{\z@}% {-12pt}% {6pt}% {\normalfont\normalsize\hyphenpenalty10000\bfseries}} \renewcommand\subsubsection{\@startsection{subsubsection}{3}{\z@}% {-12pt} {6pt} {\normalfont\normalsize\hyphenpenalty10000\bfseries}} \let\savesubsub\subsubsection \def\subsubsection#1{\savesubsub{\ \ #1}} \parskip=0pt plus .01pt \let\saveparagraph\paragraph \def\paragraph#1{\vskip1sp {\bf #1}\hskip1em\relax} \raggedbottom \newenvironment{hangref}{\begin{list}{}{\setlength{\itemsep}{0pt} \setlength{\parsep}{0pt}\setlength{\rightmargin}{0pt} \setlength{\leftmargin}{+\parindent} \setlength{\itemindent}{-\parindent}}}{\end{list}} \newif\iftitle \def\@oddhead{\iftitle\global\titlefalse \vtop to0pt{\hbox to.9\textwidth{\titlepageheadfont Proceedings of the \currentYear{} Winter Simulation Conference\hfill}% \vskip2pt \hbox to .9\textwidth{\titlepageheadfont \currentEditors , eds.\hfill}% \vss} \else \hbox to\textwidth{\titlepageheadfont\hfill\thetitle\hfill}\fi} \def\@evenhead{\iftitle\global\titlefalse\fi% \hbox to \textwidth{\hss\titlepageheadfont \theauthors\hss}} \let\@oddfoot\relax \let\@evenfoot\@oddfoot \def\ttitle#1{\gdef\thetitle{#1}} \def\vskip12pt{\vskip12pt} \let\vs\vskip12pt \def\bd{\vskip2pt\noindent} \spaceskip=3.5pt plus 2pt minus2pt \parindent=.25in \hfuzz=1pt \widowpenalty=10000 \clubpenalty=10000 \def\verbatim{\spaceskip=0pt \@verbatim \frenchspacing\@vobeyspaces \@xverbatim} \newcommand\smscriptsize{\@setfontsize\scriptsize\@vipt\@viipt} \def\def\@captype{figure}{\def\@captype{figure}} \let\endnofloatfigure\relax \def\def\@captype{table}{\def\@captype{table}} \let\endnofloattable\relax \newcount\itemcount \def\spenumerate{\bgroup\leftskip=.25in \global\itemcount=0 \def\item{\global\advance\itemcount by 1 \vskip1sp \noindent\hskip-.25in\hbox to .25in{\the\itemcount.\hss}}} \def\vskip12pt\egroup{\vskip12pt\egroup} \newif\ifnoindent \def\@begintheorem#1#2{\vskip-12pt\vskip1sp \trivlist \item[\ifnoindent\global\noindentfalse\else \hskip.25in\fi\hskip \labelsep{\bfseries #1\ #2}]\itshape} \def\@opargbegintheorem#1#2#3{\vskip-12pt\vskip1sp \trivlist \item[\ifnoindent\global\noindentfalse\else\hskip.25in\fi% \hskip \labelsep{\bfseries #1\ #2\ (#3)}]\itshape} \def\@endtheorem{\vskip1sp} \newlength{\bibhang} \setlength{\bibhang}{2em} \newdimen\bibindent \bibindent=.25in \@ifundefined{refname}% {\@ifundefined{chapter}% {\newcommand{\refname}{References}}% {\newcommand{\refname}{Bibliography}}% }% {}% \def\thebibliography#1{\section*{\refname\@mkboth {\uppercase{\refname}}{\uppercase{\refname}}}\list {[\arabic{enumi}]}{\settowidth\labelwidth{[#1]} \rightmargin=0pt \leftmargin=0pt \leftmargin\labelwidth \advance\leftmargin\labelsep \advance\leftmargin\bibindent \advance\leftmargin-24pt \itemindent -\bibindent \listparindent \itemindent \parsep \z@ \usecounter{enumi}} \def{} \sloppy \sfcode`\.=1000\relax} \endinput \makeatletter \def\@lbibitem[#1]#2{\item[ \if@filesw {\let\protect\noexpand\immediate\write\@auxout{ \string\bibcite {#2}{#1}}}\fi\ignorespaces} \def\@cite#1#2{{#1\if@tempswa , #2\fi}} \makeatother \def\Box{\vbox to 6pt{\hrule \hbox{\vrule height 4.8pt \hskip 4.8pt \vrule } \hrule}} \end{filecontents*} \begin{filecontents*}{wscbib.tex} \makeatletter \let\@internalcite\cite \def\cite{\def\@citeseppen{-1000}% \def\@cite##1##2{(##1\if@tempswa , ##2\fi)}% \def\citeauthoryear##1##2##3{##1 ##3}\@internalcite} \def\citeNP{\def\@citeseppen{-1000}% \def\@cite##1##2{##1\if@tempswa , ##2\fi}% \def\citeauthoryear##1##2##3{##1 ##3}\@internalcite} \def\citeN{\def\@citeseppen{-1000}% \def\@cite##1##2{##1\if@tempswa, ##2)\else{}\fi}% \def\citeauthoryear##1##2##3{##1 (##3)}\@citedata} \def\citeA{\def\@citeseppen{-1000}% \def\@cite##1##2{(##1\if@tempswa , ##2\fi)}% \def\citeauthoryear##1##2##3{##1}\@internalcite} \def\citeANP{\def\@citeseppen{-1000}% \def\@cite##1##2{##1\if@tempswa , ##2\fi}% \def\citeauthoryear##1##2##3{##1}\@internalcite} \def\def\citeauthoryear##1##2##3{##2, ##3}\@internalcite{\def\@citeseppen{-1000}% \def\@cite##1##2{(##1\if@tempswa , ##2\fi)}% \def\citeauthoryear##1##2##3{##2 ##3}\@internalcite} \def\shortciteNP{\def\@citeseppen{-1000}% \def\@cite##1##2{##1\if@tempswa , ##2\fi}% \def\citeauthoryear##1##2##3{##2 ##3}\@internalcite} \def\shortciteN{\def\@citeseppen{-1000}% \def\@cite##1##2{##1\if@tempswa, ##2\else{}\fi}% \def\citeauthoryear##1##2##3{##2 (##3)}\@citedata} \def\def\citeauthoryear##1##2##3{##2}\@internalcite{\def\@citeseppen{-1000}% \def\@cite##1##2{(##1\if@tempswa , ##2\fi)}% \def\citeauthoryear##1##2##3{##2}\@internalcite} \def\shortciteANP{\def\@citeseppen{-1000}% \def\@cite##1##2{##1\if@tempswa , ##2\fi}% \def\citeauthoryear##1##2##3{##2}\@internalcite} \def\def\citeauthoryear##1##2##3{##3}\@internalcite{\def\@citeseppen{-1000}% \def\@cite##1##2{(##1\if@tempswa , ##2\fi)}% \def\citeauthoryear##1##2##3{##3}\@citedata} \def\citeyearNP{\def\@citeseppen{-1000}% \def\@cite##1##2{##1\if@tempswa , ##2\fi}% \def\citeauthoryear##1##2##3{##3}\@citedata} \def\@citedata{% \@ifnextchar [{\@tempswatrue\@citedatax}% {\@tempswafalse\@citedatax[]}% } \def\@citedatax[#1]#2{% \if@filesw\immediate\write\@auxout{\string\citation{#2}}\fi% \def\@citea{}\@cite{\@for\@citeb:=#2\do% {\@citea\def\@citea{, }\@ifundefine {b@\@citeb}{{\bf ?}% \@warning{Citation `\@citeb' on page \thepage \space undefined}}% {\csname b@\@citeb\endcsname}}}{#1}}% \def\@citex[#1]#2{% \if@filesw\immediate\write\@auxout{\string\citation{#2}}\fi% \def\@citea{}\@cite{\@for\@citeb:=#2\do% {\@citea\def\@citea{, }\@ifundefine {b@\@citeb}{{\bf ?}% \@warning{Citation `\@citeb' on page \thepage \space undefined}}% {\csname b@\@citeb\endcsname}}}{#1}}% \def\@biblabel#1{} \makeatother \newdimen\bibindent \bibindent=0.0em \def\thebibliography#1{\section*{\refname}\list {}{\settowidth\labelwidth{[#1]} \leftmargin\parindent \itemindent -\parindent \listparindent \itemindent \itemsep 0pt \parsep 0pt} \def{} \sloppy \sfcode`\.=1000\relax} \end{filecontents*} \section*{\refname\@mkboth \def\thebibliography#1{\section*{\refname}\list {}{\settowidth\labelwidth{[#1]} \leftmargin\parindent \itemindent -\parindent \listparindent \itemindent \itemsep 0pt \parsep 0pt} \def{} \sloppy \sfcode`\.=1000\relax}
{'timestamp': '2020-04-21T02:27:34', 'yymm': '2004', 'arxiv_id': '2004.09312', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09312'}
arxiv
\section*{Data availability} The code used for the analysis and to generate the synthetic data is publicly available and can be found at \url{https://github.com/mcontisc/MTCOV}. \section*{Acknowledgements} This work was partially supported by the Cyber Valley Research Fund. The authors thank the International Max Planck Research School for Intelligent Systems (IMPRS-IS) for supporting Martina Contisciani. The authors are grateful for the goodwill of the residents of Te\underline{n}pa\d{t}\d{t}i and A\underline{l}ak\={a}puram, the support of faculty and students from the Folklore Department at Madurai Kamaraj University, and the assistance of the Chella Meenakshi Centre for Educational Research and Services. Funding for fieldwork was provided by the US National Science Foundation Doctoral Dissertation Improvement grant (no. BCS-1121326), a Fulbright-Nehru Student Researcher Award, the Stanford Center for South Asia, and a National Science Foundation Interdisciplinary Behavioral \& Social Science Research grant (no. IBSS-1743019). We thank Cristopher Moore and Daniel Larremore for useful discussions and the Santa Fe Institute for providing the environment fostering these interactions. \bibliographystyle{apsrev4-1} \subsection*{Results on single-layer networks} Our model can be used for single-layer networks as well. For these we can compare against two state-of-the-art algorithms, both probabilistic generative models but different in their assumptions: \mbox{{\small CESNA}} \cite{yang2013community} which considers overlapping communities and posits two independent Bernoulli distributions for network edges and node attributes; and the model proposed by Newman and Clauset \cite{newman2016structure} (\mbox{{\small NC}}) for non-overlapping communities, a Bayesian approach where the priors on the community memberships depend on the node attributes. \mbox{{\small CESNA}}, similarly to our model, assumes conditional independence of the two likelihoods and introduces a regularization parameter between them; it uses block-coordinate ascent for parameters' estimation, while \mbox{{\small NC}}\text{} uses an EM algorithm for parameters' estimation, similarly to what we do here. We test \mbox{{\small MTCOV}}\text{} against them on both synthetic and real single-layer networks with node attributes, with and without ground-truth. We transform directed networks to undirected because both \mbox{{\small CESNA}}\text{} and \mbox{{\small NC}}\text{} do not distinguish for edge directionality. Results on synthetic data show that \mbox{{\small MTCOV}}\text{} and \mbox{{\small NC}}\text{} have similar performance in correctly classifying nodes in their ground-truth communities and both are better than \mbox{{\small CESNA}}; the main difference is that \mbox{{\small MTCOV}}\text{} is more stable and has less variance for high attribute correlation, in particular in the hard regime where classification is more difficult. We leave details in the Supplementary Section S3. For single-layer real networks, we use datasets with ground-truth candidates and node attributes: the ego-Facebook network\cite{facebook} (\textit{facebook}), a set of 21 networks built from connections between a person's friends where potential ground-truth are circles of friends hand-labeled by the ego herself; the American College football network (\textit{football}) \cite{football}, a network of football teams playing against each other, where a ground-truth candidate is the conference to which each team belongs; and a network of political blogs \cite{polblogs} (\textit{polblogs}) where potential ground-truth communities are divided by \textit{left/liberal} and \textit{right/conservative} political parties, see Supplementary Section S3 for details. For each network, we run a 5-fold cross-validation procedure combined with grid-search for fixing the hyperparameter $\gamma$. For \textit{facebook} we find that the average over the 21 networks is $\gamma=0.15$, which signals a low correlation between the covariates and the communities, whereas for the \textit{football} and \textit{polblogs} networks we obtain much higher values of $\gamma$ equal to $0.6$ and $0.75$ respectively. \mbox{{\small MTCOV}}\text{} has better performance in terms of F1-score and Jaccard similarity across the majority of datasets, as shown in Table \ref{tab: single-layer}. This is also supported by a trial-by-trial comparison shown in Fig. \ref{fig: single-layer1} for F1-score (similar results are obtained for Jaccard), where we find that \mbox{{\small MTCOV}}\text{} is more accurate in $59\%$ and $90\%$ of the cases than \mbox{{\small NC}}\text{} and \mbox{{\small CESNA}}, respectively. \begin{table}[] \centering \renewcommand{\arraystretch}{1.2} {\begin{tabular}{lccc|ccc} \clineB{1-7}{3} \multicolumn{1}{c}{\textbf{}} & \multicolumn{3}{c|}{\textbf{F1-score}} & \multicolumn{3}{c}{\textbf{Jaccard similarity}} \\ \multicolumn{1}{l|}{\textbf{Method}} & \textbf{facebook} & \textbf{football} & \textbf{polblogs} & \textbf{facebook} & \textbf{football} & \textbf{polblogs} \\ \hline \multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & \textbf{0.5$\pm$0.1} & \textbf{0.86$\pm$0.03} & 0.8$\pm$0.2 & \textbf{0.4$\pm$0.1} & \textbf{0.82$\pm$0.04} & 0.8$\pm$0.2 \\ \multicolumn{1}{l|}{\mbox{{\small NC}}} & 0.48$\pm$0.08 & 0.82$\pm$0.06 & \textbf{0.95$\pm$0.09} & 0.36$\pm$0.08 & 0.75$\pm$0.08 & \textbf{0.9$\pm$0.1} \\ \multicolumn{1}{l|}{\mbox{{\small CESNA}}} & 0.46$\pm$0.09 & 0.7$\pm$0.0 & 0.6$\pm$0.0 & 0.33$\pm$0.08 & 0.6$\pm$0.0 & 0.4$\pm$0.0 \\ \clineB{1-7}{3} \end{tabular}} \caption{Performance of methods \mbox{{\small MTCOV}}, \mbox{{\small NC}}\text{} and \mbox{{\small CESNA}}\text{} on three datasets, according to two different measures used in the equation (\ref{eq: validation}). The results are averages and standard deviations over ten independent runs and the best outcomes are bolded. } \label{tab: single-layer} \end{table} \begin{figure}[] \centering \includegraphics[width=0.7\linewidth]{./Figures/single_layers_nets_mtcov_nc_cesna} \caption{Trial-by-trial performance in F1-score. We compare \mbox{{\small MTCOV}}\text{} on the y-axis, with on the x-axis (left) \mbox{{\small NC}}\text{} and (right) \mbox{{\small CESNA}}. Markers denote the datasets: squares for \textit{facebook}, triangles for \textit{football} and circles for \textit{polblogs}. Points above the diagonal, shown in red, are trials where \mbox{{\small MTCOV}}\text{} is more accurate than the other. The fractions for which each method is superior are shown in the plot legend. } \label{fig: single-layer1} \end{figure} \section{Methods: EM detailed derivation} \label{apx:EMderivation} We show derivations of the updates given in equations ({\color{red} 12})-({\color{red} 15}) of the main manuscript. The partial derivative with respect to the elements of the affinity matrices $W^{(\alpha)}$ is given by \begin{align} \label{der_w} \frac{\partial \mathcal{L}}{\partial w_{kl}^{(\alpha)}}= (1-\gamma)\frac{\partial \mathcal{L}_G}{\partial w_{kl}^{(\alpha)}} = (1-\gamma)\sum_{i,j} \bigg[\frac{A_{ij}^{(\alpha)} \rho_{ijkl}^{(\alpha)}}{w_{kl}^{(\alpha)}}-u_{ik}v_{jl}\bigg]. \end{align} The valid update when $\gamma$ is different from 1, is given by setting equation (\ref{der_w}) to zero and we obtain \begin{align} \label{eq:w} w_{kl}^{(\alpha)} = \frac{\sum_{i,j} A_{ij}^{(\alpha)} \rho_{ijkl}^{(\alpha)}}{\sum_i u_{ik} \sum_j v_{jl}}. \end{align} In order to take the derivative with respect to $\beta_{kz}$ we need to consider the Lagrange multiplier $\lambda_k^{(\beta)}$ because of the constraint in equation ({\color{red} 11}). Then, \begin{align} \frac{\partial \mathcal{L}}{\partial \beta_{kz}} = \gamma \, \bigg( \frac{1}{\beta_{kz}} \sum_{i} x_{iz} h_{izk}\bigg) - \lambda_k^{(\beta)} \quad, \end{align} and setting it to zero implies \begin{align} \label{eq:b} \beta_{kz} = \frac{\gamma}{\lambda_k^{(\beta)}} \sum_{i} x_{iz} h_{izk} \quad . \end{align} Enforcing the constraint ({\color{red} 11}), we have \begin{align} \sum_z \frac{\gamma}{\lambda_k^{(\beta)}} \sum_{i} x_{iz} h_{izk}= 1 \ \ , \end{align} which implies \begin{align} \label{eq:lambda} \lambda_k^{(\beta)} = \gamma \sum_{i,z} x_{iz} h_{izk} \quad. \end{align} Plugging (\ref{eq:lambda}) into (\ref{eq:b}), we obtain the update: \begin{align} \label{eq:beta} \beta_{kz} = \frac{\sum_{i} x_{iz} h_{izk}}{\sum_{i,z} x_{iz} h_{izk}} \quad. \end{align} Focusing the attention on the elements of the matrix $U$, we first consider that plugging the update for $w_{kl}^{(\alpha)}$ given in equation (\ref{eq:w}) into the log-likelihood of the structural dimension $\mathcal{L}_{G}$, the last term becomes a constant. Indeed, \begin{align} \nonumber - \sum_{i,j}\sum_{k,l}u_{ik}v_{jl}\frac{\sum_{i,j} A_{ij}^{(\alpha)} \rho_{ijkl}^{(\alpha)}}{\sum_i u_{ik} \sum_j v_{jl}} &= - \sum_{k,l}\bigg(\frac{\sum_{i,j} A_{ij}^{(\alpha)} \rho_{ijkl}^{(\alpha)}}{\sum_i u_{ik} \sum_j v_{jl}} \sum_{i,j}u_{ik}v_{jl}\bigg)\\ \nonumber &= - \sum_{k,l}\bigg(\sum_{i,j} A_{ij}^{(\alpha)} \rho_{ijkl}^{(\alpha)}\bigg)\\ \nonumber &= - \sum_{i,j} A_{ij}^{(\alpha)} \sum_{k,l} \rho_{ijkl}^{(\alpha)}\\ \nonumber &= - \sum_{i,j} A_{ij}^{(\alpha)} \\ &= - T^{(\alpha)} \end{align} since $\sum_{k,l} \rho_{ijkl}^{(\alpha)}=1$ and $\sum_{i,j} A_{ij}^{(\alpha)}$ is the number of links in layer $\alpha$ when the network is directed (or twice this value in the undirected case). Thus, we can ignore this term when estimating $u_{ik}$. Using the same strategy used in computing the update of $\beta$, we compute the Lagrange multiplier $\lambda_i^{(u)}$ for the constraint in equation ({\color{red} 11}). Then, \begin{align} \frac{\partial \mathcal{L}}{\partial u_{ik}} = \frac{1}{u_{ik}}\bigg(\gamma \sum_z x_{iz} h_{izk} + (1-\gamma) \sum_{j,l,\alpha}A_{ij}^{(\alpha)} \rho_{ijkl}^{(\alpha)}\bigg) - \lambda_i^{(u)} \end{align} and \begin{align} \label{eq:u} u_{ik} = \frac{1}{\lambda_i^{(u)}}\bigg(\gamma \sum_z x_{iz} h_{izk} + (1-\gamma) \sum_{j,l,\alpha}A_{ij}^{(\alpha)} \rho_{ijkl}^{(\alpha)}\bigg) . \end{align} Enforcing the constraint $\sum_{k} u_{ik}=1$ yields: \begin{align} \sum_k \frac{1}{\lambda_i^{(u)}}\bigg(\gamma \sum_z x_{iz} h_{izk} + (1-\gamma) \sum_{j,l,\alpha}A_{ij}^{(\alpha)} \rho_{ijkl}^{(\alpha)}\bigg) = 1 \end{align} which implies \begin{align} \nonumber \lambda_i^{(u)} &= \sum_k\bigg(\gamma \sum_z x_{iz} h_{izk} + (1-\gamma) \sum_{j,l,\alpha}A_{ij}^{(\alpha)} \rho_{ijkl}^{(\alpha)}\bigg)\\ \label{eq:delta} &= \gamma + (1-\gamma) \sum_{j,\alpha}A_{ij}^{(\alpha)} \ \ , \end{align} since $\sum_{k} h_{izk}=1$, $\sum_{k,l} \rho_{ijkl}^{(\alpha)}=1$ and $\sum_{z} x_{iz}=1$. Plugging the result of equation (\ref{eq:delta}) into the equality (\ref{eq:u}) we obtain \begin{align} \label{eq:u2} u_{ik} = \frac{\gamma \sum_z x_{iz} h_{izk} + (1-\gamma) \sum_{j,l,\alpha}A_{ij}^{(\alpha)} \rho_{ijkl}^{(\alpha)}}{ \gamma + (1-\gamma) \sum_{j,\alpha}A_{ij}^{(\alpha)}} . \end{align} In order to compute the update for $V$, we fix $j$ and $l$, rewriting the attribute dimension $\mathcal{L}_{X}(U,V,\beta,h)$ as \begin{align} \mathcal{L}_{X}(U,V,\beta,h)=\sum_{j,z,l} x_{jz} (h_{jzl}\,\text{log}(\beta_{lz} (u_{jl}+v_{jl})) - h_{jzl}\,\text{log}(h_{jzl}) ). \end{align} Analogously to before, we consider the Lagrange multiplier to satisfy the constraint given in equation ({\color{red} 11}), and we obtain \begin{align} \label{eq:v} v_{jl} = \frac{\gamma \sum_z x_{jz} h_{jzl} + (1-\gamma) \sum_{i,k,\alpha}A_{ij}^{(\alpha)} \rho_{ijkl}^{(\alpha)}}{ \gamma + (1-\gamma) \sum_{i,\alpha}A_{ij}^{(\alpha)}} . \end{align} In each iteration of the EM algorithm, the parameters in $\Theta = ({U,V, W,\beta})$ are updated with equations (\ref{eq:w}), (\ref{eq:beta}), (\ref{eq:u2}) and (\ref{eq:v}), until the log-likelihood $\mathcal{L}(\Theta, h,\rho)$ reaches a fixed point. \section{Multilayer social support network of rural Indian villages} \label{apx: multi_real_data} \subsection{Normalization} \label{apx: normalization} A way to control the magnitude of the likelihood terms is rescaling each term individually. Here, we estimate two linear regression models in order to obtain the normalization constants for the two terms. Given the access to several network datasets of the same kind (social support networks in Indian villages), we collect log-likelihood values with respect to the number of nodes ($N$), edges ($E$) of the observed network and the number of categories of the categorical attribute ($Z$). Quantitatively, this means normalizing as: \begin{align} \label{normalization_eq} \mathcal{L} = (1-\gamma)\frac{\mathcal{L}_G}{c^G_N N+c^G_E E+c^G_Z Z} + \gamma \frac{\mathcal{L}_X}{c^X_N N+c^X_E E+c^X_Z Z}. \end{align} The super and the subscripts of the $c$ parameters indicate the dependent variable ($\mathcal{L}_X$ or $ \mathcal{L}_G$) and the input regressor they refer to, respectively. In particular, we collect the data by running the model for each pair of network and categorical attribute, arbitrarily fixing the number of communities $C=3$ and the scaling parameter $\gamma=0.5$. Table \ref{tab: Estimation} states the values of the statistically significant coefficients for the estimation of the log-likelihood terms, and only those coefficients are used in the normalized equation (\ref{normalization_eq}). \begin{table}[ht] \centering \resizebox{0.3\textwidth}{!}{ \renewcommand\arraystretch{1.25} \begin{tabular}{ccc} \clineB{1-3}{3} \textbf{} & \textbf{$\mathcal{L}_X$} & \textbf{$\mathcal{L}_G$} \\ \hline $c_N$ & $-0.486^{***} $ & $-1.778^{**} $ \\ $c_E$ & & $-6.158^{***} $ \\ $c_Z$ & $-33.862^{***}$ & \\ \clineB{1-3}{3} \end{tabular}} \caption{Coefficient estimates $c^X_N$, $c^X_E$, $c^X_Z$, $c^G_N$, $c^G_E$ and $c^G_Z$ for the two linear regression models.} \label{tab: Estimation} \end{table} On one side, this procedure allows to obtain coefficient estimates useful for analyzing all four networks of Indian villages in a quantitative and automatized way. On the other side, we are aware that these coefficients are strictly related to the type of network we are working with, i.e. their values cannot be used in network datasets other than the social support networks used here. Future works should investigate an automated normalization procedure applicable to any network dataset as a pre-processing step. \subsection{Hyperparameter fitting} \label{apx: hyperparameters} \begin{table}[h!] \centering \resizebox{0.8\textwidth}{!}{ \renewcommand\arraystretch{1.25} \begin{tabular}{ll|cccc} \clineB{1-6}{3} \multicolumn{1}{c}{\textbf{}} &\multicolumn{1}{c}{\textbf{}} &\multicolumn{4}{c}{\textbf{Hyperparameters setting}} \\ \multicolumn{1}{l}{\textbf{Attribute}} &\multicolumn{1}{l|}{\textbf{Method}} & \textbf{Ala 2013} & \textbf{Ala 2017} & \textbf{Ten 2013} & \textbf{Ten 2017} \\ \hline \multicolumn{1}{l}{\textbf{}}&\multicolumn{1}{l|}{\mbox{{\small MULTITENSOR}}}& $C=8$ & $C=9$ & $C=3$& $C=3$\\ \multirow{1}{*}{Caste} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & $C=7$, $\gamma=0.8$ & $C=7$, $\gamma=0.8$ & $C=6$, $\gamma=0.8$&$C=6$, $\gamma=0.9$\\ \multirow{1}{*}{Religion} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } &$C=6$, $\gamma=0.8$ &$C=6$, $\gamma=0.8$ & $C=6$, $\gamma=0.7$ & $C=6$, $\gamma=0.7$ \\ \multirow{1}{*}{Age} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & $C=8$, $\gamma=0.4$ & $C=8$, $\gamma=0.3$ & $C=9$, $\gamma=0.2$ & $C=7$, $\gamma=0.3$\\ \multirow{1}{*}{Gender} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & $C=10$, $\gamma=0.8$ & $C=10$, $\gamma=0.7$ & $C=10$, $\gamma=0.4$ & $C=9$, $\gamma=0.7$\\ \clineB{1-6}{3} \end{tabular}} \caption{Values of the hyperparameters $C$ and $\gamma$ extracted by 5-fold cross-validation combined with grid-search.} \label{tab: estimates} \end{table} \subsection{Biased link prediction} \label{apx: biased_tpe} We use sampling bias techniques for assigning higher or lower sampling probability to the entries of the adjacency tensor, which correspond to edges and non-edges. By defining \textit{tpe} the total probability of selecting one edge (non-zero entry), we assign to the entries $a_{ij}^{(\alpha)}>0$ the probability of being selected in the test set given by: \begin{align} p_1 = \frac{\textit{tpe}}{E} \ \ , \end{align} and for $0$ entries \begin{align} p_2 =\frac{1- \textit{tpe}}{N^{2}\, L - E} \ \ , \end{align} where $E$ and $N^2\, L$ are the total number of the edges and entries of the adjacency tensor respectively. These two probabilities are assigned to the entries $a_{ij}^{(\alpha)}$ for performing a biased selection while choosing test and train sets, as in a selection of a binary mask. The \textit{tpe} is used to select entries for the test set; in case of selecting entries uniformly at random, this value would be around $0.004$. This low value is due to the common case in real networks of having sparse matrices, where the number of non-zero entries is much lower than the number of zeros. We create three different situations, starting from $tpe =0.001$ where the probability of selecting one edge is lower than the probability of choosing one non edge, and the number of edges in the training set is much higher than the number in the test set. Then we have $tpe =0.015$ and finally $tpe =0.03$, where the probability of selecting one edge in the test set is higher than the probability of choosing one non edge, and the test set has a bigger number of positive examples. These settings follow an increasing order of complexity, starting from an under-represented case, where $tpe=0.001$, and ending with a difficult task where the number of edges in the test set is over-represented, $tpe=0.03$. We run 10 independent trials for each setting and model. \begin{table}[ph!] \centering \resizebox{0.9\textwidth}{!}{ \renewcommand\arraystretch{1.25} \begin{tabular}{cll|cccc} \clineB{1-7}{3} \multicolumn{1}{c}{\textbf{}} &\multicolumn{1}{c}{\textbf{}} &\multicolumn{1}{c}{\textbf{}} &\multicolumn{4}{c}{\textbf{AUC for link prediction}} \\ \multicolumn{1}{l}{\textbf{Edge bias sampling}} &\multicolumn{1}{l}{\textbf{Attribute}} &\multicolumn{1}{l|}{\textbf{Method}} & \textbf{Ala 2013} & \textbf{Ala 2017} & \textbf{Ten 2013} & \textbf{Ten 2017} \\ \hline \multirow{4}{*}{$tpe=0.001$} & &\multicolumn{1}{l|}{\mbox{{\small MULTITENSOR}}}& 0.82$\pm$0.01 & 0.85$\pm$0.01 &0.78$\pm$0.02&0.82$\pm$0.02\\ &\multirow{1}{*}{Caste} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & \textbf{0.851$\pm$0.008} & \textbf{0.87$\pm$0.01}&\textbf{0.85$\pm$0.01}&\textbf{0.83$\pm$0.02}\\ &\multirow{1}{*}{Religion} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & 0.82$\pm$0.02 & 0.85$\pm$0.02 & 0.83$\pm$0.02 & 0.83$\pm$0.01\\ &\multirow{1}{*}{Age} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & 0.83$\pm$0.01 & 0.83$\pm$0.01& 0.81$\pm$0.02 &0.821$\pm$0.009\\ &\multirow{1}{*}{Gender} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } &0.81$\pm$0.02 &0.85$\pm$0.02&0.83$\pm$0.01&0.82$\pm$0.01\\ \clineB{1-7}{3} \multirow{4}{*}{$tpe=0.004$} & &\multicolumn{1}{l|}{\mbox{{\small MULTITENSOR}}}& 0.771$\pm$0.009 & 0.835$\pm$0.006 &0.758$\pm$0.005&0.81$\pm$0.01\\ &\multirow{1}{*}{Caste} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & \textbf{0.846$\pm$0.007} & \textbf{0.865$\pm$0.006} &\textbf{0.838$\pm$0.006}&\textbf{0.82$\pm$0.01}\\ &\multirow{1}{*}{Religion} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & 0.816$\pm$0.009 & 0.83$\pm$0.01 &0.81$\pm$0.01& 0.82$\pm$0.01\\ &\multirow{1}{*}{Age} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & 0.82$\pm$0.01 & 0.83$\pm$0.01 & 0.791$\pm$0.009 &0.79$\pm$0.02\\ &\multirow{1}{*}{Gender} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & 0.790$\pm$0.007& 0.83$\pm$0.02& 0.81$\pm$0.01&0.82$\pm$0.02\\ \clineB{1-7}{3} \multirow{4}{*}{$tpe=0.015$} & &\multicolumn{1}{l|}{\mbox{{\small MULTITENSOR}}} & 0.62$\pm$0.01 & 0.73$\pm$0.01 &0.68$\pm$0.01&0.76$\pm$0.01\\ &\multirow{1}{*}{Caste} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & \textbf{0.806$\pm$0.008} &\textbf{0.847$\pm$0.006} &\textbf{0.811$\pm$0.007}&\textbf{0.812$\pm$0.006}\\ &\multirow{1}{*}{Religion} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & 0.76$\pm$0.01 &0.81$\pm$0.01 &0.75$\pm$0.01&0.78$\pm$0.01 \\ &\multirow{1}{*}{Age} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & 0.68$\pm$0.01 & 0.77$\pm$0.02 & 0.68$\pm$0.02 &0.74$\pm$0.03\\ &\multirow{1}{*}{Gender} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } &0.71$\pm$0.01 &0.79$\pm$0.02&0.70$\pm$0.01& 0.76$\pm$0.02\\ \clineB{1-7}{3} \multirow{4}{*}{$tpe=0.03$} & &\multicolumn{1}{l|}{\mbox{{\small MULTITENSOR}}}& 0.46$\pm$0.01 & 0.554$\pm$0.009 &0.55$\pm$0.01&0.63$\pm$0.01\\ &\multirow{1}{*}{Caste} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & \textbf{0.73$\pm$0.01} &\textbf{0.79$\pm$0.01}&\textbf{0.760$\pm$0.008}&\textbf{0.77$\pm$0.01}\\ &\multirow{1}{*}{Religion} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & 0.68$\pm$0.02 &0.74$\pm$0.02 &0.64$\pm$0.02 &0.68$\pm$0.01\\ &\multirow{1}{*}{Age} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & 0.54$\pm$0.02 & 0.63$\pm$0.02 & 0.54$\pm$0.01 &0.61$\pm$0.02\\ &\multirow{1}{*}{Gender} &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } &0.58$\pm$0.01 &0.66$\pm$0.02&0.55$\pm$0.02& 0.65$\pm$0.01\\ \clineB{1-7}{3} \end{tabular}} \caption{Prediction performance on real multilayer networks with attributes and bias sampling on edges. Results are averages and standard deviations over 10 independent trials of cross-validation with 80-20 splits applied to the entries of $A$ (the whole $X$ is given in input); best performances are in boldface. Datasets are described in the main manuscript.} \label{tab: bias} \end{table} \section{Single-layer networks experiments} \label{apx: single_data} We generate 10 independent realization with different random initializaton for each network. We run \mbox{{\small NC}}\text{} setting the maximum number of BP steps before aborting to 40 and maximum number of EM steps before aborting to 500 to be consistent with \mbox{{\small MTCOV}}. \mbox{{\small MTCOV}}\text{} and \mbox{{\small CESNA}}\text{} use the fraction match as weight between the network and attributes. Moreover, for \mbox{{\small CESNA}}\text{} we add a new community with all non-classified nodes, and this is done for all tests. Therefore, \mbox{{\small NC}}\text{} and \mbox{{\small MTCOV}}\text{} give the possibility to decide if considering a hard membership or a mixed one, thanks to the posterior probabilities given as output, and assigning the community with the highest probability, even though \mbox{{\small NC}}\text{} doesn't mention the possibility of mixed-membership in the paper. On the other hand, \mbox{{\small CESNA}}\text{} does not return those values, and we have to work with their output files which provide an overlapping partition of the nodes. \subsection{Single-layer synthetic networks} In analogy with what done for multilayer synthetic networks, we test \mbox{{\small MTCOV}} 's ability to detect communities on synthetic single-layer networks, using the approach proposed by Newman and Clauset\cite{newman2016structure}, where they generate synthetic networks with known community structure embedded within them. Networks are generated using the stochastic block model\cite{holland1983stochastic, karrer2011stochastic}, with $N=1000$ nodes and $C=2$ non-overlapping communities of equal size. Edge probabilities are $p_{in} = c_{in}/n$ and $p_{out} = c_{out}/n$, for within-group and between-group edges, respectively. The difference $c_{in}-c_{out}$ measures the strength of the community structure, when $c_{in}$ is much greater than $c_{out}$ the communities are easy to detect from network structure alone, and it becomes harder when these two quantities are close. Discrete-valued attributes are generated on nodes, which match the true community assignments of nodes a given fraction of the times, and are instead chosen uniformly at random from the non-matching values otherwise. This allows to control the correlation between attributes and community structure and hence test the algorithm's ability to exploit the extra information of varying quality. The match between attributes and planted communities varies between $0.5$ and $0.9$, the higher this value the higher the extent to which node attributes help predicting edges. In Fig. \ref{fig:synthetic} we show the fraction of correctly classified nodes in terms of F1-score (results in terms of Jaccard are similar) for such experiments. We notice first a clear pattern where all the methods increase their performance and reduce their variance as the difference $c_{in}-c_{out}$ gets bigger, going from a hard to an easy to detect regime. In the hard regime, where community structure weakens, both \mbox{{\small MTCOV}}\text{} and \mbox{{\small NC}}\text{} remain robust in detecting the communities for scenarios where attributes are correlated. However, \mbox{{\small MTCOV}}\text{} shows lower variance and has more stable results for high attribute correlations. In addition, empirically we observe that \mbox{{\small NC}}\text{} does not reach converge in $19\%$ of the trials, while \mbox{{\small MTCOV}}\text{} only for the $13\%$ of the times. \mbox{{\small CESNA}}\text{} always shows lower performances, probably penalized by the relative high number of non classified examples which we also observe experimentally. \begin{figure}[] \centering \includegraphics[width=\linewidth]{./Figures/val_mean_perc_f1} \caption{Accuracy of classification for synthetic single-layer networks with two communities of equal size, generated with the stochastic block model. Each plot shows results with a given match between metadata and planted communities. The results are averaged over 10 independent trials and the bars represent the standard deviation. The accuracy is measured with F1-score as similarity measure. } \label{fig:synthetic} \end{figure} \subsection{Single-layer real networks} \paragraph{The \textit{facebook} ego-networks} We consider the attributes \textit{Birthday (B), Hometown (H)} and \textit{Location (L)}, relationship that potentially correlate with the community partitions. In addition, they have a reasonable number of values, compared to other attributes whose proportions of missing values are too high. We take in consideration also the sum by row: since we are assuming a multinomial distribution for the attribute, we ask for a sum by row equal to 1. As first step, we combine all the 10 ego networks merging both the edges and the covariates. In this way we double check the real number of edges and the number of nodes. Moreover, we build complete design matrices for B, H and L. They are used for retrieving the largest possible number of attributes for each node. However, we decide to work with the ego networks separately, for having a clear classification of the ground truth. We build the input files using the following procedure, where we consider only the nodes having at least one edge and the attribute. We obtain 30 networks: 3 for each ego network according to the attribute B, H or L; and for each combination of ego and attribute we have different adjacency matrix $A$ and ground truth $circles$. However, we analyse 21 networks because we have to discard three ego networks (3437, 3980, 698) due to the null number of communities or to the small number of nodes with ground truth. \paragraph{American College Football} We use the corrected version of the dataset\cite{football_corrected}, where among all they assign the independent teams to a unique community label rather than assigning them a single community label as in the original football dataset. In this way the number of communities given by the number of conferences is 19. \paragraph{Political Blogs (polblogs)} We remove the isolated vertices and self-loops. The ground-truth communities are \textit{left/liberal, right/conservative}, so $C=2$. For the analysis of these networks, we run \mbox{{\small CESNA}}\text{} with the default parameter $\alpha=0.5$ because their released code does not allow to perform a cross-validation procedure on the scaling parameter. The facebook networks have overlapping communities, while for the other two datasets we assume non-overlapping, according to the proposed ground-truth. For facebook we consider the 21 ego networks as different iterations. For the other two, since both \mbox{{\small MTCOV}}\text{} and \mbox{{\small NC}}\text{} are based on a EM algorithm which does not ensure to reach a global maximum, we perform 10 restarts of the algorithms with different initializations at random. Results are presented in the main manuscript. \section*{Discussion} \label{sec: Discussion} We present \mbox{{\small MTCOV}}, a generative model that performs overlapping community detection in multilayer networks with node attributes. We show its robustness in adapting to different scenarios, and its flexibility in exploiting the attributes that are more informative while ignoring those that are less correlated with the network communities. Our method is capable of estimating quantitatively the contribution given by the attributes and incorporating them to improve prediction performance both in terms of recovering missing attributes and in terms of link prediction. This allows domain experts to investigate particular attributes and select relevant community partitions based on what type of node information they are interested in investigating. There are valuable possible extensions of this work. One example is to incorporate modeling of more complex data types for the attributes, for instance combinations of discrete and continuous attributes, or other types of extra information, like time-varying network elements, whether the attributes, node, edges or combinations of these. From a technical point of view, when the topological and attribute datasets are very unbalanced in size, this might impact their relative likelihood weight and thus inference. One should then consider automating the process of rescaling them accordingly, as a pre-processing step to be incorporated into the model. Similarly, hyperparameter selection would benefit from an automatized routine when more than one performance metric is considered. The relations between attributes and communities could be transferred across networks to predict missing information when having access to similar but incomplete datasets. We show examples of these here, where we studied two snapshots of the same village networks across time. While we leave these questions for future work, we provide an open source version of the code. \section*{Results} \label{sec: Results} We test \mbox{{\small MTCOV}}'s ability to detect communities in multilayer networks with node attributes by considering both synthetic and real-world datasets. We compare against \mbox{{\small MULTITENSOR}} \cite{Multitensor}, an algorithm similar to ours but that does not include node attributes. We also test \mbox{{\small MTCOV}}'s performance on single-layer networks, as the mathematical framework behind \mbox{{\small MTCOV}}\text{} still applies. Given this potential use and the paucity of algorithms suitable for comparison for multilayer networks, such comparisons assess the general utility of \mbox{{\small MTCOV}}\text{}. \subsection*{Multilayer synthetic networks with ground-truth} To illustrate the flexibility and the robustness of our method, we generate multilayer synthetic networks with different kinds of structures in the various layers adapting the protocol described in De Bacco et al.\cite{Multitensor} to accommodate node attributes. We generate attributes as done in Newman and Clauset \cite{newman2016structure}: we match them with planted communities in increasing ratios varying from 0.3 to 0.9; these values correspond also to the $\gamma$ parameters that we fix for \mbox{{\small MTCOV}}. Specifically, we generate three types of directed networks using a stochastic block model \cite{holland1983stochastic}, all with $C=2$ communities of equal-size unmixed group membership and $N=1000$ nodes, but with different numbers and kinds of layers, similar to De Bacco et al.\cite{Multitensor}. The first network ($G_{1}$) has $L=2$ layers, one assortative ($W^{\alpha}$ has higher diagonal entries) and one disassortative ($W^{\alpha}$ has higher off-diagonal entries); the second ($G_{2}$) has $L=4$ layers, two assortative and two disassortative and the third ($G_{3}$) has $L=4$ layers, one assortative, one disassortative, one core-periphery ($W^{\alpha}$ has higher diagonal entries but one of the two is bigger than the other) and one with biased directed structure ($W^{\alpha}$ has higher off-diagonal entries but one of the two is bigger than the other). We generate ten independent samples of each of these types of networks and use all the evaluation metrics described in the Methods section in the presence of ground-truth. We use the membership inferred by the algorithms using the best maximum likelihood fixed point over 10 runs with different random initial conditions. As shown in Table \ref{tab: multisynthetic}, \mbox{{\small MTCOV}}\text{} performs significantly better than \mbox{{\small MULTITENSOR}}\text{} on the first and second network. This suggests that incorporating attribute information can significantly boost inference, with an increasing benefit for a smaller number of layers. Figure \ref{fig:partition1} shows an example of this result. On the other hand, notice that $G_{2}$ requires a smaller match ($\gamma=0.5)$ between attributes and communities than $G_{1}$ ($\gamma=0.7)$ to achieve similar performance. $G_{1}$ and $G_{2}$ have similar structure but the second has twice as many layers. Thus, increasing the number of layers may require less contribution from the extra information of the attributes, a possible advantage for multilayer networks. This intuition is reinforced by noticing not only that the best performance is achieved for $\gamma<0.9$, but also that both the algorithms perform very well in the third network, regardless of the value of the match between attributes and communities. Contrary to $G_{2}$, $G_{3}$ has a different structure in each of the 4 layers. This diversity can be even more beneficial than having more but correlated layers (as in $G_{1}$ \textit{vs} $G_{2}$). These synthetic tests demonstrate the impact of leveraging both node attributes and topological information: when topological structure is not very informative (as in $G_{1}$ with only two layers), adding node attributes can significantly help in recovering the communities. In contrast, when topological information is more complex (as in $G_{3}$ where all layers are different), properly combining the different layers' structures can compensate for a limited access to extra information on nodes. Overall, this shows the need for methods suited for exploiting various sources of information and the complexity behind multilayer networks. \begin{table}[h!] \centering \renewcommand{\arraystretch}{1.2} \resizebox{\textwidth}{!} {\begin{tabular}{l|cccc|cccc|cccc} \clineB{1-13}{3} \multicolumn{1}{c}{\textbf{}} & \multicolumn{4}{c|}{\textbf{$G_{1}$}} & \multicolumn{4}{c|}{\textbf{$G_{2}$}} & \multicolumn{4}{c}{\textbf{$G_{3}$}} \\ \multicolumn{1}{l|}{\textbf{Method}} & \textbf{F1-score} & \textbf{Jaccard} & \textbf{CS} & \textbf{L$_1$} & \textbf{F1-score} & \textbf{Jaccard} & \textbf{CS} & \textbf{L$_1$} & \textbf{F1-score} & \textbf{Jaccard} & \textbf{CS} & \textbf{L$_1$} \\ \hline \multicolumn{1}{l|}{\mbox{{\small MULTITENSOR}}} & 0.512$\pm$0.006 &0.344$\pm$0.006 &0.585$\pm$0.005 &0.492$\pm$0.004 & 0.514$\pm$0.006&0.346$\pm$0.06 &0.614$\pm$0.005 & 0.490$\pm$0.005 &\textbf{0.999$\pm$0.001}&\textbf{0.998$\pm$0.001}&\textbf{0.991$\pm$0.001}&0.063$\pm$0.002\\ \multicolumn{1}{l|}{\mbox{{\small MTCOV}}\_0.3} & 0.7$\pm$0.2& 0.5$\pm$0.2 &0.7$\pm$0.1 &0.4$\pm$0.1 & 0.8$\pm$0.2&0.7$\pm$0.2 &0.8$\pm$0.1 &0.3$\pm$0.2 &0.995$\pm$0.002&0.990$\pm$0.004&0.984$\pm$0.002&0.080$\pm$0.004\\ \multicolumn{1}{l|}{\mbox{{\small MTCOV}}\_0.5} &0.6$\pm$0.1&0.5$\pm$0.2 & 0.7$\pm$0.1& 0.4$\pm$0.1 & 0.992$\pm$0.005&0.985$\pm$0.009 &0.986$\pm$0.004 &0.064$\pm$0.004 &0.996$\pm$0.002&0.992$\pm$0.004&0.985$\pm$0.002&0.079$\pm$0.004\\ \multicolumn{1}{l|}{\mbox{{\small MTCOV}}\_0.7} & \textbf{0.988$\pm$0.002}& \textbf{0.976$\pm$0.004} &\textbf{0.977$\pm$0.002} & 0.079$\pm$0.003 & \textbf{1.$\pm$0.}&\textbf{1.000$\pm$0.001} &\textbf{0.991$\pm$0.001} &0.062$\pm$0.002 &0.994$\pm$0.002&0.988$\pm$0.004&0.982$\pm$0.001&0.087$\pm$0.002\\ \multicolumn{1}{l|}{\mbox{{\small MTCOV}}\_0.9} & 0.958$\pm$0.003&0.920$\pm$0.005 & \textbf{0.977$\pm$0.001}& \textbf{0.050$\pm$0.002} & 0.992$\pm$0.002&0.984$\pm$0.004 &0.988$\pm$0.001 &\textbf{0.050$\pm$0.002} &0.976$\pm$0.003&0.952$\pm$0.006&0.982$\pm$0.002&\textbf{0.051$\pm$0.003}\\ \clineB{1-13}{3} \end{tabular}} \caption{Performance of algorithms \mbox{{\small MULTITENSOR}}\text{} and \mbox{{\small MTCOV}}\text{} on synthetic multilayer networks with attributes. We use different matches (one per row, e.g. $\mbox{{\small MTCOV}} \_{0.3}$ denotes a match of 0.3, this is also the value we use to fix $\gamma$) between attributes and planted communities on synthetic directed multilayer networks. Results are averages and standard deviations over 10 networks samples for each network type $G_{m}$, $m=1,2,3$; we take the average performance over the in-coming and out-going memberships, i.e., the matrices $U$ and $V$, and the best performances are in boldface. Networks are generated with stochastic block model with $C=2$, $N=1000$ and average degree $k=4$. Denote $W^{a}$, $W^{d}$, $W^{cp}$ and $W^{bd}$, the affinity matrices of the assortative, disassortative, core-periphery and the biased directed layers respectively. Then, their entries are $w^{a}_{11}=w^{a}_{22}=w^{d}_{12}=w^{d}_{21}=w^{cp}_{11}=w^{bd}_{12}=\f{kC}{N}$, $w^{a}_{12}=w^{a}_{21}=w^{d}_{11}=w^{d}_{22}=w^{cp}_{12}=w^{cp}_{21}=w^{bd}_{11}=w^{bd}_{22}=0.1\times\f{kC}{N}$ and $w^{cp}_{22}=w^{bd}_{12}=0.03\times \f{kC}{N}$. The F1-score, Jaccard, CS and L$_1$ are performance metrics as defined in the Methods section.} \label{tab: multisynthetic} \end{table} \begin{figure}[htp]% \centering \subcaptionbox{Ground-truth}{\includegraphics[width=0.24\linewidth]{Figures/gt_299.png}} \subcaptionbox{\mbox{{\small MULTITENSOR}}}{\includegraphics[width=0.24\linewidth]{Figures/mt_299.png}} \subcaptionbox{\mbox{{\small MTCOV}}, $\gamma=0.5$}{\includegraphics[width=0.24\linewidth]{Figures/mtcov05_299.png}} \subcaptionbox{\mbox{{\small MTCOV}}, $\gamma=0.7$}{\includegraphics[width=0.24\linewidth]{Figures/mtcov07_299.png}} \caption{Partition of a synthetic multilayer network with attributes. We generated synthetic directed multilayer networks using a stochastic block model, that aligns with $G_1$. To illustrate, here we do the equivalent task on a smaller network of size N = 299, C = 2 communities of equal-size unmixed group membership and L = 2 layers, of which one assortative (green) and one disassortative (pink); (a) the ground-truth partition; (b-d) the communities inferred by three different methods: (b) \mbox{{\small MULTITENSOR}}, an algorithm without attributes, (c) \mbox{{\small MTCOV}}\text{} using the network structure and the attributes with the same proportion, i. e. $\gamma=0.5$ and (d) \mbox{{\small MTCOV}}\text{} using mostly the attribute structure, i.e. $\gamma=0.7$. Colors denote the inferred partition; the attributes in (c) and (d) are generated by matching them with true community assignments for the $50\%$ and $70\%$ of the nodes respectively, and chosen uniformly at random from the non-matching values; square and triangle denote the synthetic dummy attribute (squares are matched with the red group, triangles with the blue) and the size of the node shows the nodes matched with the true community (bigger means deterministic match, smaller means uniform at random match). We use the matrix $U$ for the membership. } \label{fig:partition1}% \end{figure} \subsection*{Multilayer social support network of rural Indian villages} We demonstrate our model beyond synthetic data by applying it to social support networks of two villages in Tamil Nadu, India, which we call by the pseudonyms ``Te\underline{n}pa\d{t}\d{t}i'' (Ten) and ``A\underline{l}ak\={a}puram'' (Ala) \cite{power2015, power2017, power2019}. Data were collected in the form of surveys where adult residents were asked to nominate those individuals who provided them with various types of support, including running errands, giving advice, and lending cash or other household items. These were collected in two rounds, one in 2013 and the other in 2017. Each type of support corresponds to a layer in the network; we consider only those layers present in both rounds, for a total of $L=6$ layers. After pre-processing the data, by considering only those individuals that had at least one outgoing edge and removing self-loops, the resulting networks have the size reported in Table \ref{tab: Statistics}. In addition, several attributes were collected, which include information about age, religion, caste, and education level. Ethnographic observation in these villages \cite{power2015} and previous analyses \cite{power2017, power2019} suggest that social relations are strongly structured by religious and caste identity, with these divisions shaping where people live, who they marry, and who they choose to associate with. In other words, they suggest a dependence between the attributes religion and caste and the mechanisms driving edge formation in these social support networks. Motivated by these insights, here we consider the attributes caste and religion and add them into the model. In addition, we test the importance of variables that we expect to be less informative, such as gender and age. The latter, being continuous, is also an example of a non-categorical variable. Provided it has a finite range, as it is the case for age, we can encode it into categorical by binning its values. Here we use equal bins of size 5 years. \begin{table}[ht] \centering \renewcommand{\arraystretch}{1.2} \begin{tabular}{ccccccccc} \clineB{1-9}{3} \textbf{Village} & \textbf{Year} & \textbf{Nodes} &$ \mathbf{ Edges}$ & $\mathbf{\langle k \rangle}$& \textbf{Caste} & \textbf{Religion}& \textbf{Age}& \textbf{Gender}\\ \hline A\underline{l}ak\={a}puram & 2013 & 419 & 4161& 20 & 14 & 3 &11& 2 \\ & 2017 & 441 & 5578 & 25 & 13 & 3 &12& 2 \\ Te\underline{n}pa\d{t}\d{t}i & 2013 & 362 &3374 & 19 & 11 & 2 &11 & 2 \\ & 2017 & 346 & 3806 & 22 & 9 &2 &12 & 2 \\ \clineB{1-9}{3} \end{tabular} \caption{Network summary statistics for the four social support networks of Indian villages. Each has the same set of 6 layers and Edges are the total over them; $\langle k \rangle$ is the average degree per node on the whole multilayer network. The columns Caste, Religion, Age and Gender are the number of different categories observed in each network for their respective attribute. } \label{tab: Statistics} \end{table} Without assuming \textit{a priori} any ground-truth, we measure performance using the AUC and accuracy as explained in the Methods section. We compare with \mbox{{\small MULTITENSOR}}\text{} to measure the extent to which adding the attributes helps predicting edges and attributes; in addition, in terms of accuracy values, we considered two baselines for further comparisons: i) a uniform at random probability over the number of possible categories (RP); and ii) the maximum relative frequency of the attribute value appearing more often (MRF). We fix hyperparameters using 5-fold cross-validation and obtain values of $\gamma \in [0.2, 0.9]$, signaling relevant correlations between attributes and communities. For details, see Supplementary Table S2. Empirically, we observe that when $\gamma>0.5$ the algorithm achieves better performance in terms of link and attribute prediction by well balancing the log-likelihood of the attribute dimension and the one of the network structure. For validation, we split the dataset into training/test sets uniformly at random as explained in the Methods section. Table \ref{tab: randomsampling} reports the average results over ten runs for each network, and shows that \mbox{{\small MTCOV}}\text{} is capable of leveraging two sources of information to improve both performance metrics. In fact, our algorithm systematically achieves the highest accuracy for attribute prediction and the highest AUC for edge prediction (boldface). While a good performance in attribute prediction is expected by design as we add this data into the model, the fact that it also boosts performance in terms of edge prediction is not granted \textit{a priori}. Instead, it is a quantitative way to show that an attribute plays an important role in the system. It also demonstrates the potential of capturing correlations between two different sources of information, which can have relevant applications, in particular when missing information of one kind. Notice in particular the improvement in AUC when using caste compared to no attribute given (\mbox{{\small MULTITENSOR}}). The other attributes are less informative; in particular age has a performance similar to \mbox{{\small MULTITENSOR}}\text{} in edge prediction, signaling that it does not contribute to inform edge formation. Indeed, it has the smallest inferred $\gamma$ (always $< 0.5$), which gives also worse accuracy performance than the baseline, signaling again that this attribute may not be correlated with the community structure. All these results show the flexibility of \mbox{{\small MTCOV}} \text{} in adapting based on the data given in input: if warranted, it is able to ignore those attributes that are not correlated with network division and instead find communities that are mainly based on the network structure. Next, we test how adding node attributes impacts robustness against unbalanced data, where the ratio of positive examples (existing edges) observed in the training is different than that in the test set. We denote the total probability of selecting an edge in the test as \textit{tpe} and consider values $\textit{tpe} \in \ccup{0.001,\, 0.004,\, 0.015, \, 0.03}$ denoting under-representation ($0.001$), equal ($0.004$), and over-representation (values $0.015$ and $0.03$) compared to the uniform at random selection (empirically we find $tpe=0.004$). In these tests, we hold out $20\%$ of the entries of $A$ biasing their selection using the \textit{tpe} values; in addition, we give as input the whole design matrix $X$ (attributes) and measure link prediction performance. We observe that \mbox{{\small MTCOV}}\text{} is significantly more robust than the algorithm that does not use any attribute information, regardless of the value of $\gamma$. In fact, even though performance deteriorates as we decrease the number of positive examples in the training set (i.e., higher \textit{tpe}), \mbox{{\small MTCOV}}\text{} is less impacted by this, as shown in Fig. \ref{fig: tpe2} (results reported in Supplementary Table S3). Notice in particular performance discrepancies when using the attribute caste in the difficult regimes ($\textit{tpe} \in \ccup{0.015, 0.03}$): \mbox{{\small MTCOV}}'s performance deteriorates only a little, while using the other attributes or none makes performance significantly worse, with AUC down to 0.6 from a value higher than 0.8 for easier regimes. Moreover, notice that attributes with the same scaling parameter value can give different prediction results, underlying the necessity to consider both the value of the estimated $\gamma$ and the quality of the attribute for quantifying its importance. This could explain why caste provides always better results, given by the fact that its categories are more heterogeneous (i.e., more information) than religion and gender. The robustness of \mbox{{\small MTCOV}}\text{} is also confirmed by analyzing the performances on a trial-by-trail basis, each trial being a random sample of the held-out entries. As we show in Fig. \ref{fig: tpe1}, \mbox{{\small MTCOV}}\text{} better predicts links in $89\%$ of the trials and never goes below the threshold of 0.5, the baseline random choice. These results demonstrate how adding another source of information helps when observing a limited amount of network edges. \begin{table}[h!] \centering \resizebox{0.9\textwidth}{!}{ \renewcommand\arraystretch{1.25} \begin{tabular}{ll|cccc|cccc} \clineB{1-10}{3} \multicolumn{1}{c}{\textbf{}} &\multicolumn{1}{c}{\textbf{}} & \multicolumn{4}{c}{\textbf{ACCURACY for attribute prediction}} & \multicolumn{4}{c}{\textbf{AUC for link prediction}} \\ \multicolumn{1}{l}{\textbf{Attribute}} &\multicolumn{1}{l|}{\textbf{Method}} & \textbf{Ala 2013} & \textbf{Ala 2017} & \textbf{Ten 2013} & \textbf{Ten 2017} & \textbf{Ala 2013} & \textbf{Ala 2017} & \textbf{Ten 2013} & \textbf{Ten 2017} \\ \hline &\multicolumn{1}{l|}{\mbox{{\small MULTITENSOR}}} &&&& & 0.771$\pm$0.009 & 0.835$\pm$0.006 &0.758$\pm$0.005&0.81$\pm$0.01\\ \hline \multirow{3}{*}{Caste} & \multicolumn{1}{l|}{RP} & 0.07 & 0.08 & 0.10& 0.11 & & & &\\ &\multicolumn{1}{l|}{MRF} & 0.556$\pm$0.009& 0.57$\pm$0.01 & 0.32$\pm$0.01 & 0.33$\pm$0.02& & & &\\ &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & \textbf{0.80$\pm$0.05} & \textbf{0.77$\pm$0.05} & \textbf{0.69$\pm$0.09} & \textbf{0.74$\pm$0.07} & \textbf{0.837$\pm$0.009} & \textbf{0.858$\pm$0.008}&\textbf{0.829$\pm$0.006}&\textbf{0.82$\pm$0.01}\\ \hline \multirow{3}{*}{Religion} &\multicolumn{1}{l|}{RP} & 0.33 & 0.33 & 0.50 & 0.50 & & & &\\ &\multicolumn{1}{l|}{MRF} & 0.837$\pm$0.008& 0.843$\pm$0.006 & 0.696$\pm$0.008 & 0.679$\pm$0.008 & & & &\\ &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & \textbf{0.96$\pm$0.02} & \textbf{0.95$\pm$0.03 } & \textbf{0.76$\pm$0.08} & \textbf{0.80$\pm$0.05} &0.813$\pm$0.007 &0.83$\pm$0.01 &0.81$\pm$0.02& 0.80$\pm$0.01\\ \hline \multirow{3}{*}{Age} &\multicolumn{1}{l|}{RP} & 0.09 & 0.08 & 0.09 & 0.08 & & & &\\ &\multicolumn{1}{l|}{MRF} & \textbf{0.135$\pm$0.005} & \textbf{0.126$\pm$0.007} & 0.126$\pm$0.005 & \textbf{0.128$\pm$0.008}& & & &\\ &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & 0.11$\pm$0.03 & 0.11$\pm$0.02 & \textbf{0.13$\pm$0.04} & 0.10$\pm$0.03 &0.80$\pm$0.01 & 0.823$\pm$0.008 &0.783$\pm$0.009 & 0.80$\pm$0.01\\ \hline \multirow{3}{*}{Gender} &\multicolumn{1}{l|}{RP} & 0.50 & 0.50 & 0.50 & 0.50 & & & &\\ &\multicolumn{1}{l|}{MRF} & 0.584$\pm$0.009 & 0.58$\pm$0.01 & 0.56$\pm$0.01 & 0.55$\pm$0.01& & & &\\ &\multicolumn{1}{l|}{\mbox{{\small MTCOV}} } & \textbf{0.61$\pm$0.05} & \textbf{0.65$\pm$0.04} & \textbf{0.58$\pm$0.08} & \textbf{0.71$\pm$0.08} &0.79$\pm$0.02 & 0.831$\pm$0.009 &0.80$\pm$0.01 & 0.81$\pm$0.01\\ \clineB{1-10}{3} \end{tabular}} \caption{Prediction performance on real multilayer networks with attributes. Results are averages and standard deviations over 10 independent trials of cross-validation with 80-20 splits selected uniformly at random (i.e., $\textit{tpe}=0.004$); the best performances are in boldface. Datasets are described in Table \ref{tab: Statistics}. RP is the performance of uniform random probability and MRF the one of the maximum relative frequency, see Methods section for details. } \label{tab: randomsampling} \end{table} \begin{figure}[h!] \centering \includegraphics[width=0.8\linewidth]{Figures/validation_all} \caption{Probabilistic link prediction with biased edge sampling. Results are AUC values of \mbox{{\small MTCOV}}\text{} and \mbox{{\small MULTITENSOR}}\text{} on four social support networks in different held-out settings. Here $tpe$ indicates the total probability of selecting one edge (positive example) in the test set. We considered Caste, Religion, Age and Gender attributes; results are averages and standard deviations over 10 independent runs. } \label{fig: tpe2} \end{figure} \begin{figure}[phbt] \begin{minipage}[c]{0.45\linewidth} \includegraphics[width=\linewidth]{Figures/ev_scatter_Religion} \end{minipage}\hfill \begin{minipage}[c]{0.5\linewidth} \caption{ Trial-by-trial probabilistic link prediction with biased edge sampling. The values of AUC for \mbox{{\small MTCOV}}\text{} and \mbox{{\small MULTITENSOR}}\text{} are shown on the vertical axis and the horizontal axis respectively. The brightness represents the hardness of the settings in terms of biasing the edge sampling in the training. From bottom to top: $tpe=0.03$ (hard, dark color), $tpe=0.015$, $tpe=0.004$ (random), $tpe=0.001$ (easy, light color). Points above the diagonal, shown in shades of red, are trials where \mbox{{\small MTCOV}}\text{} is better performing than \mbox{{\small MULTITENSOR}}\text{}. The fractions for which each method is superior are shown in the plot legend. We use the attribute Religion. } \label{fig: tpe1} \end{minipage} \end{figure} \subsubsection*{Qualitative analysis of a social support network} To demonstrate our \mbox{{\small MTCOV}}\text{} model beyond prediction tasks and highlight its potential for interpretability, we show as an example its qualitative behavior on the real network of A\underline{l}ak\={a}puram in 2017 (see Table \ref{tab: Statistics}). Specifically, we compare the communities extracted by our algorithm and those inferred by \mbox{{\small MULTITENSOR}}. To ease comparison, we fix the same number of groups to $C=4$ for both algorithms and measure how caste membership distributes across communities, and fix $\gamma=0.8$ as obtained with cross-validation. Figure \ref{fig:intNet} shows the magnitude of each individual's inferred outgoing memberships $u_{i}$ in each group. While the communities identified by \mbox{{\small MTCOV}} \text{} and \mbox{{\small MULTITENSOR}} \text{} show substantial similarities, \mbox{{\small MTCOV}}\text{} generally classifies castes more consistently into distinct communities, as we show in Fig. \ref{fig:intNet} and \ref{fig: interpretability_Ala2017}. To make a quantitative estimate of the different behaviors, we measure the entropy of the attribute inside each community $H_{k}=-\sum_{z=1}^{Z}f_{z}\log f_{z}/\log(Z)$, where $f_{z}$ is the relative frequency of the $z$-th caste inside a group $k$, and the denominator is the entropy of a uniform distribution over the $Z$ castes, our baseline for comparison. Values of $H_{k}$ close to 1 denote a more uniform distribution of castes, whereas smaller values denote an unbalanced distribution with most of the people belonging to a few castes. We found that \mbox{{\small MTCOV}}\text{} has smaller entropies over the groups, with two groups having the smallest values, whereas \mbox{{\small MULTITENSOR}}\text{} have the highest, showing its tendency to cluster individuals of different castes in the same group. In addition, we observe that \mbox{{\small MTCOV}}\text{} has a more heterogenous group size distribution which seems to be correlated with caste. Notably, the algorithms differ in how they place two caste groups that live in hamlets separated from the main village (the Hindu Y\= atavars and CSI Pa\underline{r}aiyars). With \mbox{{\small MULTITENSOR}} \text{}, they are grouped together, while with \mbox{{\small MTCOV}} \text{}, the Hindu Y\= atavars are joined up into a community with Pa\d l\d lars and Kul\= alars. While \mbox{{\small MULTITENSOR}} \text{} is clearly picking up the structural similarities of the two hamlets, this division makes little sense socially and culturally. In contrast, the way in which \mbox{{\small MTCOV}} \text{} defines a community which spans caste boundaries (\mbox{{\small MTCOV}} \text{} C1) aligns with ethnographic knowledge of the relations between these castes. Finally, we remark that there might be multiple meaningful community divisions in the network, and the fact that \mbox{{\small MTCOV}}'s partition seems to better capture the distributions in the attribute caste does not mean than one algorithm is better than the other. In fact, there might be other hidden topological properties that \mbox{{\small MULTITENSOR}}'s partition is picking up by being agnostic to caste membership. The choice of which algorithm to use should be made based on the final goal of the application at hand. \begin{figure}[h!] \begin{subfigure}{0.2\textwidth} \centering \includegraphics[width=0.9\linewidth]{Figures/caste} \caption{Caste} \label{fig:int-caste} \end{subfigure} \begin{subfigure}{0.8\textwidth} \centering \includegraphics[width=0.9\linewidth]{Figures/C4_mtcov} \caption{\mbox{{\small MTCOV}}} \includegraphics[width=0.9\linewidth]{Figures/C4_mt} \caption{\mbox{{\small MULTITENSOR}}} \label{fig:int-mtcov-mt} \end{subfigure} \caption{Attributes and inferred communities. Nodes of the social support network of A\underline{l}ak\={a}puram in 2017 are colored by: (a) the attribute Caste (with colors as shown in Fig. \ref{fig: interpretability_Ala2017}); inferred communities by (b) \mbox{{\small MTCOV}}\text{} and (c) \mbox{{\small MULTITENSOR}}\text{}. Darker values in the grey scales indicate higher values of the entry of the membership vector $u_i$. } \label{fig:intNet} \end{figure} \begin{figure}[phbt] \begin{minipage}[c]{0.63\linewidth} \includegraphics[width=\linewidth]{Figures/Interpretability_Ala2017} \end{minipage}\hfill \begin{minipage}[c]{0.35\linewidth} \caption{Partition of the attribute Caste inside each community detected by \mbox{{\small MTCOV}}\text{} and \mbox{{\small MULTITENSOR}}\text{} in the social support network of A\underline{l}ak\={a}puram in 2017. The category Other contains small categories having less than five individuals. The label on top of each bar is the value of the entropy of the variable Caste inside the corresponding community. Note that nodes can have mixed membership, here we build a group $k$ by adding to it all nodes $i$ that have a non-zero $k$-th entry $u_{ik}$. The number of nodes is $N=441$, corresponding to the maximum value of the y-axis plotted.} \label{fig: interpretability_Ala2017} \end{minipage} \end{figure} \section*{Introduction} \label{sec: Introduction} Community detection is a fundamental task when investigating network data. Its goal is to cluster nodes into communities and thus find large-scale patterns hidden behind interactions between many individual elements. The range of application of this problem spans several disciplines. For instance, community detection has been used in sociology to analyze terrorist groups in online social networks \cite{waskiewicz2012friend}; in finance to detect fraud events in telecommunication networks \cite{pinheiro2012community}; in engineering to refactor software packages in complex software networks \cite{pan2013refactoring}; and in biology to investigate lung cancer\cite{bechtel2005lung} and to explore epidemic spreading processes \cite{chen2012epidemic}. In recent years, the variety of fields interested in this topic has broadened and the availability of rich datasets is increasing accordingly. However, most research approaches rely on using only the information about interactions among nodes, in other words the network topology structure. This information can be complex and rich, as is the case for multilayer networks where one observes different types of interactions. For instance, in social networks, interactions could entail exchanging goods, socializing, giving advice, or requesting assistance. Most network datasets, however, contain additional information about individuals, attributes which describe their features; for instance their religion, age or ethnicity. Node attributes are often neglected \textit{a priori} by state-of-the-art community detection methods, in particular for multilayer networks. They are instead commonly used \textit{a posteriori}, acting as candidates for ``ground-truth'' for real-world networks to measure the quality of the inferred partition \cite{traud2011comparing,newman2006modularity}; a practice that can also lead to incorrect scientific conclusions \cite{Peele1602548}. It is thus a fundamental question how to incorporate node attributes into community detection in a principled way. This is a challenging task because one has to combine two types of information \cite{yang2013community}, while evaluating the extent to which topological and attribute information contribute to the network's partition \cite{falih2018community}. To tackle these questions, we develop \mbox{{\small MTCOV}}, a mathematically rigorous and flexible model to address this problem for the general case of multilayer networks, i.e., in the presence of different types of interactions. To the best our knowledge, \mbox{{\small MTCOV}}\text{} is the first overlapping community detection method proposed for multilayer networks with node attributes. The model leverages two sources of information, the topological network structure and node covariates (or attributes), to partition nodes into communities. It is flexible as it can be applied to a variety of network datasets, whether directed, weighted, or multilayer and it outputs overlapping communities, i.e., nodes can belong to multiple groups simultaneously. In addition, the model does not assume any \textit{a priori} correlation structure between the attributes and the communities. On the contrary, the contribution of the attribute information is quantitatively given as an output of the algorithm by fitting the observed data. The magnitude of this contribution can vary based on the dataset. Even if this is not very high, for instance if the attributes are noisy or sparse, the model is nevertheless able to use this extra information to improve performance. At the same time, if incorporating attribute information hurts inference tasks, the model will down weigh this contribution and instead use mostly the topological network structure. Our method allows domain experts to investigate particular attributes and select relevant community partitions based on what type of node information they are interested in studying. In fact, by choosing the input data, we can drive the algorithm to select for communities that are more relevant to the attribute under study. If the attribute hurts performance and is consequently down weighted by the algorithm, this can be used as a signal that the attribute might not correlate well with any partition, given the remaining topological information available, and thus inform the expert accordingly. We study \mbox{{\small MTCOV}}\text{} on synthetic multilayer networks, a variety of single-layer node-attributed real networks and several real multilayer networks of social support interactions in two Indian villages. We measure performance based on prediction tasks and overlap with ground-truth (when this is known). For single-layer networks, we compare the performance of \mbox{{\small MTCOV}}\text{} to state-of-the-art community detection algorithms with node attributes; for multilayer networks, we test against a state-of-the-art algorithm that does not use any node attribute information and measure the extent to which knowing both types of information helps inference. We find that \mbox{{\small MTCOV}}\text{} performs well in predicting missing links and attributes. It also leads to more interpretable community structures and allows the quantification of the impact of the node attributes given as input. \textbf{Related Work.} Several methods have been proposed to study community detection in networks \cite{fortunato2010community}. In particular, we are interested in those valid for multilayer networks \cite{de2013}. These generalize single-layer networks in that they can model different types of interactions and thus incorporate extra information which is increasingly available. Among these, we focus on generative models for multilayer networks \cite{Multitensor,schein2015,schein2016bayesian,valles2016,stanley2015,peixoto2015,paul2015}, which are based on probabilistic modeling like Bayesian inference or maximum likelihood optimization. These are flexible and powerful in terms of allowing multiple inference tasks, injecting domain knowledge into the theoretical framework, and being computationally efficient. However, the majority of these methods do not consider node attributes as input along with the network information. In fact, the few methods developed for community detection in multilayer networks with node attributes are based on first aggregating the multilayer network into a single layer, either by combining directly the adjacency matrices of each layer \cite{gheche2018orthonet} or by using similarity matrices derived from them along with the node attributes \cite{papadopoulos2015, papadopoulos2017}. In the context of data mining, a similar problem can be framed for learning low dimensional representations of heterogeneous data with both content and linkage structure (what we call attributes and edges). This is tackled by using embeddings extracted via deep architectures \cite{chang2015}, which is rather different than our approach based on statistical inference. Our problem bears some common ground with the one studied by Sachan et al. \cite{TUCM} for extracting communities in online social networks, where users gather based on common interests; they adopt a Bayesian approach, but with a rather different goal of associating different types of edges to topics of interest. A related but different problem is that of performing community detection with node attributes on multiple independent networks \cite{sweet2018estimating, Signorelli_2019}; this differs with modeling a single multilayer network in that it assumes that covariates influence in the same way all the nodes in a network but in a different way the various networks in the ensemble. For single-layer networks, there has been more extensive work recently on incorporating extra information on nodes \cite{newman2016structure,yang2013community,bothorel2015clustering,zhang2016community,hric2016network,stanley2019stochastic,emmons2019map,sweet2018estimating, xu2012model}. Among those adopting probabilistic modeling, some incorporate covariate information into the prior information of the latent membership parameters \cite{sweet2018estimating, tallberg2004bayesian,white2016mixed}, while others include covariates in an additive way along with the latent parameters \cite{ airoldi2011confidence,sweet2015incorporating}, so that covariates influences the probability of interactions independently of the latent membership. These works show the impact of adding nodes attributes in community detection \textit{a priori} into the models to uncover meaningful patterns. One might then be tempted to adopt such methods also in multilayer networks by collapsing the topological structure into a suitable single network that can then be given in input to these single-layer and node-attributed methods as done by Gheche et al.\cite{gheche2018orthonet} However, collapsing a multilayer network often leads to important loss of information, and one needs to be careful in determining when this collapse is appropriate and how it should be implemented, as shown for community detection methods without attribute information \cite{taylor2016enhanced,taylor2017super}. Thus the need of a method that not only incorporates different types of edges but also node attributes. \section*{Methods} \label{sec: Methods} \thispagestyle{empty} We adapt recent ideas from the generative model behind \mbox{{\small MULTITENSOR}} \cite{Multitensor}, a multilayer mixed-membership model based on a Poisson tensor factorization \cite{Kolda2009}, to incorporate node attributes in a principled manner. It can take in input directed and undirected networks, allowing different topological structures in each layer, including arbitrarily mixtures of assortative, disassortative and core-periphery structures. We move beyond \mbox{{\small MULTITENSOR}}\text{} by incorporating node covariates via introducing a proper likelihood term that accounts for this extra information. We use the formalism of maximum likelihood estimation: we combine the structural and the node information into a global likelihood function and provide a highly scalable Expectation-Maximization algorithm for the estimation of parameters. \subsection*{Model description and notation} Consider a multilayer network of $N$ nodes and $L$ layers. This is a set of graphs $G = \{G^{(\alpha)}\left(\mathcal{V}, \mathcal{E}^{(\alpha)}\right)\}_{1\leq \alpha \leq L} $ defined on a set $\mathcal{V}$ of $N$ vertices shared across $L\geq1$ layers, and $\mathcal{E}^{(\alpha)}$ is the set of edges in the layer $\alpha$. Each layer $\alpha \in \{1,\dots, L\}$ is a graph $G^{(\alpha)}(\mathcal{V}, \mathcal{E}^{(\alpha)})$ with adjacency matrix $A^{(\alpha)} = [a_{ij}^{(\alpha)}] \in \mathbb{R}^{N\times N}$, where $a_{ij}^{(\alpha)}$ is the number of edges of type $\alpha$ from $i$ to $j$; here we consider only positive discrete entries; for binary entries, $E=\sum_{i,j,\alpha} a_{ij}^{(\alpha)}$ is the total the number of edges. Alternatively, we can consider a 3-way tensor $A$ with dimensions $N\times N \times L$. In addition, for each node $i\in \mathcal{V}$ consider the vector of covariates $X_i \in \mathbb{R}^{1\times K}$ (alternatively called also attributes or metadata), where $K$ is the total number of attributes. Here, for simplicity we focus on the case of $K=1$ and categorical covariates with $Z$ different categories. However, we can easily generalize to more than one covariate by encoding each possible combination of them as a different value of one single covariate. For example, for two covariates being gender and nationality, we can encode $X_{i}$ being one covariate with possible values female/American, male/Spanish and so forth. One could also consider real-valued covariates by cutting them into bins. Nevertheless, a future expansion should include the possibility to work with any type of metadata.\\ A community is a subset of vertices that share some properties. Formally, each node belongs to a community to an extent measured by a $C$-dimensional vector denoted \textit{membership}. Since we are interested in directed networks, for each node $i$ we assign two such vectors, $u_i$ and $v_i$ (for undirected networks we set $u =v$); these determine how $i$ forms outgoing and incoming links respectively. Each layer $\alpha$ has an \textit{affinity} matrix $W^{(\alpha)} = [w_{kl}^{(\alpha)}]\in \mathbb{R}^{C \times C}$ which describes the density of edges between each pair ($k, l$) of groups. Each community $k\in \{1,\dots, C\}$ is linked to a category $z\in \{1,\dots, Z\}$ by a parameter $\beta_{kz}$, that explains how much information of the $z$-th category is used for creating the $k$-th community. To summarize, we consider two types of observed data: the adjacency tensor $A = \{A^{(\alpha)}\}_{1\leq \alpha \leq L}$ and the design matrix $X=\{X_i\}_{i\in \{1,\dots, N\}}$; the first contains information about the networks topology structure, the latter about the node covariates. In addition, we have the model parameters that we compactly denote as $\Theta=\ccup{U,V,W,\beta}$. The goal is to find the latent parameters $\Theta$ using the data $A$ and $X$. In other words, given an observed multilayer network with adjacency tensor $A$ and design matrix $X$, our goal is to simultaneously infer the node's membership vectors $u_i$ and $v_i$ $\forall i\in \{1,...,N \}$; the affinity matrices $W^{(\alpha)}$, $ \forall \alpha \in \{1,\dots, L\}$, and the matrix $\beta = [\beta_{kz}] \in \mathbb{R}^{C \times Z}$, which captures correlations between communities and attributes. We consider a probabilistic generative model where \mbox{{\small MTCOV}}\text{} generates the network and the attributes probabilistically, assuming an underlying structure consisting of $C$ overlapping communities. We adopt a maximum likelihood approach where, given the latent parameters $\Theta$, we assume that the data $A$ and $X$ have independent likelihoods; in other words, we assume that $A$ and $X$ are \textit{conditionally independent} given the latent parameters $\Theta$. In addition, we assume that the memberships $U$ and $V$ couple the two datasets, as they are parameters shared between the two likelihoods; whereas the $W$ and $\beta$ are specific to the adjacency and design matrix respectively. We describe separately the procedures for modeling the topology of the network and the node attributes and then we show how to combine them in a unified log-likelihood framework. \subsection*{Modeling the network topology} In modeling the likelihood of the network topology, we adopt the ideas behind \mbox{{\small MULTITENSOR}}: we assume that the expected number of edges of type $\alpha$ from $i$ to $j$ is given by the parameter: \begin{align}\label{eqn:meanPoisson} M_{ij}^{(\alpha)}= \sum_{k,l =1}^C u_{ik}v_{jl}w_{kl}^{(\alpha)} . \end{align} We then assume that each entry $a_{ij}^{(\alpha)}$ of the adjacency tensor is extracted from a Poisson distribution with parameter $M_{ij}^{(\alpha)}$. This is a common choice for network data \cite{ball2011,gopalan2013,gopalan-rec} as it leads to tractable and efficient algorithmic implementations, compared for instance with other approaches that use Bernoulli random variables \cite{yang2013community,newman2016structure}; it also allows the flexibility of treating both binary and integer-weighted networks. We further assume that, given the memberships and affinity matrices, the edges are distributed independently; this is again a conditional independence assumption. We can then write the likelihood of the network topology as: \begin{align}\label{eqn:poisson} P_{G}(A|U,V, W) = \prod_{i,j =1}^N \prod_{\alpha =1}^L \frac{{e}^{-M_{ij}^{(\alpha)}} \left(M_{ij}^{(\alpha)}\right)^{A_{ij}^{(\alpha)}}}{A_{ij}^{(\alpha)} !} , \end{align} which leads to the log-likelihood $\mathcal{L}_G(U,V,W)$ for the \textit{structural dimension}: \begin{equation}\label{eqn:l_structural} \mathcal{L}_G(U,V,W) = \sum_{i,j,\alpha} \bigg[ A_{ij}^{(\alpha)} \text{log} \sum_{k,l} u_{ik}v_{jl}w_{kl}^{(\alpha)} - \sum_{k,l} u_{ik}v_{jl}w_{kl}^{(\alpha)} \bigg], \ee where we have neglected constants that do not depend on the parameters. \subsection*{Modeling the node attributes} In modeling the likelihood of the attributes, we assume that this extra information is generated from the membership vectors; this captures the intuition that knowing a node's community membership helps in predicting the value of the node's attribute. This assumption has also been made in other models for single-layer attributed networks \cite{yang2013community} where one wants to enforce the tendency that nodes in the same community (for assortative structures) are likely to share common attributes. Different approaches \cite{ airoldi2011confidence,sweet2015incorporating} assume instead independence between attributes and membership, which follows a different idea of observing an interaction between individuals if either they belong to the same community (for assortative structures) or they share an attribute or both. \\ Then, we model the probability of observing the $z$-th category for the attribute covariate of node $i$ as the parameter: \begin{align} \label{eq: piz} \pi_{iz} = \frac{1}{2}\sum_{k=1}^C \beta_{kz} (u_{ik}+v_{ik}) , \end{align} where $\beta_{kz}$ is the probability of observing a particular category $z$ together with a community $k$; thus $\pi_i= (\pi_{i1} \dots, \pi_{iZ})$ is a $Z$-dimensional vector such that $ \pi_{iz} \in \rup{0,1}$ and $\sum_{z=1}^Z \pi_{iz} =1, \forall i$. For convenience, we consider one-hot encoding for $x_i = (x_{i1}, \dots, x_{iZ})$, the realization of the random variable $X_i$: $x_{iz}=1$ if node $i$ has attribute corresponding to category $z$, $0$ otherwise and $\sum_{z=1}^Z x_{iz} =1$; the original design matrix $X_{N\times1}$ is thus translated into a binary matrix $X_{N\times Z}$.\\ We then assume that each entry $X_{i}$ of the design matrix is extracted from a multinomial distribution of parameter $\pi_{i}$, which yields the likelihood of the covariates: \begin{align} \label{eqn:multinomial} P_{X}(X_i=x_i|U,V,\beta) = P_{X}(X_{i1}=x_{i1}, \dots, X_{iZ}= x_{iZ}|U,V,\beta) = \pi_{i1}^{x_{i1}} \dots \pi_{iZ}^{x_{iZ}}\ \ . \end{align} In order to satisfy the sum constraint $\sum_{z=1}^Z \pi_{iz} =1$, we impose the normalizations $\sum_{z=1}^Z \beta_{kz} =1$, valid $\forall k$ and $\sum_{k=1}^C u_{ik}= \sum_{k=1}^C v_{ik} =1$, valid $\forall i$. Such constraints are a particular case for which the general constraint for the multinomial parameter is satisfied. Although they are not the only choices, they allow us to give a probabilistic meaning to the components of $\beta$ and the memberships $U$ and $V$. As done for the network's edges, we assume conditional independence for the attributes on the various nodes. This leads to the log-likelihood $\mathcal{L}_{X}(U,V,\beta)$ for the \textit{attribute dimension}: \begin{equation} \label{eq:l_covariate} \mathcal{L}_{X}(U,V,\beta) = \sum_{i=1}^N \sum_{z=1}^Z x_{iz} \, \text{log}(\pi_{iz}) =\sum_{i, z} x_{iz} \, \text{log}\bigg(\frac{1}{2}\sum_{k}\beta_{kz} (u_{ik}+v_{ik})\bigg) . \ee Note, we assume that the attributes have values that can be binned in a finite number $Z$ of unordered categories and the attributes do not need to be one-dimensional. Indeed, we can encode each combination of more attributes as a different value of one-dimensional ``super-attribute''. The model will not be affected, but the computational complexity might increase. \subsection*{Inference with the EM algorithm} Having described how the model works and its main assumptions and intuitions, we now turn our attention to describe how to fit the parameters to the data, in other words, how to perform inference. We assume conditional independence between the network and attribute variables, thus we can decompose the total log-likelihood into a sum of two terms $\mathcal{L}(U,V,W,\beta)=\mathcal{L}_G(U,V,W)+ \mathcal{L}_{X}(U,V,\beta)$. However, in practice, we can improve parameters' inference performance by better balancing the contributions of the two terms as their magnitude can be on different scales, thus the risk of biasing the total likelihood maximization towards one of the two terms. For this, we introduce a scaling parameter $\gamma \in [0,1]$ that explicitly controls the relative contribution of the two terms. The total log-likelihood is then: \begin{eqnarray}\label{eqn:totalL} \mathcal{L}(U,V,W,\beta)&=&\bup{1- \gamma}\mathcal{L}_G(U,V,W)+ \gamma \, \mathcal{L}_{X}(U,V,\beta)\\ &=&(1-\gamma) \sum_{i,j,\alpha} \bigg[A_{ij}^{(\alpha)} \text{log} \sum_{k,l} u_{ik}v_{jl}w_{kl}^{(\alpha)} - \sum_{k,l} u_{ik}v_{jl}w_{kl}^{(\alpha)}\bigg] +\gamma \, \sum_{i, z} x_{iz} \text{log}\bigg(\frac{1}{2}\sum_{k} \beta_{kz} (u_{ik}+v_{ik})\bigg) \nonumber \end{eqnarray} Varying $\gamma$ from 0 to 1 lets us interpolate between two extremes: analyzing the data purely in terms of the network topology or purely in terms of the attribute information. One can either fix this \textit{a priori} based on the goal of the application, closer to 0 for link prediction or closer to 1 for attribute classification, or this can be treated as a hyperparameter that must be estimated, whose optimal value is obtained by fitting the data \textit{via} tuning techniques (for instance cross-validation). This approach provides a natural quantitative measure for the dependence between the communities and the two sources of information. Notice that one can rescale \textit{a priori} each likelihood term individually in order to control even more their magnitudes, and then add it to equation \ref{eqn:totalL}. This choice should be made based on the dataset at hand. Here we consider rescaling $\mathcal{L}_G$ and $\mathcal{L}_X$ only in studying the social support networks of Indian villages, as we have enough data for estimating the normalization coefficients; see Supplementary Section S2.1 for details. We wish to find the $\Theta = ({U,V, W,\beta})$ that maximizes equation (\ref{eqn:totalL}). In general, this is computationally difficult, but we make it tractable by adopting a variational approach using an Expectation-Maximization (EM) algorithm \cite{dempster1977maximum}, similar to what done by De Bacco et al.\cite{Multitensor}, but extended here to include attribute information. Namely, we introduce two probability distributions: $h_{ikz}$ and $\rho_{ijkl}^{(\alpha)}$. For each $i, z$ with $X_{iz}=1$, $h_{izk}$ represents our estimate of the probability that the $i$-th node has the $z$-th category, given that it belongs to the community $k$. On the other hand, for each $i, j, \alpha$ with $A_{ij}^{(\alpha)} =1$, $\rho_{ijkl}^{(\alpha)}$ is the probability distribution over pairs of groups $k, l$. Using Jensen's inequality $\log \bar{x} \geq \overline{\log x}$ for each log-likelihood term gives: \begin{align} \mathcal{L}_X(U,V,\beta) &\geq \sum_{i, z} x_{iz} \sum_{k} h_{izk}\log \frac{\beta_{kz} (u_{ik}+v_{ik})}{2h_{izk}} =\sum_{i,z,k} x_{iz} \rup{h_{izk}\,\log \beta_{kz} (u_{ik}+v_{ik}) - h_{izk}\, \log 2h_{izk}} = \mathcal{L}_X(U,V,\beta, h) \label{eq:lxh} \\ \mathcal{L}_G(U,V,W) &\geq \sum_{i,j,k,l,\alpha}\bigg[ A_{ij}^{(\alpha)}\bigg(\rho_{ijkl}^{(\alpha)} \, \log u_{ik}v_{jl}w_{kl}^{(\alpha)} - \rho_{ijkl}^{(\alpha)}\log \rho_{ijkl}^{(\alpha)}\bigg) - u_{ik}v_{jl}w_{kl}^{(\alpha)}\bigg] = \mathcal{L}_G(U,V,W, \rho) \label{eq:lgp} \quad. \end{align} These lower bounds hold with equality when \begin{align} \label{eqn:Estep} h_{izk}=\frac{\beta_{kz} (u_{ik}+v_{ik})}{\sum_{k'} \beta_{k'z} (u_{ik'}+v_{ik'})} \quad,\quad \rho_{ijkl}^{(\alpha)} =\frac{u_{ik}v_{jl}w_{kl}^{(\alpha)}}{\sum_{k',l'} u_{ik'}v_{jl'}w_{k'l'}^{(\alpha)}} \quad, \end{align} thus maximizing $\mathcal{L}_X(U,V,\beta)$ is equivalent to maximizing $\mathcal{L}_X(U,V,\beta, h)$; similarly for $\mathcal{L}_G(U,V,W)$ and $ \mathcal{L}_G(U,V,W, \rho)$ (this was also the same result derived in \cite{Multitensor}). Overall, we aim at maximizing $\mathcal{L}(U,V,W,\beta, h,\rho)=\bup{1- \gamma}\mathcal{L}_G(U,V,W, \rho)+ \gamma \, \mathcal{L}_{X}(U,V,\beta,h)$, in analogy with what was done before. These maximizations can be performed by alternatively updating a set of parameters while keeping the others fixed. The EM algorithm performs these steps by alternatively updating $h$, $\rho$ (Expectation step) and $\Theta$ (Maximization step); this is done starting from a random configuration until $\mathcal{L}(\Theta, h,\rho)$ reaches a fixed point. Calculating equation (\ref{eqn:Estep}) represents the E-step of the algorithm. The M-step is obtained by computing partial derivatives of $\mathcal{L}(\Theta, h,\rho)$ with respect to the various parameters in $\Theta$ and setting them equal to zero. We add Lagrange multipliers $\lambda=\bup{\lambda^{(\beta)},\lambda^{(u)}, \lambda^{(v)}}$ to enforce constraints: \begin{equation} \label{eqn:LBeta} \mathcal{L}^{'}(\Theta, h,\rho,\lambda)= \mathcal{L}(\Theta, h,\rho) - \sum_{k} \lambda^{(\beta)}_{k} \bup{\sum_{z=1}^Z \beta_{kz} -1} - \sum_{i} \lambda^{(u)}_{i} \bup{\sum_{k=1}^C u_{ik} -1} - \sum_{i} \lambda^{(v)}_{i} \bup{\sum_{k=1}^C v_{ik} -1} \ee For instance, focusing on the update for $\beta_{zk}$, setting the derivative with respect to it in equation (\ref{eqn:LBeta}) to zero and enforcing the constraint $\sum_{z=1}^Z \beta_{kz} =1$ gives $\lambda^{(\beta)}_k = \gamma \sum_{i,z} x_{iz} h_{izk}$; plugging this back finally gives: \begin{align} \label{eqn:beta} \beta_{kz} = \frac{\sum_{i} \,x_{iz} \,h_{izk}}{\sum_{i,z} \,x_{iz} \,h_{izk}} \quad , \end{align} which is valid for $\gamma \neq 0$. Doing the same for the other parameters yields (see Supplementary Section S1 for details): \begin{eqnarray} u_{ik} &=& \frac{\gamma \, \sum_z \,x_{iz} h_{izk} + (1-\gamma)\, \sum_{j,l,\alpha}A_{ij}^{(\alpha)} \rho_{ijkl}^{(\alpha)}}{ \gamma + (1-\gamma) \sum_{j,\alpha}A_{ij}^{(\alpha)}}\label{eqn:u} \\ v_{ik}&=& \frac{\gamma \,\sum_z\, x_{iz} h_{izk} + (1-\gamma)\, \sum_{j,l,\alpha}A_{ji}^{(\alpha)} \rho_{jilk}^{(\alpha)}}{ \gamma + (1-\gamma) \sum_{j,\alpha}A_{ji}^{(\alpha)}} \label{eqn:v} \\ w_{kl}^{(\alpha)} &=& \frac{\sum_{i,j} A_{ij}^{(\alpha)} \rho_{ijkl}^{(\alpha)}}{\sum_i u_{ik} \sum_j v_{jl}} \label{eqn:w}\quad , \end{eqnarray} where equation (\ref{eqn:w}) is valid for $\gamma \neq 1$. The EM algorithm thus consists in randomly initializing the parameters $\Theta$ and then repeatedly alternating between updating $h$ and $\rho$ using equation (\ref{eqn:Estep}) and updating $\Theta$ using equations (\ref{eqn:beta})-(\ref{eqn:w}) until $\mathcal{L}(\Theta, h,\rho)$ reaches a fixed point. A pseudo-code is given in Algorithm \ref{alg:EM}. In general, the fixed point is a local maximum but we have no guarantees that it is also the global one. In practice, we run the algorithm several times, starting from different random initializations and taking the run with the largest final $\mathcal{L}(\Theta, h,\rho)$. The computational complexity per iteration scales as $O(M\,C^{2}+NCZ)$, where $M$ is the total number of edges summed across layers. In practice, $C$ and $Z$ have similar order of magnitude, usually much smaller than the system size $M$; for sparse networks, as is often the case for real datasets, $M \propto N$, thus the algorithm is highly scalable with a total running time roughly linear in the system size. \\ Notice that, although we started from a network log-likelihood $\mathcal{L}_{G}(U,V,W)$ similar to the one proposed in the \mbox{{\small MULTITENSOR}}\text{} model \cite{Multitensor}, the only update preserved from that is the one of $w_{kl}$ in equation (\ref{eqn:w}). The updates for $ u_{ik}$ and $v_{ik}$ are instead quite different; the main reason is that here we incorporated the node attributes, which appear both explicitly and implicitly (through $h$) inside the updates. In addition, here we enforce normalizations like $\sum_{k}u_{ik}=1$, not enforced in \mbox{{\small MULTITENSOR}} . This implies that our model restricted to $\gamma=0$, i.e., no attribute information, does not correspond exactly to \mbox{{\small MULTITENSOR}} . This also implies that, upon convergence, we can directly interpret the memberships as \textit{soft} community assignments (or overlapping) without the need of post-processing their values; in words, $u_{ik}$ represent the probability of node $i$ to belong to the \textit{incoming} community $k$, similarly for $v_{ik}$ and an $\textit{outgoing}$ membership. This distinction is necessary when considering directed networks. If one is interested in recovering \textit{hard} memberships, where a node is assigned to only one community, then one can choose the community corresponding to the maximum entry of $u$ or $v$. \setlength{\textfloatsep}{5pt} \begin{algorithm}[H] \setstretch{0.7} \DontPrintSemicolon \; \KwIn{network $A=\{A_{ij}\}_{i,j=1}^{N}$, design matrix $X=\ccup{x_{iz}}_{i=1}^{N}$, number of communities $C$, hyperparameter $\gamma$} \BlankLine \KwOut{membership vectors $U=\rup{u_{ik}},\, V=\rup{v_{ik}}$; network-affinity matrix $W=\rup{w_{kl}}$; attribute-affinity matrix $\beta=\rup{\beta_{kz}}$.} \BlankLine Initialize $U,V,W,\beta$ at random. \BlankLine Repeat until convergence: \BlankLine \quad 1. Calculate $h$ and $\rho$ (E-Step): \begin{equation} h_{izk}=\frac{\beta_{kz} (u_{ik}+v_{ik})}{\sum_{k'} \beta_{k'z} (u_{ik'}+v_{ik'})} \quad,\quad \rho_{ijkl}^{(\alpha)} =\frac{u_{ik}v_{jl}w_{kl}^{(\alpha)}}{\sum_{k',l'} u_{ik'}v_{jl'}w_{k'l'}^{(\alpha)}} \nonumber \ee \quad 2. Update parameters $\Theta$ (M-Step): \BlankLine \quad \quad \quad i) for each node $i$ and community $k$ update memberships: \begin{eqnarray} \quad u_{ik} &=& \frac{\gamma \, \sum_z \,x_{iz} h_{izk} + (1-\gamma)\, \sum_{j,l,\alpha}A_{ij}^{(\alpha)} \rho_{ijkl}^{(\alpha)}}{ \gamma + (1-\gamma) \sum_{j,\alpha}A_{ij}^{(\alpha)}} \nonumber\\ \quad v_{ik}&=& \frac{\gamma \,\sum_z\, x_{iz} h_{izk} + (1-\gamma)\, \sum_{j,l,\alpha}A_{ji}^{(\alpha)} \rho_{jilk}^{(\alpha)}}{ \gamma + (1-\gamma) \sum_{j,\alpha}A_{ji}^{(\alpha)}} \nonumber \end{eqnarray} \quad \quad \quad ii) if $\gamma \neq 1$, for each pair of communities $(k,l)$ update network-affinity matrix: \begin{equation} \quad w_{kl}^{(\alpha)} = \frac{\sum_{i,j} A_{ij}^{(\alpha)} \rho_{ijkl}^{(\alpha)}}{\sum_i u_{ik} \sum_j v_{jl}} \nonumber \ee \quad \quad \quad iii) if $\gamma \neq 0$, for each pair of community-attribute $(k,z)$ update attribute-affinity matrix: \begin{equation} \quad \beta_{kz} = \frac{\sum_{i} \,x_{iz} \,h_{izk}}{\sum_{i,z} \,x_{iz} \,h_{izk}} \nonumber \ee \caption{\mbox{{\small MTCOV}} - EM algorithm} \label{alg:EM} \end{algorithm} \subsection*{Evaluation metrics} We adopt two different criteria for performance evaluation, based on having or not having access to ground-truth values for the community assignments. The first case applies to synthetic-generated data, the second to both synthetic and real-world data. We explain performance metrics in detail below. \paragraph{Ground-truth available} In the presence of a known partition, we measure the agreement between the set of ground-truth communities $\mathcal{C}^*$ and the set of detected communities $\mathcal{C}$ using metrics for recovering both hard and soft assignments. For hard partitions, the idea is to match every detected community with its most similar ground-truth community and measure similarity $\delta(\mathcal{C}_i^*, \mathcal{C}_j)$ (and vice versa for every ground-truth community matched against a detected community) as done by Yang et al.\cite{yang2013community}. The final performance is the average of these two comparisons: \begin{equation} \frac{1}{2|\mathcal{C}^*|} \sum_{\mathcal{C}_i^*\in \mathcal{C}^*} \max_{\mathcal{C}_j\in \mathcal{C}} \delta(\mathcal{C}_i^*, \mathcal{C}_j) + \frac{1}{2|\mathcal{C}|} \sum_{\mathcal{C}_j\in \mathcal{C}} \max_{\mathcal{C}_i^*\in \mathcal{C}^*} \delta(\mathcal{C}_i^*, \mathcal{C}_j) \label{eq: validation} \end{equation} where here we consider as similarity metric $\delta(\cdot)$ the F1-score and the Jaccard similarity. In both cases, the final score is a value between 0 and 1, where 1 indicates the perfect matching between detected and ground-truth communities. For soft partitions, we consider two standard metrics for measuring distance between vectors as done by De Bacco et al.\cite{Multitensor}, such as \textit{cosine similarity} (CS) and $L_{1}$ error, averaged over the nodes: \begin{eqnarray} CS(U,U^{0})&=& \f{1}{N} \sum_{i=1}^{N} \f{u_{i} \cdot u^{0}_{i}}{||u_{i}||_{2}\,||u^{0}_{i}||_{2}} =\f{1}{N} \sum_{i=1}^{N} \sum_{k=1}^{C} \f{u_{ik} \, u^{0}_{ik}}{||u_{i}||_{2}\,||u^{0}_{i}||_{2}} \\ L_{1}(U,U^{0})&=& \f{1}{2N} \sum_{i=1}^{N}|| u_{i}-u_{i}^{0}||_{1}=\f{1}{2N} \sum_{i=1}^{N}\sum_{k=1}^{C}| u_{ik}-u_{ik}^{0}| \quad, \end{eqnarray} where $u_{i}$ is the $C$-dimensional vector containing the $i$-th row of $U$, representing the detected membership and similarly for $u_{i}^{0}$ for the ground-truth $U^{0}$. The factor $1/2$ ensures that the $L_{1}$ distance ranges from 0 for identical distributions to 1 for distributions with disjoint support. Similarly to the what done for hard partitions, we match the ground-truth and detected communities by choosing the permutation of $C$ groups that gives the highest cosine similarity or smallest $L_{1}$ distance. \paragraph{Ground-truth not available} In the absence of ground-truth, these metrics cannot be computed, and one must resort to other approaches for model evaluation. Here we consider performance in prediction tasks when hiding part of the input datasets while fitting the parameters, and in particular on the extent to which partial knowledge of network edges helps predict node attributes and vice versa. Thus we consider a measure for link-prediction and one for correct retrieval of the attributes. For link-prediction, we used the AUC statistic, equivalent to the area under the receiver-operating characteristic (ROC) curve \cite{hanley1982meaning}. It represents the probability that a randomly chosen missing connection (a true positive) is given a higher score than a randomly chosen pair of unconnected vertices (a true negative). Thus, an AUC statistic equal to $0.5$ indicates random chance, while the closer it is to $1$, the more our model's predictions are better than chance. We measure the probability of observing an edge as the predicted expected Poisson parameters of equation (\ref{eqn:meanPoisson}). For the attribute, instead, we use the accuracy as a quality measure. For each node, we compute the predicted expected multinomial parameter $\pi_i$ using equation (\ref{eq: piz}). We then assign to each node the category with the highest probability, computing the accuracy as the ratio between the correctly classified examples over the total number of nodes. As baselines, we compare with the accuracy obtained with a random uniform probability and the highest relative frequency observed in the training set. \subsection*{Cross-validation tests and hyperparameter settings} We perform prediction tasks using cross-validation with 80-20 splits: we use $80\%$ of the data for training the parameters and then measure AUC and accuracy on the remaining $20\%$ test set. Specifically, for the network topology, we hold out $20\%$ of the triples $(i,j,\alpha)$; for the attributes, we hold out $20\%$ of the entries of the categorical vector.\\ Our model has two hyperparameters, the scaling parameter $\gamma$ and the number of communities $C$. We estimate them by using $5$-fold cross-validation along with grid search to range across their possible values. We then select the combination ($\hat{C},\hat{\gamma}$) that returns the best average performance over the cross-validation runs. Standard cross-validation considers performance in terms of a particular metric. However, here we have two possible ones which are qualitatively different, i.e., AUC and accuracy. Depending on the task at hand, one can define performance as a combination of the two, bearing in mind that the values of ($\hat{C},\hat{\gamma})$ at the maximum of either of them might not coincide. Here we select ($\hat{C},\hat{\gamma})$ as the values are jointly closer to both the maximum values. In the experiments where one of the two hyperparameters is fixed \textit{a priori}, we run the same procedure but vary with grid search only the unknown hyperparameter.
{'timestamp': '2020-04-21T02:24:07', 'yymm': '2004', 'arxiv_id': '2004.09160', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09160'}
arxiv
\section{Introduction} Word embeddings have become an integral part of modern NLP. They capture semantic and syntactic similarities and are typically used as features in training NLP models for diverse tasks like named entity tagging, sentiment analysis, and classification, to name a few. Word embeddings are learnt in an unsupervised manner from a large text corpora and a number of pre-trained embeddings are readily available. The quality of the word embeddings, however, depends on various factors like the size and genre of training corpora as well as the training method used. This has led to ensemble approaches for creating meta-embeddings from different original embeddings \citep{yin16,bollegala18naacl,bollegala18iccl,oneilly2020meta}. Meta-embeddings are appealing because: (a) they can improve quality of embeddings on account of noise cancellation and diversity of data sources and algorithms, (b) no need to retrain the model, (c) the original corpus may not be available, and (d) may increase vocabulary coverage. Various approaches have been proposed to learn meta-embeddings and can be broadly classified into two categories: (a) simple linear methods like averaging or concatenation, or a low-dimensional projection via singular value projection \citep{yin16,bollegala18naacl} and (b) non-linear methods that aim to learn meta-embeddings as shared representation using auto-encoding or transformation between common representation and each embedding set \citep{muromagi-etal-2017-linear,bollegala2017think,bollegala18iccl,oneilly2020meta}. In this work, we focus on simple linear methods such as averaging and concatenation for computing meta-embeddings, which are very easy to implement and have shown highly competitive performance \citep{yin16,bollegala18naacl}. Due to the nature of the underlying embedding generation algorithms \citep{mikolov13bnips,pennington14}, correspondences between dimensions, e.g., of two embeddings $x\in\mathbb{R}^d$ and $z\in\mathbb{R}^d$ of the same word, are usually not known. Hence, averaging may be detrimental in cases where the dimensions are negatively correlated. Consider the scenario where $z\coloneqq-x$. Here, simple averaging of $x$ and $z$ would result in the zero vector. Similarly, when $z$ is a (dimension-wise) permutation of $x$, simple averaging would result in a sub-optimal meta-embedding vector than performing averaging of \textit{aligned} embeddings. Therefore, we propose to align the embeddings (of a given word) as an important first step towards generating meta-embeddings. To this end, we develop a geometric framework for learning meta-embeddings, by aligning different embeddings in a common latent space, where the dimensions of different embeddings (of a given word) are in coherence. Mathematically, we perform different orthogonal transformations of the source embeddings to learn a latent space along with a Mahalanobis metric that scales different features appropriately. The meta-embeddings are, subsequently, learned in the latent space, e.g., using averaging or concatenation. Empirical results on the word similarity and the word analogy tasks show that the proposed geometrically aligned meta-embeddings outperform strong baselines such as the plain averaging and the plain concatenation models. \section{Proposed Geometric Modeling} Consider two (monolingual) embeddings $x_i\in\mathbb{R}^d$ and $z_i\in\mathbb{R}^d$ of a given word $i$ in a $d$-dimensional space. As discussed earlier, embeddings generated from different algorithms \citep{mikolov13bnips,pennington14} may express different characteristics (of the same word). Hence, the goal of learning a meta-embedding $w_i$ (corresponding to word $i$) is to generate a representation that inherits the properties of the different source embeddings (e.g., $x_i$ and $z_i$). Our framework imposes orthogonal transformations on the given source embeddings to enable alignment. In this latent space, we additionally induce the Mahalanobis metric to incorporate the feature correlation information \citep{mjaw19a}. The Mahalanobis similarity generalizes the cosine similarity measure, which is commonly used for evaluating the relatedness between word embeddings. The combination of the orthogonal transformation and Mahalanobis metric learning allows to capture any \textit{affine} relationship between different available source embeddings of a given word \citep{bonnabel09a,mishra14}. Overall, we formulate the problem of learning geometric transformations -- the orthogonal rotations and the metric scaling -- via a binary classification problem. The meta-embeddings are subsequently computed using these transformations. The following sections formalize the proposed latent space and meta-embedding models. \subsection{Learning the Latent Space} In this section, we learn the latent space using geometric transformations. Let ${\mathbf U}\in \mathcal{M}^d$ and ${\mathbf V} \in \mathcal{M}^d$ be orthogonal transformations for embeddings $x_i$ and $z_i$, respectively, for all words $i$. Here $\mathcal{M}^d$ represents the set of $d\times d$ orthogonal matrices. The aligned embeddings in the latent space corresponding to $x_i$ and $z_i$ can then be expressed as ${\mathbf U} x_i$ and ${\mathbf V} z_i$, respectively. We next induce the Mahalanobis metric $\mathbf B$ in this (aligned) latent space, where $\mathbf B$ is a $d\times d$ symmetric positive-definite matrix. In this latent space, the similarity between the two embeddings $x_i$ and $z_i$ is given by the following expression: $({\mathbf U} x_i)^\top \mathbf B ({\mathbf V} z_i)$. An equivalent interpretation is that the expression $({\mathbf U} x_i)^\top \mathbf B ({\mathbf V} z_i)$ boils down to the standard scalar product (cosine similarity) between $\mathbf B^\frac{1}{2}{\mathbf U} x_i$ and $\mathbf B^\frac{1}{2}{\mathbf V} z_i$, where $\mathbf B^\frac{1}{2}$ denotes the matrix square root of the symmetric positive definite matrix $\mathbf B$. The orthogonal transformations as well as the Mahalanobis metric are learned via the following binary classification problem: pairs of word embeddings $\{x_i,z_i\}$ of the same word $i$ belong to the positive class while pairs $\{x_i,z_j\}$ belong to the negative class (for $i\neq j$). We consider the similarity between the two embeddings in the latent space as the decision function of the proposed binary classification problem. Let ${\mathbf X} = [x_1,\ldots,x_n]\in\mathbb{R}^{d\times n}$ and ${\mathbf Z} = [z_1,\ldots,z_n]\in\mathbb{R}^{d\times n}$ be the word embedding matrices for $n$ words, where the columns correspond to different words. In addition, let ${\mathbf Y}$ denote the label matrix, where ${\mathbf Y}_{ii}=1$ for $i=1,\ldots,n$ and ${\mathbf Y}_{ij}=0$ for $i\neq j$. The proposed optimization problem employs the simple to optimize square loss function: \begin{equation}\label{eqn:geommavg} \mathop{\rm min}\limits_{\substack{{\mathbf U},{\mathbf V}\in\mathcal{M}^d,\\\mathbf B\succ0}} \norm{{\mathbf X}^\top{\mathbf U}^\top\mathbf B{\mathbf V}{\mathbf Z} - {\mathbf Y}}^2 + C\norm{\mathbf B}^2, \end{equation} where $\|\cdot\|$ is the Frobenius norm and $C>0$ is the regularization parameter. \subsection{Averaging and Concatenation in Latent Space} Meta-embeddings constructed by averaging or concatenating the given word embeddings have been shown to obtain highly competitive performance \citep{yin16,bollegala18naacl}. Hence, we propose to learn meta-embeddings as averaging or concatenation in the learned latent space. \subsubsection*{Geometry-Aware Averaging} The meta-embedding $w_i$ of a word $i$ is generated as an average of the (aligned) word embeddings in the latent space. The latent space representation of $x_i$, as a function of orthogonal transformation ${\mathbf U}$ and metric $\mathbf B$, is $\mathbf B^\frac{1}{2}{\mathbf U} x_i$ \citep{mjaw19a}. Hence, we obtain $w_i = \texttt{average}(\mathbf B^\frac{1}{2}{\mathbf U} x_i,\mathbf B^\frac{1}{2}{\mathbf V} z_i)=(\mathbf B^\frac{1}{2}{\mathbf U} x_i+\mathbf B^\frac{1}{2}{\mathbf V} z_i)/2$. It should be noted that the proposed geometry-aware averaging approach generalizes \citep{bollegala18naacl}, which is now a particular case in our framework by choosing ${\mathbf U}$, ${\mathbf V}$, and $\mathbf B$ as identity matrices. Our framework easily generalizes to the case of more than two source embeddings, by learning different source-embedding specific orthogonal transformations and a common Mahalanobis metric. \subsubsection*{Geometry-Aware Concatenation} We next propose to concatenate the aligned embeddings in the learned latent space. For a given word $i$, with $x_i$ and $z_i$ as different source embeddings, the meta-embeddings $w_i$ learned by the proposed geometry-aware concatenation model is $w_i=\texttt{concatenation}(\mathbf B^\frac{1}{2}{\mathbf U} x_i,\mathbf B^\frac{1}{2}{\mathbf V} z_i)=[(\mathbf B^\frac{1}{2}{\mathbf U} x_i)^\top,(\mathbf B^\frac{1}{2}{\mathbf V} z_i)^\top]^\top$. It can be easily observed that the plain concatenation \citep{yin16} is a special case of the proposed geometry-aware concatenation (by setting $\mathbf B={\mathbf U}={\mathbf V}={\mathbf I}$, where ${\mathbf I}$ is a $d$-dimensional identity matrix). \subsection{Optimization} The proposed optimization problem (\ref{eqn:geommavg}) employs square loss function and $\ell_2$-norm regularization, both of which are well-studied in literature. In addition, the proposed problem involves optimization over smooth constraint sets such as the set of symmetric positive definite matrices and the set of orthogonal matrices. Such sets have well-known Riemannian manifold structure \citep{Lee03a} that allows to propose computationally efficient iterative optimization algorithms. We employ the popular Riemannian optimization framework \citep{absil08a} to solve (\ref{eqn:geommavg}). Recently, \citet{mjaw19a} have studied a similar optimization problem in the context of learning cross-lingual word embeddings. Our implementation is done using the Pymanopt toolbox \citep{townsend16a}, which is a publicly available Python toolbox for Riemannian optimization algorithms. In particular, we use the conjugate gradient algorithm of Pymanopt. For, this we need only supply the objective function of (\ref{eqn:geommavg}). This can be done efficiently as the numerical cost of computing the objective function is $O(nd^2)$. The overall computational cost of our implementation scales linearly with the number of words in the vocabulary sets. \begin{table*}[t] \setlength{\tabcolsep}{3.5pt} \begin{center} \begin{tabular}{l|l|ccccccc|cccc} \toprule & Model & RG & MC & WS & MTurk & RW & SL & Avg.(WS) & MSR & GL & SemEvaL & Avg.(WA) \\ \midrule \parbox[t]{2mm}{\multirow{3}{*}{\rotatebox[origin=c]{90}{indv.}}} & CBOW & $76.1$ & $80.0$ & $77.2$ & $68.4$ & $53.4$ & $44.2$ & $66.5$ & $71.7$ & $55.4$ & $20.4$ & $49.2$\\ & GloVe & $82.9$ & $84.0$ & $79.6$ & $70.0$ & $48.7$ & $45.3$ & $68.4$ & $69.3$ & $75.2$ & $18.6$ & $54.4$\\ & fastText & $83.8$ & $82.5$ & $83.5$ & $73.3$ & $58.0$ & $46.4$ & $71.2$ & $78.7$ & $71.0$ & $22.5$ & $57.4$\\ \midrule \parbox[t]{2mm}{\multirow{4}{*}{\rotatebox[origin=c]{90}{Gl.+ CB.}}} & CONC & $81.1$ & $84.6$ & $\mathbf{81.4}$ & $71.9$ & $54.6$ & $46.0$ & $69.9$ & $76.6$ & $69.9$ & $\mathbf{20.1}$ & $55.5$\\ & AVG & $81.5$ & $83.7$ & $79.4$ & $\mathbf{72.1}$ & $52.9$ & $46.2$ & $69.3$ & $73.7$ & $66.9$ & $19.7$ & $53.4$\\ & Geo-CONC & $\mathbf{86.0}$ & $\mathbf{85.0}$ & $81.2$ & $70.5$ & $55.6$ & $\mathbf{48.2}$ & $\mathbf{71.1}$ & $\mathbf{78.1}$ & ${73.3}$ & $19.9$ & $\mathbf{57.1}$\\ & Geo-AVG & $85.8$ & $83.5$ & $81.2$ & $69.1$ & $\mathbf{55.7}$ & $\mathbf{48.2}$ & $70.6$ & $77.3$ & $72.3$ & $19.5$ & $56.3$\\ \midrule \parbox[t]{2mm}{\multirow{4}{*}{\rotatebox[origin=c]{90}{Gl.+ fa.}}} & CONC & $\mathbf{83.8}$ & $82.5$ & $83.4$ & $73.3$ & $57.9$ & $46.4$ & $71.2$ & $79.8$ & $71.7$ & $22.5$ & $58.0$\\ & AVG & $83.4$ & $82.1$ & $\mathbf{83.5}$ & $73.3$ & $\mathbf{58.0}$ & $46.5$ & $71.1$ & $79.7$ & $71.7$ & $22.4$ & $57.9$\\ & Geo-CONC & $83.7$ & $\mathbf{84.0}$ & $82.6$ & $\mathbf{74.6}$ & $55.1$ & $\mathbf{48.4}$ & $\mathbf{71.4}$ & $\mathbf{80.4}$ & $\mathbf{79.3}$ & $21.5$ & $\mathbf{60.4}$\\ & Geo-AVG & $83.6$ & $82.0$ & $82.7$ & $74.3$ & $57.0$ & $\mathbf{48.4}$ & $71.3$ & $79.1$ & $71.1$ & $\mathbf{23.1}$ & $57.8$\\ \midrule \parbox[t]{2mm}{\multirow{4}{*}{\rotatebox[origin=c]{90}{CB.+ fa.}}} & CONC & $83.8$ & $82.5$ & $\mathbf{83.5}$ & $73.6$ & $\mathbf{59.9}$ & $46.4$ & $71.6$ & $79.9$ & $75.8$ & $\mathbf{22.5}$ & $59.4$\\ & AVG & $83.7$ & $82.5$ & $83.4$ & $\mathbf{73.7}$ & $59.8$ & $46.4$ & $71.6$ & $79.9$ & $75.8$ & $\mathbf{22.5}$ & $59.4$\\ & Geo-CONC & $85.3$ & $84.3$ & $82.9$ & $73.6$ & $59.7$ & $\mathbf{47.4}$ & $72.2$ & $\mathbf{80.1}$ & $\mathbf{76.9}$ & $22.1$ & $\mathbf{59.7}$\\ & Geo-AVG & $\mathbf{85.5}$ & $\mathbf{84.6}$ & $82.9$ & $73.6$ & $59.7$ & $\mathbf{47.4}$ & $\mathbf{72.3}$ & $79.9$ & $\mathbf{76.9}$ & $22.0$ & $59.6$\\ \bottomrule \end{tabular} \caption{Generalization performance of the meta-embedding algorithms on the Word Similarity (WS) and Word Analogy (WA) tasks. The columns `Avg.(WS)' and `Avg.(WA)' correspond to the average performance on the WS and the WA tasks, respectively. The rows marked `indv.' correspond to the performance of individual source embeddings CBOW, GloVe, and fastText. The rows marked `Gl.+CB.' correspond to the performance of meta-embedding algorithms with GloVe and CBOW embeddings as input. Similarly, `Gl.+fa.' corresponds to GloVe and fastText embeddings and `CB.+fa.' implies CBOW and fastText embeddings. A meta-embedding result is highlighted if it obtains the best result on a dataset when compared with the corresponding source embeddings as well as other meta-embedding algorithms employing the same source embeddings. We observe that the best overall performance on both the tasks, word similarity and word analogy, is obtained by the proposed geometry-aware models for every pair of input source embeddings.}\label{table:geometa} \end{center} \end{table*} \section{Experiments} In this section, we evaluate the performance of the proposed meta-embedding models. \subsection{Evaluation Tasks and Datasets} We consider the following standard evaluation tasks \citep{yin16,bollegala18naacl}: \begin{itemize} \item \textbf{Word similarity}: in this task, we compare the human-annotated similarity scores between pairs of words with the corresponding cosine similarity computed via the constructed meta-embeddings. We report results on the following benchmark datasets: {\bf RG} \citep{rubenstein}, {\bf MC} \citep{miller}, {\bf WS} \citep{finkelstein}, {\bf MTurk} \citep{halawi}, {\bf RW} \citep{luong}, and {\bf SL} \citep{hill}. Following previous works \citep{yin16,bollegala18naacl,oneilly2020meta}, we report the Spearman correlation score (higher is better) between the cosine similarity (computed via meta-embeddings) and the human scores. \item \textbf{Word analogy}: in this task, the aim is to answer questions which have the form ``\textit{A is to B as C is to ?}'' \citep{mikolov13bnips}. After generating the meta-embeddings $a$, $b$, and $c$ (corresponding to terms \textit{A}, \textit{B}, and \textit{C}, respectively), the answer is chosen to be the term whose meta-embedding has the maximum cosine similarity with $(b-a+c)$ \citep{mikolov13bnips}. The benchmark datasets include {\bf MSR} \citep{msrgao}, {\bf GL} \citep{mikolov13bnips}, and {\bf SemEval} \citep{davidsemeval}. Following previous works \citep{yin16,bollegala18naacl,oneilly2020meta}, we report the percentage of correct answers for MSR and GL datasets, and the Spearman correlation score for SemEval. In both cases, a higher score implies better performance. \end{itemize} We learn the meta-embeddings from the following publicly available $300$-dimensional pre-trained word embeddings for English. \begin{itemize} \item \textbf{CBOW} \citep{mikolov13bnips}: has $929\,023$ word embeddings trained on Google News. \item \textbf{GloVe} \citep{pennington14}: has $1\,917\,494$ word embeddings trained on $42$B tokens of web data from the common crawl. \item \textbf{fastText} \citep{bojanowski17}: has $2\,000 \,000$ word embeddings trained on common crawl. \end{itemize} The meta-embeddings are learned on the common set of words from different pairs of the source embeddings. The number of common words between various source embeddings pairs are as follows: $154\,077$ (GloVe $\cap$ CBOW), $552\,168$ (GloVe $\cap $ fastText), and $641\,885$ (CBOW $\cap $ fastText). \subsection{Results and Discussion} The performance of our geometry-aware averaging and concatenation models, henceforth termed as Geo-AVG and Geo-CONC, respectively, are reported in Table~\ref{table:geometa}. We also report the performance of meta-embeddings models AVG \citep{bollegala18naacl} and CONC \citep{yin16}, which perform plain averaging and concatenation, respectively. In addition, we report the performance of individual source embeddings (CBOW, GloVe, and fastText), serving as a benchmark which the meta-embeddings algorithms should ideally surpass in order to justify their usage. We observe that the proposed geometry-aware models, Geo-AVG and Geo-CONC, outperform the individual source embeddings in all the datasets. The proposed models also easily surpass the AVG and CONC models in both the word similarity and the word analogy tasks. This shows that the alignment of word embedding spaces with orthogonal rotations and the Mahalanobis metric improves the overall quality of the meta-embeddings. \section{Conclusion} We propose a geometric framework for learning meta-embeddings of words from various sources of word embeddings. Our framework aligns the embeddings in a common latent space. The importance of learning the latent space is shown in several benchmark datasets, where the proposed algorithms (Geo-AVG and Geo-CONC) outperforms the plain averaging and the plain concatenation models. The proposed framework can be extended to generating sentence meta-embeddings, which remains a future research direction. \bibliographystyle{acl_natbib}
{'timestamp': '2020-04-21T02:25:45', 'yymm': '2004', 'arxiv_id': '2004.09219', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09219'}
arxiv
\section{Survey Personality Questions} \begin{longtable}[b]{|c||m{1.5cm}|m{1.4cm}|m{1.5cm}|m{1cm}|m{1.5cm}|} \hline \footnotesize \textbf{I see myself as someone ...} &\scriptsize Very Inaccurate & \scriptsize Moderately Inaccurate & \scriptsize Neither Inaccurate nor Accurate &\scriptsize Moderately Accurate &\scriptsize Very Accurate \\\hline \footnotesize \textbf{who is generally trusting} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{Don't like to draw attention to myself} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{Believe in the importance of art} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{tends to find fault in others} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{pays attention to details} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{Shirks duties} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{who is generally trusting} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{who is reserved} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{has a good word for everyone} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{insults people} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{feels comfortable around people} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{dislikes self} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{has a little to say} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{has frequent mood swings} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{often feels blue} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{does not like art} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{cuts others to pieces} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{is the life of the party} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{believes that others have good intentions} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{avoids philosophical discussions} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{makes friends easily} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{gets chores done rightaway} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{accepts people as they are} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{relaxed, handles stress well} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{does a thorough job} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{does just enough work to get by} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{enjoys going to art museums} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{often down in the dumps} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{always prepared} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{has few artistic interests} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{not easily bothered by things} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{knows how to captivate people} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{is not interested in abstract ideas} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{makes plans and sticks to them} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{doesn't see things as they are} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{is outgoing and sociable} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{doesn't talk a lot} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{gets back at others} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{tends to vote for the liberal candidates} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{has an active imagination} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{seldoms feel blue} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{carries out the plans} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{gets nervous easily} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{feels comfortable with self} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{panics easily} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{keeps in the background} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{finds it difficult to get down to work} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{tends to vote for conservative candidates} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{skilled in handling social situations} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{wastes time} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{tends to be lazy} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \footnotesize \textbf{respects others} &$\square$& $\square$ & $\square$ &$\square$ & $\square$ \\\hline \caption{} \label{tab:longtable1} \end{longtable} \onecolumn \section{Commonsense Survey and Results} \begin{longtable}[b]{|m{4cm}||c|c|c|c|c|c|c|c|} \hline \footnotesize \textbf{Question} &\scriptsize RFC & \scriptsize DT & \scriptsize KNN &\scriptsize SVM-Linear &\scriptsize SVM-Poly &\scriptsize SVM-rbf &\scriptsize Perceptron &\scriptsize MLP \\\hline {\scriptsize What are your gender/color priorities for the US commander in chief?} &\scriptsize 84\% &\scriptsize 70\% &\scriptsize 83\% &\scriptsize 77\% &\scriptsize 77\% &\scriptsize 83\% &\scriptsize 83\% &\scriptsize 72\% \\\hline {\scriptsize President Trumps travel ban is} &\scriptsize 82\% &\scriptsize 72\% &\scriptsize 78\% &\scriptsize 76\% &\scriptsize 77\% &\scriptsize 79\% &\scriptsize 70\% &\scriptsize 71\% \\\hline {\scriptsize When you're looking for work, name a way you might find out about the job opening} &\scriptsize 78\% &\scriptsize 66\% &\scriptsize 75\% &\scriptsize 79\% &\scriptsize 75\% &\scriptsize 79\% &\scriptsize 58\% &\scriptsize 70\% \\\hline {\scriptsize{An engineer who lost her father in childhood in a shooting accident hates guns and blames gunmakers for her loss.However, the only job offer that she has received is from a big gunmaker company. If she declines the job offer (refusing to make guns that can kill other kids' dads), her retired mother must sell her house to pay off her school loan.She should ...}} &\scriptsize 78\% &\scriptsize 66\% &\scriptsize 75\% &\scriptsize 79\% &\scriptsize 75\% &\scriptsize 79\% &\scriptsize 58\% &\scriptsize 70\% \\\hline {\scriptsize Name something your body tells you it's time to do.} &\scriptsize 73\% &\scriptsize 59\% &\scriptsize 70\% &\scriptsize 70\% &\scriptsize 70\% &\scriptsize 72\% &\scriptsize 47\% &\scriptsize 64\% \\\hline {\scriptsize What is your opinion about creating united health care insurance by slightly increasing the sales/income tax?} &\scriptsize 73\% &\scriptsize 59\% &\scriptsize 70\% &\scriptsize 70\% &\scriptsize 70\% &\scriptsize 72\% &\scriptsize 47\% &\scriptsize 64\% \\\hline {\scriptsize You share values with} &\scriptsize 70\% &\scriptsize 59\% &\scriptsize 54\% &\scriptsize 64\% &\scriptsize 59\% &\scriptsize 66\% &\scriptsize 47\% &\scriptsize 57\% \\\hline {\scriptsize Name something that people like to do in their backyard} &\scriptsize 70\% &\scriptsize 59\% &\scriptsize 54\% &\scriptsize 64\% &\scriptsize 59\% &\scriptsize 66\% &\scriptsize 47\% &\scriptsize 57\% \\\hline {\scriptsize Name something that's embarrassing to fall asleep while doing.} &\scriptsize 69\% &\scriptsize 61\% &\scriptsize 65\% &\scriptsize 65\% &\scriptsize 65\% &\scriptsize 69\% &\scriptsize 63\% &\scriptsize 60\% \\\hline {\scriptsize A patient who has agreed to donate his vital organs is in a coma and lives only with the assistance of life-support machines,but will pass away in the next few days anyway. There are a few patients who need the organs withing a few hours to survive. Which one do you agree with:} &\scriptsize 67\% &\scriptsize 54\% &\scriptsize 64\% &\scriptsize 65\% &\scriptsize 62\% &\scriptsize 67\% &\scriptsize 62\% &\scriptsize 68\% \\\hline {\scriptsize Name a reason people change their names} &\scriptsize 66\% &\scriptsize 54\% &\scriptsize 65\% &\scriptsize 60\% &\scriptsize 61\% &\scriptsize 66\% &\scriptsize 59\% &\scriptsize 61\% \\\hline {\scriptsize Why did Hillary Clinton lose the presidential election?} &\scriptsize 65\% &\scriptsize 59\% &\scriptsize 57\% &\scriptsize 62\% &\scriptsize 61\% &\scriptsize 65\% &\scriptsize 58\% &\scriptsize 58\% \\\hline {\scriptsize If a scientific theory does not agree with your religious belief:} &\scriptsize 65\% &\scriptsize 55\% &\scriptsize 60\% &\scriptsize 61\% &\scriptsize 65\% &\scriptsize 65\% &\scriptsize 58\% &\scriptsize 56\% \\\hline {\scriptsize Tell me the most important habit a mom should teach her son.} &\scriptsize 63\% &\scriptsize 54\% &\scriptsize 56\% &\scriptsize 64\% &\scriptsize 62\% &\scriptsize 60\% &\scriptsize 55\% &\scriptsize 60\% \\\hline {\scriptsize Name something that people do to their faces} &\scriptsize 62\% &\scriptsize 56\% &\scriptsize 57\% &\scriptsize 62\% &\scriptsize 59\% &\scriptsize 65\% &\scriptsize 58\% &\scriptsize 62\% \\\hline {\scriptsize If you were arrested and could make only one call, whom would you call?} &\scriptsize 62\% &\scriptsize 50\% &\scriptsize 56\% &\scriptsize 59\% &\scriptsize 58\% &\scriptsize 62\% &\scriptsize 59\% &\scriptsize 50\% \\\hline {\scriptsize Name something you've stayed up all night worrying about.} &\scriptsize 61\% &\scriptsize 55\% &\scriptsize 56\% &\scriptsize 55\% &\scriptsize 54\% &\scriptsize 59\% &\scriptsize 53\% &\scriptsize 52\% \\\hline {\scriptsize Is this a big deal if the fired missile from Yemen to Saudi Arabia was in fact made in Iran?} &\scriptsize 60\% &\scriptsize 54\% &\scriptsize 57\% &\scriptsize 59\% &\scriptsize 59\% &\scriptsize 61\% &\scriptsize 44\% &\scriptsize 58\% \\\hline \scriptsize{A US-based solar panel manufacturing company can no longer compete with fully-automated companies in Asia that manufacture solar panels 50\% cheaper. Hundreds of workers will lose their jobs in the US if the company is closed. The company should ... }&\scriptsize 60\% &\scriptsize 55\% &\scriptsize 56\% &\scriptsize 58\% &\scriptsize 60\% &\scriptsize 63\% &\scriptsize 60\% &\scriptsize 55\% \\\hline {\scriptsize Name something that your boss could tell you that would come as a big shock.} &\scriptsize 60\% &\scriptsize 55\% &\scriptsize 54\% &\scriptsize 55\% &\scriptsize 55\% &\scriptsize 55\% &\scriptsize 52\% &\scriptsize 52\% \\\hline {\scriptsize In a smartphone, the main issue for you is} &\scriptsize 59\% &\scriptsize 55\% &\scriptsize 57\% &\scriptsize 59\% &\scriptsize 60\% &\scriptsize 59\% &\scriptsize 50\% &\scriptsize 56\% \\\hline {\scriptsize Name something people do when riding in the back of a taxicab} &\scriptsize 59\% &\scriptsize 53\% &\scriptsize 52\% &\scriptsize 57\% &\scriptsize 55\% &\scriptsize 57\% &\scriptsize 57\% &\scriptsize 43\% \\\hline {\scriptsize If money is not an issue, you would like to buy} &\scriptsize 59\% &\scriptsize 55\% &\scriptsize 51\% &\scriptsize 50\% &\scriptsize 54\% &\scriptsize 57\% &\scriptsize 54\% &\scriptsize 50\% \\\hline {\scriptsize Name something specific you might remember about one of your teachers from high school.} &\scriptsize 58\% &\scriptsize 52\% &\scriptsize 53\% &\scriptsize 59\% &\scriptsize 59\% &\scriptsize 59\% &\scriptsize 53\% &\scriptsize 53\% \\\hline {\scriptsize Name a reason a young man might join the army} &\scriptsize 57\% &\scriptsize 52\% &\scriptsize 51\% &\scriptsize 54\% &\scriptsize 56\% &\scriptsize 57\% &\scriptsize 50\% &\scriptsize 55\% \\\hline {\scriptsize Name a reason you might ask the manager of a hotel for another room.} &\scriptsize 57\% &\scriptsize 53\% &\scriptsize 55\% &\scriptsize 62\% &\scriptsize 60\% &\scriptsize 60\% &\scriptsize 58\% &\scriptsize 57\% \\\hline {\scriptsize You are tired of a driver who is tailgating you for over an hour, what would you do?} &\scriptsize 57\% &\scriptsize 54\% &\scriptsize 56\% &\scriptsize 56\% &\scriptsize 56\% &\scriptsize 58\% &\scriptsize 58\% &\scriptsize 55\% \\\hline {\scriptsize Name a way you can tell that your child is lying} &\scriptsize 57\% &\scriptsize 52\% &\scriptsize 53\% &\scriptsize 45\% &\scriptsize 48\% &\scriptsize 54\% &\scriptsize 53\% &\scriptsize 50\% \\\hline {\scriptsize If you have ever been fined for any driving violations, it has most likely been for ...} &\scriptsize 57\% &\scriptsize 48\% &\scriptsize 57\% &\scriptsize 56\% &\scriptsize 58\% &\scriptsize 57\% &\scriptsize 52\% &\scriptsize 59\% \\\hline {\scriptsize The politician who wins the election is usually the person with the most what?} &\scriptsize 57\% &\scriptsize 52\% &\scriptsize 56\% &\scriptsize 53\% &\scriptsize 54\% &\scriptsize 56\% &\scriptsize 48\% &\scriptsize 49\% \\\hline \scriptsize Name something that you'd like to do all day without feeling any guilt. &\scriptsize 56\% &\scriptsize 51\% &\scriptsize 54\% &\scriptsize 53\% &\scriptsize 55\% &\scriptsize 58\% &\scriptsize 56\% &\scriptsize 51\% \\\hline \scriptsize Which food do you think should be chosen as the "National Food" of America? &\scriptsize 56\% &\scriptsize 49\% &\scriptsize 56\% &\scriptsize 55\% &\scriptsize 57\% &\scriptsize 56\% &\scriptsize 54\% &\scriptsize 52\% \\\hline \scriptsize Name something most people clean at least once a day. &\scriptsize 55\% &\scriptsize 55\% &\scriptsize 54\% &\scriptsize 55\% &\scriptsize 52\% &\scriptsize 54\% &\scriptsize 50\% &\scriptsize 52\% \\\hline \scriptsize Name a reason why people sometimes need to take a day off from the work. &\scriptsize 54\% &\scriptsize 51\% &\scriptsize 53\% &\scriptsize 52\% &\scriptsize 51\% &\scriptsize 58\% &\scriptsize 54\% &\scriptsize 54\% \\\hline \scriptsize What's the hardest part of your budget to cut out? &\scriptsize 54\% &\scriptsize 39\% &\scriptsize 52\% &\scriptsize 43\% &\scriptsize 47\% &\scriptsize 54\% &\scriptsize 33\% &\scriptsize 54\% \\\hline {\scriptsize Name a tip people give you on how to get rich.} &\scriptsize 53\% &\scriptsize 52\% &\scriptsize 52\% &\scriptsize 49\% &\scriptsize 48\% &\scriptsize 56\% &\scriptsize 49\% &\scriptsize 52\% \\\hline {\scriptsize Where would you look to find out how old someone is?} &\scriptsize 52\% &\scriptsize 53\% &\scriptsize 51\% &\scriptsize 55\% &\scriptsize 54\% &\scriptsize 55\% &\scriptsize 49\% &\scriptsize 53\% \\\hline {\scriptsize Name a technique people use to remember things.} &\scriptsize 51\% &\scriptsize 50\% &\scriptsize 48\% &\scriptsize 48\% &\scriptsize 50\% &\scriptsize 51\% &\scriptsize 53\% &\scriptsize 52\% \\\hline {\scriptsize Name something that's important to parents when house hunting?} &\scriptsize 50\% &\scriptsize 39\% &\scriptsize 42\% &\scriptsize 49\% &\scriptsize 46\% &\scriptsize 50\% &\scriptsize 46\% &\scriptsize 38\% \\\hline {\scriptsize Tell me a reason why a man would want to have a son.} &\scriptsize 50\% &\scriptsize 48\% &\scriptsize 49\% &\scriptsize 51\% &\scriptsize 49\% &\scriptsize 52\% &\scriptsize 49\% &\scriptsize 48\% \\\hline {\scriptsize Name a reason you might make your spouse get out of bed at the middle of the night } &\scriptsize 48\% &\scriptsize 43\% &\scriptsize 37\% &\scriptsize 44\% &\scriptsize 42\% &\scriptsize 40\% &\scriptsize 39\% &\scriptsize 39\% \\\hline {\scriptsize Many jobs will be lost in the next few decades due to smart robots and unemployment will thus increase. Therefore, } &\scriptsize 48\% &\scriptsize 36\% &\scriptsize 39\% &\scriptsize 40\% &\scriptsize 41\% &\scriptsize 48\% &\scriptsize 39\% &\scriptsize 37\% \\\hline {\scriptsize When you pick a password for your phone, you pick a password that is.} &\scriptsize 48\% &\scriptsize 31\% &\scriptsize 41\% &\scriptsize 40\% &\scriptsize 40\% &\scriptsize 48\% &\scriptsize 37\% &\scriptsize 42\% \\\hline \scriptsize On a sunny day, in a freeway with the maximum speed of 60 miles per hour if there is no police officer, you will typically drive with a speed ... &\scriptsize 50\% &\scriptsize 51\% &\scriptsize 52\% &\scriptsize 50\% &\scriptsize 52\% &\scriptsize 50\% &\scriptsize 48\% &\scriptsize 57\% \\\hline \scriptsize If money is not an issue, you will buy a driver-less car &\scriptsize 47\% &\scriptsize 43\% &\scriptsize 39\% &\scriptsize 42\% &\scriptsize 44\% &\scriptsize 48\% &\scriptsize 45\% &\scriptsize 42\% \\\hline \scriptsize What should the US do if we learn that the false nuclear alarm in Hawaii was real but the North Korean missile exploded before reaching Hawaii: &\scriptsize 47\% &\scriptsize 39\% &\scriptsize 44\% &\scriptsize 40\% &\scriptsize 41\% &\scriptsize 48\% &\scriptsize 35\% &\scriptsize 41\% \\\hline \scriptsize If you are not in a hurry, which route would you choose to your destination: &\scriptsize 45\% &\scriptsize 37\% &\scriptsize 34\% &\scriptsize 39\% &\scriptsize 40\% &\scriptsize 47\% &\scriptsize 40\% &\scriptsize 35\% \\\hline \scriptsize True democracy can be implemented using smartphone voting, as people can vote every day on important issues and there is no need to have a costly congress or senate anymore. The people will finally be in charge! &\scriptsize 43\% &\scriptsize 35\% &\scriptsize 36\% &\scriptsize 37\% &\scriptsize 36\% &\scriptsize 41\% &\scriptsize 38\% &\scriptsize 38\% \\\hline \scriptsize You really like a luxury car that costs \$70,000 but you can only afford \$40,000. &\scriptsize 43\% &\scriptsize 34\% &\scriptsize 37\% &\scriptsize 33\% &\scriptsize 35\% &\scriptsize 43\% &\scriptsize 43\% &\scriptsize 38\% \\\hline \scriptsize Name something you hope you never find in your house. &\scriptsize 40\% &\scriptsize 24\% &\scriptsize 34\% &\scriptsize 30\% &\scriptsize 32\% &\scriptsize 39\% &\scriptsize 24\% &\scriptsize 29\% \\\hline \scriptsize Name a subject that sons discuss with their fathers rather than with their mothers. &\scriptsize 40\% &\scriptsize 37\% &\scriptsize 39\% &\scriptsize 43\% &\scriptsize 39\% &\scriptsize 45\% &\scriptsize 30\% &\scriptsize 38\% \\\hline \scriptsize Besides being fast, name something people like about fast food. &\scriptsize 39\% &\scriptsize 35\% &\scriptsize 35\% &\scriptsize 35\% &\scriptsize 36\% &\scriptsize 40\% &\scriptsize 36\% &\scriptsize 35\% \\\hline {\scriptsize Name something one family member might steal from another.} &\scriptsize 37\% &\scriptsize 38\% &\scriptsize 30\% &\scriptsize 32\% &\scriptsize 32\% &\scriptsize 37\% &\scriptsize 34\% &\scriptsize 33\% \\\hline {\scriptsize A study at the University of Washington showed that by increasing the minimum wage, unemployment rate will increase, therefore} &\scriptsize 37\% &\scriptsize 29\% &\scriptsize 36\% &\scriptsize 33\% &\scriptsize 34\% &\scriptsize 37\% &\scriptsize 29\% &\scriptsize 34\% \\\hline {\scriptsize Name a reason you might pull your car over to the side of the road.} &\scriptsize 37\% &\scriptsize 36\% &\scriptsize 36\% &\scriptsize 30\% &\scriptsize 30\% &\scriptsize 37\% &\scriptsize 26\% &\scriptsize 31\% \\\hline {\scriptsize Name something that would be smart to know how to ask for in a foreign country.} &\scriptsize 37\% &\scriptsize 35\% &\scriptsize 33\% &\scriptsize 36\% &\scriptsize 32\% &\scriptsize 34\% &\scriptsize 36\% &\scriptsize 32\% \\\hline {\scriptsize Name something you do while driving, even though you know it's wrong} &\scriptsize 36\% &\scriptsize 32\% &\scriptsize 35\% &\scriptsize 34\% &\scriptsize 34\% &\scriptsize 40\% &\scriptsize 31\% &\scriptsize 33\% \\\hline {\scriptsize As micro sized robots will be developed soon,people can be filmed anytime and anywhere without their knowledge, which will destroy their privacy.} &\scriptsize 35\% &\scriptsize 26\% &\scriptsize 34\% &\scriptsize 36\% &\scriptsize 36\% &\scriptsize 37\% &\scriptsize 32\% &\scriptsize 31\% \\\hline {\scriptsize Name something people do to guard against wrinkles} &\scriptsize 34\% &\scriptsize 27\% &\scriptsize 28\% &\scriptsize 31\% &\scriptsize 31\% &\scriptsize 34\% &\scriptsize 32\% &\scriptsize 36\% \\\hline {\scriptsize Name a reason why someone might go a whole day without eating.} &\scriptsize 33\% &\scriptsize 36\% &\scriptsize 34\% &\scriptsize 36\% &\scriptsize 31\% &\scriptsize 34\% &\scriptsize 34\% &\scriptsize 34\% \\\hline {\scriptsize Name a Doctor's order people never take seriously.} &\scriptsize 32\% &\scriptsize 25\% &\scriptsize 27\% &\scriptsize 31\% &\scriptsize 33\% &\scriptsize 32\% &\scriptsize 29\% &\scriptsize 30\% \\\hline {\scriptsize We asked 100 married women... If your husband asked you for a divorce Sunday night, what's the first thing you'd do Monday morning?} &\scriptsize 30\% &\scriptsize 30\% &\scriptsize 27\% &\scriptsize 28\% &\scriptsize 26\% &\scriptsize 29\% &\scriptsize 31\% &\scriptsize 31\% \\\hline {\scriptsize Name a question a person who's afraid of flight might ask a flight attendant.} &\scriptsize 30\% &\scriptsize 24\% &\scriptsize 26\% &\scriptsize 22\% &\scriptsize 23\% &\scriptsize 32\% &\scriptsize 30\% &\scriptsize 32\% \\\hline {\scriptsize If time flies when you're having fun, name a place it crawls} &\scriptsize 29\% &\scriptsize 24\% &\scriptsize 30\% &\scriptsize 32\% &\scriptsize 30\% &\scriptsize 30\% &\scriptsize 26\% &\scriptsize 29\% \\\hline {\scriptsize Name something specific everyone complains about} &\scriptsize 21\% &\scriptsize 18\% &\scriptsize 22\% &\scriptsize 23\% &\scriptsize 18\% &\scriptsize 25\% &\scriptsize 16\% &\scriptsize 27\% \\\hline \caption{} \label{tab:longtable} \end{longtable} \begin{adjustbox}{angle=90} \begin{tabular}{|c|c|} \hline \textbf{Question} & \textbf{Answers}\\ \hline \small{Name a subject that sons discuss with their fathers rather than with their mothers.} & ~~\llap{\textbullet}~~ \small Girls \\ & ~~\llap{\textbullet}~~ \small Sports \\ & ~~\llap{\textbullet}~~ \small{Becoming a man} \\ & ~~\llap{\textbullet}~~ \small{Birds and bees} \\ \hline \small{Name a technique people use to remember things.} & ~~\llap{\textbullet}~~ \small{Thinking about it} \\ & ~~\llap{\textbullet}~~ \small{Repeating it} \\ & ~~\llap{\textbullet}~~ \small{Word association} \\ & ~~\llap{\textbullet}~~ \small{String on finger} \\ & ~~\llap{\textbullet}~~ \small{Writing it down} \\ \hline \small{Name something people do to guard against wrinkles} & ~~\llap{\textbullet}~~ \small{Botox} \\ & ~~\llap{\textbullet}~~ \small{Stay out of sun} \\ & ~~\llap{\textbullet}~~ \small{Iron clothes} \\ & ~~\llap{\textbullet}~~ \small{Sunscreen} \\ & ~~\llap{\textbullet}~~ \small{Facial cream} \\ & ~~\llap{\textbullet}~~ \small{Wear makeup} \\ \hline \small{Name something people like to do in their backyard} & ~~\llap{\textbullet}~~ \small Games \\ & ~~\llap{\textbullet}~~ \small Barbecue \\ & ~~\llap{\textbullet}~~ \small{Catch some rays} \\ & ~~\llap{\textbullet}~~ \small{Garden/Mow grass} \\ & ~~\llap{\textbullet}~~ \small Swim \\ \hline \small{Name something people do when riding in the back of a taxicab} & ~~\llap{\textbullet}~~ \small{Talk to the cabby} \\ & ~~\llap{\textbullet}~~ \small{Look out the window} \\ & ~~\llap{\textbullet}~~ \small{Talk on cell} \\ & ~~\llap{\textbullet}~~ \small{Give directions} \\ & ~~\llap{\textbullet}~~ \small Read \\ & ~~\llap{\textbullet}~~ \small{Watch meter} \\ & ~~\llap{\textbullet}~~ \small Sleep \\ \hline \small{Name a question a person who's afraid of flight might ask a flight attendant.} & ~~\llap{\textbullet}~~ \small{Will we crash?} \\ & ~~\llap{\textbullet}~~ \small{You certified?} \\ & ~~\llap{\textbullet}~~ \small{Is the pilot good?} \\ & ~~\llap{\textbullet}~~ \small{How long is the flight?} \\ & ~~\llap{\textbullet}~~ \small{How's the weather} \\ & ~~\llap{\textbullet}~~ \small{Is the plane safe?} \\ \hline \small{We asked 100 married women...If your husband asked you for a divorce Sunday night,} & ~~\llap{\textbullet}~~ \small{Clean out the bank} \\ \small{what's the first thing you'd do Monday morning?} & ~~\llap{\textbullet}~~ \small{Kick him out} \\ & ~~\llap{\textbullet}~~ \small{Leave the house} \\ & ~~\llap{\textbullet}~~ \small{Ask him why} \\ & ~~\llap{\textbullet}~~ \small{See a lawyer/File} \\ & ~~\llap{\textbullet}~~ \small{Change the locks} \\ \hline \small{When you're looking for work, name a way you might find out about the job openning} & ~~\llap{\textbullet}~~ \small{Newspaper} \\ & ~~\llap{\textbullet}~~ \small{Friend} \\ & ~~\llap{\textbullet}~~ \small{Internet} \\ & ~~\llap{\textbullet}~~ \small{Unemployment office} \\ \hline \end{tabular} \end{adjustbox} \begin{adjustbox}{angle=90} \begin{tabular}{|c|c|} \hline \small{Name something you do while driving, even though you know it's wrong} & ~~\llap{\textbullet}~~ \small{Speed} \\ & ~~\llap{\textbullet}~~ \small{Smoke cigarette} \\ & ~~\llap{\textbullet}~~ \small{Not use the seat belts} \\ & ~~\llap{\textbullet}~~ \small{Eat/Drink} \\ & ~~\llap{\textbullet}~~ \small{Don't use the signals} \\ & ~~\llap{\textbullet}~~ \small{Talk on the phone} \\ \hline \small{Name a doctor's order people never take seriously} & ~~\llap{\textbullet}~~ \small{Stop smoking} \\ & ~~\llap{\textbullet}~~ \small{Get exercise} \\ & ~~\llap{\textbullet}~~ \small{Plenty of rest} \\ & ~~\llap{\textbullet}~~ \small{Weight/Eat right} \\ & ~~\llap{\textbullet}~~ \small{Medicine/ vitamins} \\ \hline \small{Where would you look to find out how old someone is?} & ~~\llap{\textbullet}~~ \small{License/ wallet} \\ & ~~\llap{\textbullet}~~ \small{Birth certificate} \\ & ~~\llap{\textbullet}~~ \small{Their hands} \\ & ~~\llap{\textbullet}~~ \small{Their eyes} \\ & ~~\llap{\textbullet}~~ \small{Ask family members} \\ & ~~\llap{\textbullet}~~ \small{Ask them} \\ \hline \small{Name something that would be smart to know how to ask for in a foreign country} & ~~\llap{\textbullet}~~ \small{The embassy} \\ & ~~\llap{\textbullet}~~ \small{Food} \\ & ~~\llap{\textbullet}~~ \small{Directions} \\ & ~~\llap{\textbullet}~~ \small{Bathroom} \\ & ~~\llap{\textbullet}~~ \small{Help} \\ \hline \small{Name something that would be smart to know how to ask for in a foreign country} & ~~\llap{\textbullet}~~ \small{The embassy} \\ & ~~\llap{\textbullet}~~ \small{Food} \\ & ~~\llap{\textbullet}~~ \small{Directions} \\ & ~~\llap{\textbullet}~~ \small{Bathroom} \\ & ~~\llap{\textbullet}~~ \small{Help} \\ \hline \normalsize{Name something that's important to parents when house hunting? } & ~~\llap{\textbullet}~~ \small{Location} \\ & ~~\llap{\textbullet}~~ \small{Backyard} \\ & ~~\llap{\textbullet}~~ \small{Safety} \\ & ~~\llap{\textbullet}~~ \small{School} \\ & ~~\llap{\textbullet}~~ \small{Enough rooms} \\ \hline \small{Besides being fast, name something people like about fast food.} & ~~\llap{\textbullet}~~ \small{Don't cook/clean} \\ & ~~\llap{\textbullet}~~ \small{Taste/flavor} \\ & ~~\llap{\textbullet}~~ \small{Variety} \\ & ~~\llap{\textbullet}~~ \small{Its hot} \\ & ~~\llap{\textbullet}~~ \small{Price/ Cheap} \\ & ~~\llap{\textbullet}~~ \small{Easy/ Convenient} \\ \hline \small{If you were arrested and could make only one call, whom would you call?} & ~~\llap{\textbullet}~~ \small{bail bondsman} \\ & ~~\llap{\textbullet}~~ \small{Sibling} \\ & ~~\llap{\textbullet}~~ \small{friend} \\ & ~~\llap{\textbullet}~~ \small{partner/ spouse} \\ & ~~\llap{\textbullet}~~ \small{parent} \\ & ~~\llap{\textbullet}~~ \small{lawyer} \\ \hline \end{tabular} \end{adjustbox} \begin{adjustbox}{angle=90} \begin{tabular}{|c|c|} \hline \small{If your cell phone rings while you're at church, who'd better be calling} & ~~\llap{\textbullet}~~ \small{My sibling} \\ & ~~\llap{\textbullet}~~ \small{My kids} \\ & ~~\llap{\textbullet}~~ \small{The lord} \\ & ~~\llap{\textbullet}~~ \small{The doctor} \\ & ~~\llap{\textbullet}~~ \small{My spouse} \\ & ~~\llap{\textbullet}~~ \small{My boss}\\ & ~~\llap{\textbullet}~~ \small{My mother}\\ \hline \small{Tell me the most important habit a mom should teach her son} & ~~\llap{\textbullet}~~ \small{Respect for women} \\ & ~~\llap{\textbullet}~~ \small{Pick up after self} \\ & ~~\llap{\textbullet}~~ \small{Toilet etiquette} \\ & ~~\llap{\textbullet}~~ \small{Honesty} \\ & ~~\llap{\textbullet}~~ \small{Manner} \\ & ~~\llap{\textbullet}~~ \small{Cleanliness} \\ \hline \small{Name something that people do to their faces } & ~~\llap{\textbullet}~~ \small{Have facial} \\ & ~~\llap{\textbullet}~~ \small{Put on makeup} \\ & ~~\llap{\textbullet}~~ \small{Shave} \\ & ~~\llap{\textbullet}~~ \small{Get botox} \\ & ~~\llap{\textbullet}~~ \small{Wash} \\ \hline \normalsize{Name a reason a young man might join the army} & ~~\llap{\textbullet}~~ \small{Drafted} \\ & ~~\llap{\textbullet}~~ \small{Career} \\ & ~~\llap{\textbullet}~~ \small{Education} \\ & ~~\llap{\textbullet}~~ \small{Serve his country} \\ & ~~\llap{\textbullet}~~ \small{Be all he can be} \\ \hline \normalsize{Name a reason people change their names} & ~~\llap{\textbullet}~~ \small{Divorces} \\ & ~~\llap{\textbullet}~~ \small{Dislike their real name} \\ & ~~\llap{\textbullet}~~ \small{Get married} \\ & ~~\llap{\textbullet}~~ \small{Hide} \\ \hline \normalsize{ Name something you'd like to do all day without feeling any guilt} & ~~\llap{\textbullet}~~ \small{Shopping} \\ & ~~\llap{\textbullet}~~ \small{Watching TV/ Movies} \\ & ~~\llap{\textbullet}~~ \small{Sleeping/Relaxing} \\ & ~~\llap{\textbullet}~~ \small{Reading} \\ & ~~\llap{\textbullet}~~ \small{Eating} \\ \hline \normalsize{Name a way you can tell that your child is lying.} & ~~\llap{\textbullet}~~ \small{Look in the eye} \\ & ~~\llap{\textbullet}~~ \small{Stuttering} \\ & ~~\llap{\textbullet}~~ \small{Fidget} \\ & ~~\llap{\textbullet}~~ \small{Turn red} \\ & ~~\llap{\textbullet}~~ \small{Expression} \\ & ~~\llap{\textbullet}~~ \small{No eye contact} \\ \hline \normalsize{Name a reason why people sometimes need to take a day off from the work} & ~~\llap{\textbullet}~~ \small{Stress relief} \\ & ~~\llap{\textbullet}~~ \small{Tired} \\ & ~~\llap{\textbullet}~~ \small{Hangover} \\ & ~~\llap{\textbullet}~~ \small{Sick} \\ \hline \end{tabular} \end{adjustbox} \begin{adjustbox}{angle=90} \begin{tabular}{|c|c|} \hline \normalsize{Name a reason you might make your spouse get out of bed at the middle of the night} & ~~\llap{\textbullet}~~ \small{Get a glass of water} \\ & ~~\llap{\textbullet}~~ \small{Check the noise} \\ & ~~\llap{\textbullet}~~ \small{Snoring} \\ & ~~\llap{\textbullet}~~ \small{Feel sick} \\ & ~~\llap{\textbullet}~~ \small{Attend to the baby} \\ \hline \normalsize{Name something your body tells you it's time to do} & ~~\llap{\textbullet}~~ \small{Eat} \\ & ~~\llap{\textbullet}~~ \small{Sleep} \\ & ~~\llap{\textbullet}~~ \small{Wake up} \\ & ~~\llap{\textbullet}~~ \small{Go to bathroom} \\ \hline \normalsize{Name something that your boss could tell you that would come as a big shock. } & ~~\llap{\textbullet}~~ \small{Promotion/raise} \\ & ~~\llap{\textbullet}~~ \small{Buisness closing} \\ & ~~\llap{\textbullet}~~ \small{Boss is gay} \\ & ~~\llap{\textbullet}~~ \small{You do bad work} \\ & ~~\llap{\textbullet}~~ \small{You're fired} \\ \hline \normalsize{If time flies when you're having fun, name a place it crawls} & ~~\llap{\textbullet}~~ \small{Jail} \\ & ~~\llap{\textbullet}~~ \small{In the traffic} \\ & ~~\llap{\textbullet}~~ \small{DMV} \\ & ~~\llap{\textbullet}~~ \small{Work} \\ & ~~\llap{\textbullet}~~ \small{Church} \\ & ~~\llap{\textbullet}~~ \small{School} \\ \hline \normalsize{What's the hardest part of your budget to cut out?} & ~~\llap{\textbullet}~~ \small{Shopping/ clothes} \\ & ~~\llap{\textbullet}~~ \small{Entertainment} \\ & ~~\llap{\textbullet}~~ \small{Rent/Mortgage} \\ & ~~\llap{\textbullet}~~ \small{Food/Eating out} \\ \hline \normalsize{Which food do you think should be chosen as the "National Food" of America?} & ~~\llap{\textbullet}~~ \small{Fries} \\ & ~~\llap{\textbullet}~~ \small{Pizza} \\ & ~~\llap{\textbullet}~~ \small{Fried chicken} \\ & ~~\llap{\textbullet}~~ \small{Hotdog} \\ & ~~\llap{\textbullet}~~ \small{Ice cream} \\ & ~~\llap{\textbullet}~~ \small{Turkey} \\ & ~~\llap{\textbullet}~~ \small{Burger} \\ \hline \normalsize{Name something specific everyone complains about} & ~~\llap{\textbullet}~~ \small{Taxes} \\ & ~~\llap{\textbullet}~~ \small{Traffic} \\ & ~~\llap{\textbullet}~~ \small{Weather} \\ & ~~\llap{\textbullet}~~ \small{Money} \\ & ~~\llap{\textbullet}~~ \small{Work} \\ \hline \normalsize{Name something that's embarrassing to fall asleep while doing} & ~~\llap{\textbullet}~~ \small{Making love} \\ & ~~\llap{\textbullet}~~ \small{Eating} \\ & ~~\llap{\textbullet}~~ \small{Drinking} \\ & ~~\llap{\textbullet}~~ \small{Talking/phone} \\ & ~~\llap{\textbullet}~~ \small{Driving} \\ \hline \normalsize{Name something specific you might remember about one of your teachers from high school.} & ~~\llap{\textbullet}~~ \small{Nice/good teacher} \\ & ~~\llap{\textbullet}~~ \small{Good looking} \\ & ~~\llap{\textbullet}~~ \small{Way they dressed} \\ & ~~\llap{\textbullet}~~ \small{Their glasses} \\ & ~~\llap{\textbullet}~~ \small{Mean/yelled} \\ \hline \end{tabular} \end{adjustbox} \begin{adjustbox}{angle=90} \begin{tabular}{|c|c|} \hline \normalsize{Name something most people clean at least once a day.} & ~~\llap{\textbullet}~~ \small{Hands} \\ & ~~\llap{\textbullet}~~ \small{Bathroom} \\ & ~~\llap{\textbullet}~~ \small{Dishes/Sink} \\ & ~~\llap{\textbullet}~~ \small{Face} \\ & ~~\llap{\textbullet}~~ \small{Teeth} \\ & ~~\llap{\textbullet}~~ \small{Body} \\ \hline \normalsize{Name something one family member might steal from another.} & ~~\llap{\textbullet}~~ \small{Food} \\ & ~~\llap{\textbullet}~~ \small{Money} \\ & ~~\llap{\textbullet}~~ \small{Lover} \\ & ~~\llap{\textbullet}~~ \small{Clothes/Shoes} \\ & ~~\llap{\textbullet}~~ \small{Jewlery} \\ \hline \normalsize{Name something specific everyone complains aboutName a reason you might ask the manager of a hotel for another room.} & ~~\llap{\textbullet}~~ \small{Bigger bed/room} \\ & ~~\llap{\textbullet}~~ \small{Thermostat broken} \\ & ~~\llap{\textbullet}~~ \small{No TV/Cable} \\ & ~~\llap{\textbullet}~~ \small{Bed/room dirty} \\ & ~~\llap{\textbullet}~~ \small{Noisy} \\ & ~~\llap{\textbullet}~~ \small{Need nonsmoking} \\ \hline \normalsize{Name a tip people give you on how to get rich.} & ~~\llap{\textbullet}~~ \small{Work hard} \\ & ~~\llap{\textbullet}~~ \small{Save money} \\ & ~~\llap{\textbullet}~~ \small{Gamble/lottery} \\ & ~~\llap{\textbullet}~~ \small{Invest} \\ \hline \normalsize{Name a reason why someone might go a whole day without eating.} & ~~\llap{\textbullet}~~ \small{Fasting/dieting} \\ & ~~\llap{\textbullet}~~ \small{Forgot/busy} \\ & ~~\llap{\textbullet}~~ \small{Depressed/stress} \\ & ~~\llap{\textbullet}~~ \small{Sick} \\ \hline \normalsize{Name a reason you might pull you car over to the side of the road.} & ~~\llap{\textbullet}~~ \small{Flat tire} \\ & ~~\llap{\textbullet}~~ \small{Phone} \\ & ~~\llap{\textbullet}~~ \small{Police} \\ & ~~\llap{\textbullet}~~ \small{Out of gas} \\ & ~~\llap{\textbullet}~~ \small{Ambulance/Fire} \\ \hline \normalsize{Name something you hope you never find in your house. } & ~~\llap{\textbullet}~~ \small{Snake} \\ & ~~\llap{\textbullet}~~ \small{Insect} \\ & ~~\llap{\textbullet}~~ \small{Dead body} \\ & ~~\llap{\textbullet}~~ \small{Rodent} \\ & ~~\llap{\textbullet}~~ \small{Burglar} \\ & ~~\llap{\textbullet}~~ \small{Spouse cheating} \\ \hline \normalsize{The politician who wins the election is usually the person with the most what?} & ~~\llap{\textbullet}~~ \small{Vote} \\ & ~~\llap{\textbullet}~~ \small{Money} \\ & ~~\llap{\textbullet}~~ \small{Charisma} \\ \hline \normalsize{Tell me a reason why a man would want to have a son.} & ~~\llap{\textbullet}~~ \small{To play sports} \\ & ~~\llap{\textbullet}~~ \small{To be like him} \\ & ~~\llap{\textbullet}~~ \small{To carry on name} \\ & ~~\llap{\textbullet}~~ \small{To help when old} \\ & ~~\llap{\textbullet}~~ \small{To love} \\ \hline \end{tabular} \end{adjustbox} \begin{adjustbox}{angle=90} \begin{tabular}{|c|c|} \hline \normalsize{Name something that you've stayed up all night worrying about.} & ~~\llap{\textbullet}~~ \small{Kids/ family} \\ & ~~\llap{\textbullet}~~ \small{School/Test} \\ & ~~\llap{\textbullet}~~ \small{Health issues} \\ & ~~\llap{\textbullet}~~ \small{Money/ Bills} \\ & ~~\llap{\textbullet}~~ \small{Job/interview} \\ \hline \small{An engineer who lost her father in childhood in a shooting accident and blames gunmakers for her loss.} & ~~\llap{\textbullet}~~ \small{Accept, look for other jobs} \\ \small{However, the only job offer that she has received is from a gunmaker company.} & ~~\llap{\textbullet}~~ \small{Decline, ask her mother to sell the house to pay off the loan} \\ \small{If she declines the job offer (refusing to make guns that can kill other kids' dads),} & ~~\llap{\textbullet}~~ \small{Deline, look for another job, pay loan with creit card} \\ \small{her retired mother must sell her house to pay off her school loan. She should} & ~~\llap{\textbullet}~~ \small{Decline, look for anothe job, do not pay off the loan} \\ \hline \small{A US-based solar panel manufacturing company can no longer compete} & ~~\llap{\textbullet}~~ \small{Lobby and add tarrifs to imported solar panels} \\ \small{ with fully-automated companies in Asia that manufacture solar panels 50\% cheaper. } & ~~\llap{\textbullet}~~ \small{spread false info regarding child abuse labor in Asia} \\ \small{Hundreds of workers will lose their jobs in the US if the company is closed. The company should} & ~~\llap{\textbullet}~~ \small{Hire low wage international workers} \\ & ~~\llap{\textbullet}~~ \small{Be closed and workers move to better jobs} \\ \hline \small{In a smartphone, the main issue for you is } & ~~\llap{\textbullet}~~ \small{Speed} \\ & ~~\llap{\textbullet}~~ \small{Memory size}\\ & ~~\llap{\textbullet}~~ \small{Display quality and size} \\ & ~~\llap{\textbullet}~~ \small{Battery's lifespan} \\ \hline \small{Through a small increase in sales/income tax, a universal healthcare insurance plan} & ~~\llap{\textbullet}~~ \small{No Universal healthcare isn't good for high quality medical services} \\ \small{ can be created in the US. Do you like this idea?} & ~~\llap{\textbullet}~~ \small{Yes, this is a great idea!} \\ & ~~\llap{\textbullet}~~ \small{No univesal healthcare is good, but the taxes are already high} \\ & ~~\llap{\textbullet}~~ \small{No, Univesal healthcare is not good} \\ & \small{religous people shouldn't pay to fund abortion} \\ & \small{medical bills for a drunk driver} \\ \hline \small{You really like a luxury car that costs \$70,000, but you can only afford \$40,000.} & ~~\llap{\textbullet}~~ \small{you lease cars untill you can buy the luxury car} \\ & ~~\llap{\textbullet}~~ \small{You buy the best new car that you can afford for \$40,000}\\ & ~~\llap{\textbullet}~~ \small{You just buy the car you need, for less than \$40,000} \\ & ~~\llap{\textbullet}~~ \small{You buy a used model of the luxury car for \$40,000.} \\ \hline \small{When you pick a password for your phone, you pick one thar is} & ~~\llap{\textbullet}~~ \small{Easy to remember and keep it unchanged} \\ & ~~\llap{\textbullet}~~ \small{Difficult to remember and keep it unchanged}\\ & ~~\llap{\textbullet}~~ \small{Difficult to remember and change it regularly} \\ & ~~\llap{\textbullet}~~ \small{Easy to remember and you change it regularly} \\ \hline \small{You share values with} & ~~\llap{\textbullet}~~ \small{Democratic party} \\ & ~~\llap{\textbullet}~~ \small{Republican party}\\ & ~~\llap{\textbullet}~~ \small{Independent/Green party} \\ & ~~\llap{\textbullet}~~ \small{None} \\ \hline \small{If money is not an issue, you would like to buy} & ~~\llap{\textbullet}~~ \small{Samsung smartphones} \\ & ~~\llap{\textbullet}~~ \small{Apple iphone}\\ & ~~\llap{\textbullet}~~ \small{HTC smartphones} \\ & ~~\llap{\textbullet}~~ \small{LG smartphones} \\ \hline \small{If not in a hurry, which rout you choose?} & ~~\llap{\textbullet}~~ \small{with least traffic} \\ & ~~\llap{\textbullet}~~ \small{Shortest/fastest}\\ & ~~\llap{\textbullet}~~ \small{most scenic} \\ & ~~\llap{\textbullet}~~ \small{best/safest} \\ \hline \end{tabular} \end{adjustbox} \begin{adjustbox}{angle=90} \begin{tabular}{|c|c|} \hline \small{A driver is tailgating you for over an hour, what would you do?} & ~~\llap{\textbullet}~~ \small{ignore it and remain patient} \\ & ~~\llap{\textbullet}~~ \small{Speed up and leave it behind}\\ & ~~\llap{\textbullet}~~ \small{slow down and annoy the driver} \\ & ~~\llap{\textbullet}~~ \small{Pull over and let it pass} \\ \hline \small{Why did Hillary Clinton lose the presidential election? } & ~~\llap{\textbullet}~~ \small{Russian cyberattacks and fake news} \\ & ~~\llap{\textbullet}~~ \small{US electoral system}\\ & ~~\llap{\textbullet}~~ \small{Voters didn't like her} \\ & ~~\llap{\textbullet}~~ \small{FBI announcement regardin new emails on a laptop} \\ \hline \small{What should the US do if we learn that the false nuclear alarm in Hawaii was real} & ~~\llap{\textbullet}~~ \small{Do nothing as no harm was caused} \\ \small{but the North Korean missile exploded before reaching Hawaii:} &~~\llap{\textbullet}~~ \small{Detroy North Korea by a nuclear attack} \\ & ~~\llap{\textbullet}~~ \small{Assassinate North Korean leader} \\ & ~~\llap{\textbullet}~~ \small{Add more sanctions} \\ \hline \small{What are your gender/color priorities for the US commander in chief?} & ~~\llap{\textbullet}~~ \small{Color an gender do not matter} \\ & ~~\llap{\textbullet}~~ \small{Color matters but gender does not}\\ & ~~\llap{\textbullet}~~ \small{Gender matters but color does not} \\ & ~~\llap{\textbullet}~~ \small{Gender and color matter} \\ \hline \small{If money is not an issue, you will buy a driver-less car } & ~~\llap{\textbullet}~~ \small{Right away} \\ & ~~\llap{\textbullet}~~ \small{Only when 25\% of cars are driver-less.}\\ & ~~\llap{\textbullet}~~ \small{Only when 50\% of cars are driver-less} \\ & ~~\llap{\textbullet}~~ \small{Only when you have no other option} \\ \hline \small{President Trump’s travel ban is} & ~~\llap{\textbullet}~~ \small{Great and improves the safety of legal and patriotic US citizens} \\ & ~~\llap{\textbullet}~~ \small{Not good, because it is discriminatory.} \\ & ~~\llap{\textbullet}~~ \small{Not good, since not all Muslim people in the banned countries} \\ & \small{should be punished because of the Sept. 11 attack} \\ & ~~\llap{\textbullet}~~ \small{Good, but should include more countries} \\ \hline \small{ Is this a big deal if the fired missile from Yemen to Saudi Arabia} & ~~\llap{\textbullet}~~ \small{No, missiles could have been sent before the sanctions}\\ \small{was in fact made in Iran?} & ~~\llap{\textbullet}~~ \small{No, Saudi Arabia uses US built missiles} \\ & ~~\llap{\textbullet}~~ \small{Yes, it shows violation in sanctions}\\ & ~~\llap{\textbullet}~~ \small{Yes, it shows Iran helped Yeme to attack Saudi Arabia} \\ \hline \small{If a scientific theory does not agree with your religious belief} & ~~\llap{\textbullet}~~ \small{You deny the scientific theory, as science is not flawless.} \\ & ~~\llap{\textbullet}~~ \small{You do not practice any religion.}\\ & ~~\llap{\textbullet}~~ \small{You convert to a new religion that agrees with that theory.} \\ & ~~\llap{\textbullet}~~ \small{You practice your religion but live with the differences.} \\ \hline \small{A study at the University of Washington showed that by increasing the minimum wage} & ~~\llap{\textbullet}~~ \small{The study is flawed} \\ \small{,unemployment rate will increase, therefore} &~~\llap{\textbullet}~~ \small{The minimum wage should be further increased to reduce unemployement} \\ & ~~\llap{\textbullet}~~ \small{The minimum wage should be reduced} \\ & ~~\llap{\textbullet}~~ \small{There should be income tax to support unemployed people.} \\ \hline \small{Many jobs will be lost in the next few decades due to smart robots} & ~~\llap{\textbullet}~~ \small{No idea!} \\ \small{ and unemployment will thus increase. Therefore, } & ~~\llap{\textbullet}~~ \small{Capitalism will collapse, since the middle class will vanish}\\ & ~~\llap{\textbullet}~~ \small{Smart robots should be banned to save jobs.} \\ & ~~\llap{\textbullet}~~ \small{The government should provide a ``living wage'' income} \\ & \small{for all unemployed workers.} \\ \hline \end{tabular} \end{adjustbox} \begin{adjustbox}{angle=90} \begin{tabular}{|c|c|} \hline \small{As micro sized robots will be developed soon, people can be filmed anytime } & ~~\llap{\textbullet}~~ \small{People will learn to protect their privacy.}\\ \small{and anywhere without their knowledge, which will destroy their privacy} & ~~\llap{\textbullet}~~ \small{People will stop micro-sized robots.} \\ & ~~\llap{\textbullet}~~ \small{The meaning of privacy will change}\\ & ~~\llap{\textbullet}~~ \small{People will tolerate the loss of privacy.} \\ \hline \small{True democracy can be implemented using smartphone voting,} & ~~\llap{\textbullet}~~ \small{There will be no real difference. Democracy is not the answer.} \\ \small{as people can vote every day on important issues,} & ~~\llap{\textbullet}~~ \small{You prefer a combination of smartphone voting and traditional representatives}\\ \small{ and there is no need to have a costly congress or senate anymore. } & ~~\llap{\textbullet}~~ \small{You prefer traditional representatives that you can trust and votes} \\ \small{The people will finally be in charge!} & ~~\llap{\textbullet}~~ \small{This is a great idea. Why should we pay to keep a broken system? } \\ \hline \end{tabular} \end{adjustbox} \end{appendices} \section{Introduction} The demand for personalized services and adaptive technologies such as driver-less cars are projected to grow rapidly and will soon be integrated into our daily life. The communication of these technologies with human-beings needs to be proper and well-trained in order to serve, explain the facts, and understand different mindsets better. Automating the process of understanding individuals' priorities and their perception of the world can potentially be used to address specific needs of individuals and to establish efficient interactions among human and technologies. Human commonsense reasoning involves human factors and personality traits in the process of judgment and decision making, and it goes beyond the conventional logical deductive or experimental inductive reasoning. These human factors include perceptions, desires, herd mentality, mental stability, prejudice or other biases, behavior traits, and personal/ethical/religious values. Therefore, commonsense reasoning is difficult to formulate for smart technologies. As an example, the complexity of predicting stock market fluctuations is due to human factor or market psychology, and is not well understood by human-beings \cite{heike}. Similarly, the rise and fall of political figures in a democratic society is not necessarily merit-based and not even deterministic and time-invariant \cite{krueger}. In marketing, other than functionality and appearance of a product, consumers' evolving taste contributes to a brand popularity and its success or failure. Understanding the limitations and ethical consequences of commonsense reasoning is paramount and requires development of machine commonsense reasoning. In philosophy, the distinction between something reasonable and not reasonable is highly challenging to formulate, especially when a person should choose between two morally questionable acts \cite{foot1967problem}. The trolley problem, which is a well-known ethical thought experiment discussed by Philippa Foot, is an example of a highly challenging task. In the trolley problem, it is presumed justifiable for a driver of a runaway trolley that is moving towards five railroad workers to divert the trolley to a branch where only one worker is on the track. 86\% of participants in the survey believed saving five lives is more important than saving a single life \cite{thomson1985trolley}. However, a surgeon may not kill a patient or even let the patient die to distribute the patient's vital organs to five other patients that would otherwise die. The math seems identical, sacrificing one to save five, but one decision seems reasonable and justifiable to many people and the second case is not. The hypothetical trolley problem can be extended to realistic scenarios with driver-less cars \cite{goodall2016can}. A driver-less car should be equipped with commonsense reasoning for simply maximizing the gain and minimizing the loss in its decision making process. The complexity of commonsense reasoning problem can be further explained by IBM Watson, the question answering computing system that defeated Jeopardy champions in 2011. Watson had special tools for analyzing natural language and had access to 200 million pages of information including the Wikipedia encyclopedia with no Internet access. Jeopardy questions were facts not human perceptions. However, in response to the question that in which US city, the largest airport was named for a World War \RNum{2} hero and its second largest airport was named for a World War \RNum{2} battle? Watson answered: ``What is Toronto?''. The answer was a very uneducated guess as Toronto is not even located in US! The supercomputer had no human-like commonsense when answered this question. Obviously, not all different scenarios can be programmed or thought through ahead of time. If we ask the same question from a large group of children, the likelihood of hearing ``Toronto'' as the answer is projected to be extremely low, even though they probably will not know the answer. Although IBM Watson easily defeated the Jeopardy champions, the real problem arises when IBM Watson is asked about human perceptions regarding issues that are not necessarily factual or for which there exists multiple correct answers for one question. As an example, it is trivial to list the name of all animals which were mentioned in the Bible. However, it is challenging for Watson to guess the most common answer of general public in US to this question. In this paper, we hypothesize that ``commonsense reasoning'' is mostly grounded in human personality traits. To date, human personality traits have remained a virtually unexplored sources of information for understanding human beings' priorities and their perception of the world. There are numerous standardized questionnaires that have been developed for personality trait analysis \cite{roberts2006patterns,deneve1998happy,goldberg1993structure}. However, this traditional approach is based on the active participation of subjects in the conducted study. The validity of these approaches also depends on the subjects' honestly and dedication to correctly answer to the questions. Recently, a passive form of personality profiling is gaining interest in which the subjects' natural behavior is examined, rather than the choices that they intentionally make in filling questionnaires. The passive approach is projected to more accurately reflect the truth if the subjects' behavior over an extended period of time is available. The passive approach can also exploit vast information that is readily available on social media, from product reviews on Amazon to Twitter and Facebook posts \cite{correa2010interacts,hughes2012tale}. The passive form of personality profiling is projected to shed more light on human mindset by exploiting the massive information that is readily available on the Internet. \begin{figure*}[!t] \begin{center} \includegraphics[width=0.6\textwidth,keepaspectratio]{lang-per-com.pdf} \caption{Utilizing personality traits for commonsense reasoning from language.} \label{figfiveFactor} \end{center} \end{figure*} In an entirely new direction, we propose {\it PerSense}, a novel framework for personality assessment and commonsense reasoning. The overall approach to depict the described hypothesis is shown in \figref{figfiveFactor}. The relationship between the personality and language is presumed to be present in two different directions and personality trait is also hypothesized to be related with commonsense reasoning. Therefore, our innovative work in this project aims to: \begin{enumerate} \item develop computationally-simple algorithms to estimate human personality traits based on user's digital footprint on social media, \item exploit the connection between personality trait and commonsense decision making, and \item demonstrate the feasibility of predicting human beings' response to open-ended questions that have no unique factual answer. \end{enumerate} Therefore, {\it PerSense} is a framework for commonsense reasoning based on personality traits. It first employs texts from different sources such as Amazon reviews for analyzing individuals' personality. We designed two low complexity approaches for estimating personality traits based on text data in {\it PerSense}. In the absence of a large scale survey based on standard personality traits questionnaires, the personality scores generated by the IBM Watson tool are used for ground truth labeling. These scores, which are real numbers between 0 and 1, are then utilized for statistical analysis and machine learning model training focused on personality analysis. Finally, we exploit human personality traits and their distributions in a society to develop machine commonsense reasoning. To this end, we use a machine learning based approach where we train the algorithms using data collected from hundreds of subjects through Amazon Mechanical Turk. \section{Related Work} In this section, we discuss related research on personality assessment via language and text. We also discuss previous research on commonsense knowledge and reasoning. \subsection{Personality Assessment} Personality has been found to significantly correlate with a number of real-world behaviors. It correlates with music taste: popular music tends to be significantly liked by extroverts, while people with a tendency to be less open to experience tend to prefer religious music and dislike rock music [32]. Personality also impacts the formation of social relations [36]: friends tend to be, to a very similar extent, open to experience and extrovert [35]. Human personality traits, thoughts, emotions, and judgments are amongst the important topics in psychology \cite{buchheim2000relationship, gleser1959relationship}. Since the most universal way of expressing human feelings and thoughts is via language, it is reasonable to assume personality trait and language are related \cite{brown1968words,berry1997linguistic,mairesse2006words}. The lexical hypothesis, which is one of the well-established propositions in psychology, upholds this assumption \cite{goldberg1993structure}. The lexical hypothesis states that any language provides an unbiased source of different personality types. Thus, it postulates the feasibility of extracting out personality types and psychometric features by examining the linguistic representation of people \cite{pennebaker2003psychological, antonioni1998relationship}. The measurement of psychometric features, which highlight individual differences \cite{pennebaker1999linguistic}, must be reliable in the sense that the measurement method and tools provide stable results across different circumstances. The measurement must also be valid in the sense that the results remain correct for various purposes \cite{beauducel2007impact}. The Big Five model or the five factor model (FFM) \cite{digman1990personality}, is a scheme of personality traits classification \cite{de2002big, hendriks1997construction, deyoung2014openness}. This model utilizes the evaluation of individuals' personality traits based on their ranking on five bipolar factors called OCEAN (Openness, Contentiousness, Extroversion, Agreeableness, and Neuroticism) \cite{mccrae1992introduction}, which is traditionally done using standard questionnaires. The validity of the Big Five model depends on the validity of the lexical hypothesis \cite{zeidner2000intelligence, deyoung2007between}. Accordingly, the validity of the lexical hypotheses, depends on its initial claim that personality is accurately represented within the structure of the language. There are interesting applications for the Big Five model. For example, It has been shown that extroverted individuals have more Facebook friends \cite{amichai2010social}. The users with high Neuroticism scores, on the contrary, post more on Facebook wall \cite{ross2009personality}. Another application of Big Five model is in prediction of job performance \cite{judge2013hierarchical}. There are a few technical reports and papers on extracting out personality from lexicon which is called the Factor Analysis. There are different methods for factor analysis. The first and conventional methods where based on the personality traits description questionnaire \cite{drasgow1999innovations, cooper2010psychometric, shahar2004interactive}. It extracted out relevant information about personality from descriptive adjectives and different questions and phrases related to personality. The automatic recognition of personality traits was first presented in \cite{argamon2005lexical}. Recent developments in Artificial Intelligence (AI) explore new methods for automatic detection of linguistic features in text. For example, Roderick Hart developed the DICTION program in 2001, which counts the words in a text related to a particular theme \cite{hart2001redeveloping}. The DICTION was a word count program to reveal the verbal tone of political statements. The five master variables (activity, optimism, certainty, realism, and commonality) that provide a robust understanding of a text were used as a basic characterization of a text. A well-known tool for linguistic analysis is Linguistic Inquiry and Word Count (LIWC) \cite{chung2012linguistic, francis1993linguistic,pennebaker2003psychological}, which is an \textit{a priori} word-category approach. The LIWC method relies on an internal default dictionary (\textit{a priori} word-category) that defines which words should be counted in the target text files. For example, the word ``cried'' is part of five word categories: sadness, negative emotion, overall effect, verb, and past tense verb. There are many available user text datasets such as social media, on-line reviews, and essays which can be utilized in inferring personality and building models for predicting an individual's behavior in society \cite{mcauley2016addressing,lambiotte2014tracking,lazer2009life}. In \cite{pentland2010honest}, an approach was proposed for capturing physical proximity, location, and movement. Later, these data were utilized for modeling human behavior. Phone and email logs can provide some patterns about human communication. A study was provided by Onnela et al., in which the communication patterns of millions of mobile phone users were utilized for observing the coupling between the strength of interactions and the structure of the network \cite{onnela2007structure}. In a work proposed by Eagle et al., physical proximities were collected over time for inferring cognitive relationships, such as friendship \cite{eagle2009inferring}. The Internet is the main source for understanding the behaviors and connections of the people \cite{watts2007twenty,teevan2008people}. Personality has impacts on people's online interaction. In a research study, it is claimed that user's personality can be predicted using Facebook data, accurately \cite{golbeck2011predicting}. They utilized linear regression for predicting user's personalities. The input features included word counts, long words, words about time, health, etc. Mean absolute error for this prediction was 11\%. In another study, the impact of users' personality on Twitter activities was investigated \cite{quercia2011our}. In this research, the relationship between big five personality traits and different types of Twitter users was studied. Moreover, user's personality traits were predicted based on the number of followings, followers, and times the user has been listed on other's reading list. For predicting each personality trait, they utilized a 10-fold cross validation with 10 iterations using M5$\prime$ rules. The maximum root-mean-square error (RMSE) is $0.88$. In this work they utilized basic network properties in user' Twitter account. In our research, we collected data from different sources and text analysis was performed. Moreover, we utilized two different approaches, statistical and probabilistic, for predicting personality traits. In another research, they proposed that Instagram picture features can be correlated with personality \cite{ferwerda2015predicting}. They tried to predict personalities based on the way the pictures were taken and filters applied to them. Features were extracted from 22,398 pictures and mean values were calculated for each feature to create a measurement of central tendency. Later, a correlation matrix was created based on the central tendencies. Their findings suggested a relationship between users' personality traits and their posted pictures. \subsection{Commonsense Reasoning} Knowledge representation and reasoning are important problems in artificial intelligence. There are different rules and methods for knowledge representation \cite{russell2016artificial}. In order for a computer to act intelligently, it should have a wide knowledge representation of the world. Designing such a computer, requires information about the type of knowledge and the ways of obtaining it. The reasoning problem is a philosophical problem that can be solved clearly using intelligent systems. In reasoning programs, interaction with the world are through inputs and outputs that can be represented in different forms. One of these representations utilizes a set of sentences in the form of logical language. Commonsense knowledge is the most general kind of knowledge that belongs to all people \cite{liu2004conceptnet}. There exist several properties such as defeasibility and context sensitivity \cite{liu2004commonsense}, which distinguish logic reasoning from human commonsense reasoning. Therefore, the use of natural language is considered to be the central component for commonsense knowledge representation \cite{sowa2000knowledge}. In order for a system to process the natural language similar to human beings, it must find the relations and information about the words and their meanings. In a study by Liu et al. a system called ConceptNet is proposed wherein natural language is explored as a tool for commonsense representation \cite{liu2004conceptnet}. In a work performed by George A. Miller, a framework called WordNet is proposed which benefits from the relationship between words \cite{miller1995wordnet}. In another work by Singh et al. a system called Open Mind is designed that obtains commonsense knowledge from people over the web \cite{singh2002open}. A calender with commonsense called SensiCal is presented by Mueller that generates warnings for avoiding errors \cite{mueller2000calendar}. For example, SensiCal sends a message to the user not to take a friend that is a vegetarian to a steakhouse. \section{PerSense Framework Design} {\it PerSense} aims to perform commonsense reasoning based on an individual's personality. An overview of the {\it PerSense} framework for algorithm design is shown in \figref{fig:system}. Designing the {\it PerSense} framework takes three phases including 1) training data construction, 2) personality assessment, and 3) commonsense reasoning. In order to construct the training data, text data from different sources are gathered, natural language processing is applied on the data to extract important information from the text, and the personality traits associated with each text sample are scored using the IBM Watson Personality Insights engine. The text data, the information extracted using the NLP algorithms, and the scores achieved through the IBM Watson engine are then stored in a database. After gathering the labeled training data, {\it PerSense} estimates personality traits for each text sample. Two models are proposed for estimating personality scores including 1) a probabilistic approach based on Aggregated Probability Density Functions (PDF); and 2) an ML-based approach that utilizes machine learning algorithms in a supervised fashion to learn a model that classifies text data into personality classes. After performing personality assessment, {\it PerSense} performs machine commonsense reasoning based on each individual's different personality traits. {\it PerSense} uses a supervised learning based methodology for commonsense reasoning. In what follows the computational algorithms utilized in {\it PerSense} framework are explained in more detail. \begin{figure}[!t] \begin{center} \includegraphics[width=0.45\textwidth,keepaspectratio]{diagram1 \caption{An overview of the {\it PerSense} framework.} \label{fig:system} \end{center} \end{figure} \subsection{Probabilistic-Based Personality Assessment} Let us assume $N$ text samples have been processed and for the score $s$, a real number between 0 and 1 ( $0 \leq s \leq 1$), is associated with a given personality trait $T$, such as Neuroticism. We assume $g(s_1,s_2)$ is the function that shows the number of text samples, among $N$ processed text samples, for which the personality trait score is between $s_1$ and $s_2$, where $s_1 \leq s_2$ ($g(0,1)=N$). The score interval $[0,1]$ is divided equally into $n$ sub-intervals of $[s_0,s_1]$, $[s_1, s_2]$, $\cdots$, $[s_{n-1}, s_n]$, where $s_0=0$ and $s_n=1$. In a uniform distribution of samples, $g(s_i, s_{i+1})= \frac{N}{n}$, where $i$ is any positive integer number between $0$ and $n-1$. In practice, it is unlikely to have a uniform distribution of samples as the chance of observing people with very high or very low scores is less than observing people with moderate scores. In any statistical analysis, increasing the number of samples will increase the accuracy of the results. Consequently, the non-uniform distribution of samples will adversely impact the accuracy of the results. However, in a sufficiently large survey there will be a sufficient number of samples in any interval. Any collected data in the $k$-th sub-interval, where $1 \leq k \leq n$, will be divided by the number of text samples in that interval ($g(\frac{k-1}{n}, \frac{k}{n})$) to generate a normalized metric. This metric indicates the likelihood of using a specific word (in this study an adjective) by authors whose personality trait score is in the $k$-th interval for the personality trait $T$. To achieve this objective, we create a histogram for each adjective with regard to a particular personality trait over personality trait intervals $[s_0,s_1]$, $[s_1, s_2]$, $\cdots$, $[s_{n-1}, s_n]$. For example, if a word $w$ occurred $x$ times in a text sample and the personality score for that text sample for a trait $T$ is $s_y$, which is in the $k$-th interval, i.e., $\frac{k-1}{n} \leq s_y \leq \frac{k}{n}$, a count of $x$ will be added to the number of times $w$ has been observed in the text samples authored by subjects whose scores are located in the $k$-th interval. By processing a large number of text samples, i.e., $N, n \rightarrow \infty$ and normalizing the generated histogram by its integral from 0 to 1 to have an area equal to 1, the histogram will be converted to a probability density function, $f_{w,T}(s)$. The probability that an author that uses $w$ in her writing has a specific personality trait score between $\alpha$ and $\beta$ is calculated by $\int_\alpha^\beta f_{w,T}(s)ds$. It is equally important in probabilistic-based and ML-based approaches to find words that convey distinctive information regarding personality traits, i.e., their probability density function is not uniform, i.e., $f_{w,T}(s) \neq 1$, at least for one personality trait. The words with the smallest variance in their probability density functions are more selective and convey more information. By developing the database and creating the probability density functions for informative words, it becomes possible to analyze new test samples without relying on IBM Watson. Any new text sample is processed and its informative words are extracted. The related probability density functions for informative words, which have already been developed, are combined to create an aggregated probability density function (PDF) for each personality trait. The aggregated probability density functions are then used to estimate the personality trait of the author. Let us assume, $w_1, w_2, \cdots, w_m$ are $m$ informative words in a sample text, where $m$ is a positive integer and the number of distinct informative words can be less than $m$, which means some informative words can be used more than one time in a sample text. The corresponding probability density functions are $f_{w_1,T}(s), f_{w_2,T}(s), \cdots, f_{w_m,T}(s)$, respectively. The aggregated probability density function for the personality trait $T$ of the text sample, $\Phi_T(s)$, is calculated by the following equation. \begin{equation} \label{eq:2} \Phi_T(s)=\frac{\prod \limits_{i=1}^mf_{w_i,T}(s)}{\int_{x=0}^1\prod \limits_{i=1}^mf_{w_i,T}(x)dx} \end{equation} Here, we made a simplifying assumption that utilizing an informative word is a completely independent event and conveys no information regarding any other informative words in the text sample, not even regarding the same informative word if it has been used multiple times. In other words, the fact that the subject author used $w_1$ in the first sentence of the text sample, has no information about using $w_i$ in the text sample, where $i$ is an integer number between 1 and $m$. As an example, if $f_{w_1,T}(s), f_{w_2,T}(s), \cdots, f_{w_m,T}(s)=1$ and convey no information, $\Phi_T(s)$ will also be equal to 1 and will convey no information regarding the personality trait $T$. The same technique can be expanded to additional informative words (verbs, pronouns, etc.) as well as additional text features, such as the use of passive and active voice, capitalization, punctuation, spelling or grammatical errors, sentence length, and word position. \subsection{Machine Learning for Personality Assessment} Alternatively, we developed a second approach for personality assessment based on supervised learning methodologies. There are a large number of methods for classification and regression in supervised learning research. Examples include tree-based, naive-based, support vector machines, etc. The classifiers and regressors do the predictions based on the input features to the system and their specific patterns. Supervised learning methodologies are useful techniques when a straightforward mathematical model cannot be extracted or building a statistical model is expensive. These techniques infer decisions based on a set of training data. The training data are divided into two sets: \begin{enumerate} \item $X$ is a finite set of input features, \item $Y$ is a finite set of output labels associated with each input feature instance, and \item $F(X)$ is a function that maps input features to output labels, i.e., $X \overset{F(X)} \rightarrow Y$ \end{enumerate} In this work, the input features are a set of adjectives utilized across the text samples and their frequencies in each text sample. The output labels are the personality scores associated with each text sample. $F(x_{i})$ is a classification algorithm that generates an output label $y_{i}$ as the predicted score/label for $sample_{i}$. The purpose of training is to find the mapping function from the input features to the output labels; therefore, if we feed a set of input features into our decision making function, it will provide a prediction of the output label. The schematic of the machine learning method is shown in \figref{fig:ML}. \begin{figure*}[!t] \begin{center} \includegraphics[width=\textwidth,keepaspectratio]{personality} \caption{The pipeline of the personality assessment framework using supervised learning methodology.} \label{fig:ML} \end{center} \end{figure*} \subsection{Machine Learning for Commonsense Reasoning} We utilized a supervised learning based methodology for commonsense reasoning. Several classification and regression algorithms are utilized for modeling the problem. As mentioned previously, a supervised learning method derives the decisions based on the inputs that are given to the model. These inputs are represented as features in the context of machine learning modeling. For the purpose of commonsense reasoning, we designed a way of human-computer interaction wherein the input features are responses to a standard FFM personality trait questionnaire \cite{buchanan2005implementing}. This online FFM questionnaire was developed from the International Personality Item Pool (IPIP). A revised version of this was utilized for this work which was created with acceptable reliability and factor uni-vocal scales. FFM model was proved to be acceptable for use in internet-mediated research via different experiments. We perform classification for each individual commonsense question. The predefined responses to commonsense questions are output labels for that question. The schematic of the supervised learning method utilized for commonsense reasoning is shown in \figref{fig:CSR}. \begin{figure*}[!t] \begin{center} \includegraphics[height=45mm,keepaspectratio]{commonsense.pdf} \caption{The pipeline of the commonsense reasoning framework.} \label{fig:CSR} \end{center} \end{figure*} \section{Experimental Setup} This section describes the steps that are taken for evaluating {\it PerSense}. In order to prevent propagation of errors from personality assessment algorithms to commonsense reasoning techniques, we evaluated these two algorithmic modules individually. The final dataset for personality analysis using ML contains $16,934$ data points, $345$ input features, and $8$ class labels for each personality trait. The dataset for commonsense reasoning consists of $300$ data points, $50$ input features, and depending on each commonsense question there are different numbers of input features ranging from 2 to 7. In this work, for evaluating the proposed framework, two sets of experiments where designed. First experiment is designed for evaluating personality assessment. For this purpose IBM Watson's text-based personality trait estimation tool was utilized for ground truth labeling. The accuracy of the proposed method was thus limited by IBM Watson’s accuracy. However, recruiting tens of thousands of volunteers to provide text samples and take standard personality tests was not a feasible option for this preliminary work. In the second part, standard personality tests results were utilized for commonsense reasoning, and the ground truth is generated by questionnaires filled through Amazon Mechanical Turk. In what follows, the steps for data collection and experimental setup are explained in detail. We will discuss the obtained results based on these experiments in the next section. \subsection{Experiments for Personality Assessment} For evaluating the performance of the personality assessment algorithms, we construct a dataset of text samples to evaluate both approaches (i.e., PDF and ML) by utilizing existing texts from Amazon movie reviews \cite{mcauley2016addressing}, stream-of-consciousness essays \cite{humphrey1958stream}, and blog posts from sites hosted by WordPress. The mined text sample dataset contained $17,128$ data points. These text samples are given a score for each personality by the IBM Watson Personality Insights, a commercialized text-based personality assessment tool running on a big supercomputer and providing other fee-based services. In this work we utilized the IBM Watson service for assessing the personality characteristics based on a user's digital footprint and communications \cite{verma2009server}. This tool has limitations on the text inputs. Moreover, some of the adjectives are not descriptive due to having a low frequency in the samples. Therefore, the text samples that don't meet the following criteria are filtered out: \begin{enumerate} \item text samples should be in English; \item the number of words in each sample should be greater than 600; and \item each adjective frequency should be greater than 25 throughout all the samples. \end{enumerate} The mined text sample dataset contained $16,834$ data points after data filtering. The scores given by IBM Watson are real values in the range of $0$ to $1$, with $0$ being the lowest in that personality trait. These scores are used as ground-truth labeling for testing our PDF and ML approaches for text-based personality trait assessment. The collected data were stored in a local database that consists of two tables. The first table has the list of all the adjectives, their frequencies, and a vector of scores associated with the samples that they were found in. The second table has all the text samples, a vector of adjectives and their frequencies in that sample, and the scores given by IBM Watson. Input features for training models for personality assessment are frequencies associated with each adjective. The output labels are the scores given to each text sample by IBM Watson. To build the training data in {\it PerSense}, the aggregated data are passed through Natural Language Processing (NLP) tools for extracting important data and their frequencies. For this purpose, the Natural Language Toolkit (NLTK) \cite{bird2004nltk} is utilized, which uses large bodies of linguistic data, or corpus. The NLTK is written in Python and distributed under the GPL open source license. We utilized existing corpora in the NLTK which are large text bodies for aggregating a list of existing adjectives, such as Gutenberg, web and chat text, Brown, and Reuters. A total of $26,414$ adjectives were found in the corpora. Utilizing this tool, we tagged the sentences in all of the text samples and extracted the adjectives and their associated frequencies in the text samples. For the purpose of ground-truth labeling, the dataset is analyzed by IBM Watson for assigning personality scores to each text sample. The data obtained from these two sources, NLP and IBM Watson, are then stored in a database. In what follows, the dataset for each personality assessment approach and statistics of the data are explained in more detail. \subsubsection{Distribution of Scores} To obtain ground-truth labeling, the dataset was fed to the IBM Watson and scores were assigned to each text sample in the dataset. Out of different personality traits, OCEAN traits were extracted from the results. The resulted scores by IBM Watson were divided into 10 class labels in order to see the distribution of data. As shown in Table 2, Openness score for 90\% of the data was above 0.9, while the remaining 10\% of the data had a score between 0 and 0.9. Although all personality traits are equally important, the most uniform distribution of the mined samples was observed for Neuroticism. This personality trait is important in mental health care and suicide prevention. Therefore, our text-based analysis was focused on this personality trait. \begin{table} \centering \small \caption{The distribution of the data for each class label.} \begin{tabular}[ht]{|c||c|c|c|c|c|} \hline \textbf{Labels} & \textbf{O} & \textbf{C} & \textbf{E} & \textbf{A} & \textbf{N} \\\hline \newline \textbf{0-0.1} & 0.3\% & 35\% & 31\% & 60\% & 6\% \newline \\\hline \textbf{0.1-0.2} & 0.6\% & 26\% & 20\% & 17\% & 6\% \newline \\ \hline \textbf{0.2-0.3} & 0.8\% & 15\% & 15\% & 8\% & 11\% \newline \\ \hline \textbf{0.3-0.4} & 1\% & 9\% & 11\% & 4\% & 17\% \newline \\ \hline \textbf{0.4-0.5} & 1\% & 5\% & 8\% & 3\% & 18\% \newline \\ \hline \textbf{0.5-0.6} & 1\% & 4\% & 5\% & 2\% & 16\% \newline \\ \hline \textbf{0.6-0.7} & 1\% & 2\% & 4\% & 2\% & 11\% \newline \\ \hline \textbf{0.7-0.8} & 2\% & 2\% & 3\% & 1.5\% & 7\% \newline \\ \hline \textbf{0.8-0.9} & 2\% & 1\% & 2\% & 1\% & 4\% \newline \\ \hline \textbf{0.9-1} & 90\% & 1\% & 1\% & 0.4\% & 3\% \newline \\ \hline \end{tabular} \label{tbl:distribution} \end{table} \subsubsection{Dataset Preparation for PDF Analysis} While $26,414$ adjectives were obtained from the NLTK corpora, only $17,771$ were used in our text samples. At first, we divided the personality scores into 10 subsets ($n=10$). The IBM Watson scores that were below $0.1$ and higher than $0.9$ seemed dubious and were typically from short text samples. Therefore, we limit the analysis to scores between $0.1$ (10\%) and $0.9$ (90\%). The labels for each subset are shown in ~\tblref{pdfscores}. The frequency of all the adjectives were computed separately for each sub-interval. The adjectives with frequencies less than $300$ over all the text samples were counted as unreliable data as there were zeros in the sub-intervals, resulting in $\Phi(s)=0$ in the related sub-interval based on (\ref{eq:2}). The final number of adjectives used in this study was $868$. \figref{fig:adj1} shows examples of PDF vectors for two adjectives: {\it Major} and {\it Happy}. \begin{figure} \captionsetup[subfigure]{justification=centering} \centering \begin{subfigure}{0.4\textwidth} \includegraphics[width=\textwidth]{Major.pdf} \caption{} \end{subfigure} \begin{subfigure}{0.4\textwidth} \includegraphics[width=\textwidth]{Happy.pdf} \caption{} \end{subfigure} \caption{The PDF values for two adjectives and the corresponding Neuroticism score: (a) Major --- (0.4-0.5), and (b) Happy --- (0.2-0.3).} \label{fig:adj1} \end{figure} After forming probability density function vectors for each adjective, we calculated the aggregated probability density function (PDF) for each text sample. The text samples with less than 1000 and more than 6000 words were eliminated. Text samples with less than 1000 words were too short to have reliable results using IBM Watson. A few text samples larger than 6000 words, up to one million words, were mined. These samples turned out not to be a usual text sample written by a subject reviewing a product or commenting about something and thus were discarded. Furthermore, we noted that we have more samples at the center and fewer samples at the corners, so the $g$ function was not uniform. In order to calculate each text sample's PDF vector, we extract the adjectives in each text sample and multiply their vectors. Finally, the PDF values are scaled to have an integral equal to one. Then the peak of each vector shows the personality score for that text sample. An example of a PDF output for Neuroticism is shown in \figref{fig:pdfEx}. This figure shows that the Neuroticism score for this specific text sample is in the range of $0.2$ to $0.3$. \begin{figure}[!t] \begin{center} \includegraphics[width=0.5\textwidth,keepaspectratio]{HighC.pdf} \caption{Neuroticism PDF for a specific text sample.}\label{fig:pdfEx} \end{center} \end{figure} \begin{table} \centering \small \caption{The division of the personality scores and labels for each section.} \begin{tabular}[ht]{|c||c|c|c|c|c|} \hline \textbf{Personality Score Range} & \textbf{Label} \\\hline \newline 0.1-0.2 & 0.15 \newline \\ \hline 0.2-0.3 & 0.25 \newline \\ \hline 0.3-0.4 & 0.35 \newline \\ \hline 0.4-0.5 & 0.45 \newline \\ \hline 0.5-0.6 & 0.55 \newline \\ \hline 0.6-0.7 & 0.65 \newline \\ \hline 0.7-0.8 & 0.75 \newline \\ \hline 0.8-0.9 & 0.85 \newline \\ \hline \end{tabular} \label{tbl:pdfscores} \end{table} \subsubsection{Dataset Preparation for ML Analysis} The initial set of input features are the total number of adjectives that were identified through the NLTK. After tagging the adjectives throughout all the text samples, the number of adjectives came down to $3,834$. Thereafter, adjectives that had a frequency of less than 10\% of the total number of occurrences of all the adjectives throughout the data points were removed from the feature set. The number of adjectives after data filtering was $345$. Other than filtering the feature set, the data points were filtered as well. The number of data points before data filtering was $17,127$. The frequencies of adjectives in each data point were enumerated, and data points with fewer than 5.5\% of the total number of features were removed from the dataset. The final dataset contains $16,934$ data points and \textbf{$345$} input features. Each $x_{ij}$ in the feature set is the number of adjective $i$ in data point $j$. \subsubsection{Regression and Classification Models} Classification is a form of predictive modeling and it is focused on learning a mapping function from input features to output labels. The classification model is used for predicting a discrete class label output. The regression model, on the other hand, is used for predicting a continuous set of class labels. The main motivation of this analysis is to quantify the correlation between adjective usage in each text sample and the personality scores associated with that sample. The correlation of the adjectives and the personality scores is estimated using regression models. As mentioned above, the dataset contains 345 features after the process of feature extraction and feature selection. The regression models utilized in this work are Support Vector Regression (SVR) with radial basis function (rbf) kernel \cite{basak2007support}, Linear Regression \cite{kutner2004applied}, and Random Forest Regression \cite{liaw2002classification}. Moreover, we tried to predict the output labels using classifiers as well. Six popular supervised learning classifiers were utilized for modeling the personality predictor, namely Support Vector Machine (rbf, degree 2 polynomial, and linear kernels) \cite{hearst1998support}, Decision Tree \cite{safavian1991survey}, K-nearest neighbors \cite{peterson2009k}, Perceptron \cite{freund1999large}, Multi-layer Perceptron \cite{gardner1998artificial}, and Random Forest classifier \cite{pal2005random}. \subsection{Experiments for Commonsense Reasoning} In this section, the setup of the experiments for commonsense reasoning based on the users' personality traits are elaborated. For the purpose of training a prediction model, data were collected using Amazon Mechanical Turk and Facebook. A test was designed for assuring the consistency of answers to survey questions. After passing the consistency test, we obtained 300 survey response and each response was considered as a data point. In what follows the data analysis steps are explained in detail. \subsubsection{Commonsense Dataset} For building the dataset for commonsense reasoning, we designed a survey with two parts. The first section of the survey carries $50$ personality trait questions. This questionnaire contains standardized five factor personality test. The responses are in the form of a Likert scale which is commonly involved in research studies that employs questionnaires or surveys: very inaccurate (1), moderately inaccurate (2), neither inaccurate nor accurate (3), moderately accurate (4), very accurate (5) \cite{allen2007likert}. The first set of questionnaire (personality questions) are input features for training commonsense reasoning models. In this article, input features are a set of scores given to each personality question by the user. There are $5^{50}$ possible outputs for standard personality questionnaire. Questions are expected to be independent and orthogonal, resembling eigenvectors in a vector space, each targeting a unique dimension of human personality. The FFM scores, historically were designed to be concise and handy for general statements not necessarily an adequate tool in big-data era and do not convey equal information for common sense analysis. The second section of the survey contains $67$ questions, $75$\% from the game show Family Feud \cite{mcclintock1993family}, and $35$\% developed in our lab. The developed questions are based on Samsung's interest, popular political questions, and health-care problems. A model is trained for each commonsense question; therefore, the output labels are the answers to each question (e.g. Question: ``If money is not an issue, you will buy a driver-less car ...'', Answers: 1. Right away, 2. Only when 25\% of cars are driver-less 3. Only when you have no other option 4. Only when 50\% of cars are driver-less). The distribution of class labels was calculated for each question. If the class labels were not well distributed for a question, we tried to merge related labels and make the results uniformly distributed. The labels for each question were merged based on the relevance of each label to another on for a particular question. This relevance of each label to another one was determined by perception of the experimenter of those labels to be positive or negative. For instance in the question about free health-care (What is your opinion about creating united health care insurance by slightly increasing the sales/income tax?), two answers agreed and two answers disagreed with this. Therefore, the experimenter merged two negative answers and two positive answers. The label distributions of a subset of commonsense questions are shown in Table 3. This table shows examples of commonsense questions and the distribution of class labels for each question. As an example, row two in Table 3 (``President Trump's travel ban is''), shows a question with four possible choices (1. ``Great and improves the safety of legal and patriotic US citizens'', 2. ``Not good, because it is discriminatory'', 3.``Good, but should include more countries'', 4. ``Not good, since not all Muslim people in the banned countries should be punished because of the Sept. 11 attack''). The distribution of responses to this question for each choice was 25\%, 17\%, 10\%, and 48\%, for each of the four above-mentioned questions. Based on the distribution and relevance of these options, responses for choices 1 and 3 were combined and responses selecting choices 2 and 4 were combined. \begin{table*} \centering \small \caption{The distributions of the answers to some of the commonsense questions.} \begin{tabular}[ht]{|m{10 cm}||c|c|} \hline \textbf{Question} & without fusion&with fusion \\\hline {\small Name a subject that sons discuss with their fathers rather than with their mothers.} & 5\%,33\%,46\%,16\%,&54\% ,46\% \\\hline {\small President Trump's travel ban is } & 25\%,17\%,10\%,48\%,&35\% ,65\% \\\hline {\small You share values with } & 26\%,39\%,19\%,16\%,&26\% 39\%,35\% \\\hline {\small What is your opinion about creating united healthcare by insurancing the sales/income tax? } & 54\%,20\%,14\%,12\%,&54\% 46\% \\\hline \end{tabular} \label{tbl:distribution2} \end{table*} \subsubsection{Prediction Model} Eight popular supervised learning classifiers were utilized for developing a machine commonsense reasoning model through human-computer interactions: three Support Vector Machine with three different kernels (rbf, degree 2 polynomial, and linear), Decision Tree, K-nearest neighbors, Perceptron, Multi-layer Perceptron, and a Random Forest classifier. \section{Results} We conducted two sets of experiments for testing our proposed methods. The results of two personality analysis approaches utilized in this research were compared with IBM Watson personality insights. IBM Watson itself utilized the personality score that was obtained from personality survey, as ground truth labeling. This comparison is performed due to the similarity between our framework and IBM Watson personality insight service. The Watson Personality Insights service extracts information from text data in user's text messages, tweets, and posts using linguistic analysis and performs personality analysis. In what follows, we demonstrate the detailed results for each part of the data analysis. \subsection{Performance of PDF Approach} For evaluating the performance of the PDF approach, we calculated the PDF vector of each data point. Thereupon, the peak value of the vector was compared with the ground truth label. The results show that the Mean Absolute Error (MAE) and the Root Mean Square Error (RMSE) of the PDF method are 15.5\% and 19.5\%, respectively. The logarithmic ratio of the first to the second maximum was then calculated for each text sample for use as a measure of ``confidence''. The confidence scores were from 0 to 10 with 0 being the lowest confidence and 10 the highest. In some cases, the first and second peaks are comparable, while in other cases they are significantly different. An example of each is shown in \figref{fig:differentiable1} and \figref{fig:differentiable2}. The number of words in the text sample shown in \figref{fig:differentiable1} are $3,079$ and the score given by IBM Watson is $0.44$. One of the peaks given by PDF approach shows the Neuroticism value in the range of $0.4$ and $0.5$. In \figref{fig:differentiable2}, the number of words are $3,500$ and the Neuroticism score given by IBM Watson is $0.18$. The score given by the PDF approach is in the range of $0.2$ and $0.3$ which is close to IBM score. \begin{figure} \captionsetup[subfigure]{justification=centering} \centering \begin{subfigure}{0.4\textwidth} \includegraphics[width=\textwidth]{LowC.pdf} \caption{An example of a low confidence data point.} \label{fig:differentiable1} \end{subfigure} \begin{subfigure}{0.4\textwidth} \includegraphics[width=\textwidth]{HighC.pdf} \caption{An example of a high confidence data point.} \label{fig:differentiable2} \end{subfigure} \caption{Two data points with different confidence scores.} \end{figure} The MAE of the samples with confidence values more than two is 10.5\%. \figref{fig:confidence} shows the MAE based on different confidence levels. \begin{figure}[!t] \begin{center} \includegraphics[width=0.5\textwidth,keepaspectratio]{MAEPDF.pdf \end{center}\caption{The Mean Absolute Error-Confidence plot shows by increasing the confidence metric the MAE drops below 4\%.}\label{fig:confidence} \end{figure} \subsection{Performance of ML-Based Personality Assessment} Since the amount of the mined data are large, we initially evaluated the accuracy using a train-test split (67\% training, 33\% testing). After choosing the best classifier, we used a 10-fold cross validation method for better accuracy evaluation. As it is shown in \tblref{distribution}, the data are not well distributed over all the scores. Therefore, we chose the most evenly distributed personality trait (Neuroticism) for performing our experiments and training models. For training ML classifiers, we utilized real value scores and converted them to integer percentages. While for training ML regressors we utilized real values as ground truth labeling, and output of the regressors were real values. Therefore, the accuracy of a classifier was measured based on the differences of the output labels which were numbers in range of 1 to 8, with the ground-truth labels generated by IBM Watson. The accuracy of a regressor was measured based on the difference between the actual score in range of 0-1 and the associated ground-truth labe. Scikit provides the root-mean-square deviation (RMSD) or root-mean-square error (RMSE) of each trained model which are frequently used as measures of the differences between actual values and the values predicted by a model. RMSD is based on the standard deviation of the predictions from ground-truth labels. While RMSE based on the average differences of predictions with ground-truth labels. The main purpose of this study is to predict a score as close as possible to the actual personality scores. Therefore, we defined an error margin for calculating the accuracy. If a predicted score is within the range of margin (-margin,+margin) away from the actual score, then it is counted as a correct prediction. Otherwise, it is counted as a mistake. The margin of error is set to 10\% for calculating the performance. It means if the score should be 90\% and the prediction is in the range of 80\% to 100\%, this is counted as a correct prediction. Results are shown in \tblref{performance}. The setting for each classifier and regressor is explained as follows: \begin{itemize} \item \textbf{SVM-Linear:} A support vector machine with linear kernel. \item \textbf{SVM-Polynomial:} A support vector machine with polynomial degree 2 kernel. \item \textbf{SVM-rbf:} A support vector machine with Radial Basis Function kernel. This is one of the most popular kernels. For distance metric squared euclidean distance was used. \item \textbf{Decision Tree Classifier:} A supervised learning classifier that trains decision rules for classifying the data. In this work, the random state was set to zero. \item \textbf{KNN:} K-Nearest Neighbor is a supervised learning classifier. The classification is done based on the vote of its neighbors. The class label of each datapoint will be the most common class among its k nearest neighbor. In this paper, k was assigned to $5$. \item \textbf{Perceptron:} A supervised learning classifier, generally used for binary classification. \item \textbf{MLP:} Multi-layer Perceptron a artificial neural network classifier. We utilized a log-loss function as a solver. L2 regularization penalty is set to ${10}^{-5}$. The size of hidden layers was $15$. \item \textbf{SVR-rbf:} A support vector regressor with rbf kernel. Kernel coefficient was set to $0.1$ and the penalty parameter was set to ${10}^3$. \item \textbf{Linear Regression:} Attempted to model a relationship in data by fitting a linear equation to observed data. \item \textbf{RFR:} Random forest fits a number of classifying decision trees on the samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. This is a random forest regressor with the maximum depth set to two. \item \textbf{RFC:} Random forest classifier with the number of trees set to 1000. \end{itemize} The highlighted cells are the lowest error values, obtained by the multi-layer perceptron. \begin{small} \begin{table} \centering \caption{The error metrics for each classifier} \begin{tabular}[ht]{|c||c|c|} \hline \footnotesize \textbf{Classifiers and Regressors} &\scriptsize Marginal Error & \scriptsize RMSE \\\hline \newline \textbf{\scriptsize SVM-Linear} &\scriptsize 37\% &\scriptsize 27\% \newline \\\hline \textbf{\scriptsize SVM-Polynomial} &\scriptsize 50\% &\scriptsize 47\% \newline \\ \hline \textbf{\scriptsize SVM-rbf} &\scriptsize 39\% &\scriptsize 30\% \newline \\ \hline \textbf{\scriptsize Decision Tree} &\scriptsize 50\% &\scriptsize 34\% \newline \\ \hline \textbf{\scriptsize KNN} &\scriptsize 45\% &\scriptsize 40\% \newline \\ \hline \textbf{\scriptsize Perceptron} &\scriptsize 43\% &\scriptsize 29\% \newline \\ \hline \textbf{\scriptsize MLP} &\cellcolor{blue!25} \scriptsize 30\% & \cellcolor{blue!25} \scriptsize 22\% \newline \\ \hline \textbf{\scriptsize SVR-rbf} &\scriptsize 43\% &\scriptsize 26\% \newline \\ \hline \textbf{\scriptsize Linear Regression} &\scriptsize 40\% &\scriptsize 24\% \newline \\ \hline \textbf{\scriptsize RFR} &\scriptsize 46\% &\scriptsize 27\% \newline \\ \hline \textbf{\scriptsize RFC} &\scriptsize 35\% &\scriptsize 27\% \newline \\ \hline \end{tabular} \label{tbl:performance} \end{table} \end{small} \subsection{Performance of ML-Based Commonsense Reasoning} We initially calculated the correlation between each input feature and the output labels and the features with low correlations were filtered out in building the prediction models. This results in different feature sets for each commonsense question. A model was trained for each commonsense question using each training model ($8 \times 67$ models). For evaluating the performance, a 10-fold cross validation method was utilized. The non-uniform distribution of the class labels in some questions made the problem too easy and resulted in very high accuracies; therefore, these questions are not a good criterion for the evaluation of the models. On the other hand, some questions are well distributed between more than 3 class labels. Due to the low number of data points, these questions lead to significantly low accuracies. The best criterion for evaluating the classifiers and regressors are the questions with uniform distribution among few numbers of class labels. We compared the accuracies of the classifiers for some of the questions before and after the data fusion. The results are shown in \figref{fig:fusion}. For instance, in \figref{fig:fusion}b the choices of the questions were: 1) Great and improves the safety of legal and patriotic US citizens (25\%); 2) Not good, since not all Muslim people in the banned countries should be punished because their fellow citizens committed the Sep.11 attack (17\%); 3) Good, but should include more countries (10\%); and 4) Not good, because it is discriminatory (48\%). We merged options 1 with 3 and options 2 with 4, the distribution of the data became (65\% and 35\%). The average accuracy before and after the data fusion 52\% and 76\%, respectively. \begin{figure}[tbh!] \centering \begin{subfigure}[b]{0.4\textwidth} \centering \includegraphics[width=\textwidth]{health.pdf} \caption{} \end{subfigure}% \qquad \begin{subfigure}[t]{0.4\textwidth} \centering \includegraphics[width=\textwidth]{trump.pdf} \caption{} \end{subfigure} \qquad \begin{subfigure}[t]{0.4\textwidth} \centering \includegraphics[width=\textwidth]{son.pdf} \caption{} \end{subfigure} \caption{Accuracy values of models before and after data fusion.} \label{fig:fusion} \end{figure} \begin{table}[H] \centering \caption{Confusion matrix for the commonsense question: ``What is your opinion about creating united healthcare insurance by increasing the tax?''} \begin{tabular}[ht]{|c||c|c|} \hline \backslashbox{\footnotesize{Correct}}{\footnotesize{Predicted}} & \textbf{Agree} & \textbf{Disagree} \\\hline \newline \textbf{Agree} & 60 & 20 \newline \\\hline \textbf{Disagree} & 19 & 41 \newline \\\hline \end{tabular} \label{tbl:healthscore} \end{table} \begin{table}[H] \centering \caption{Confusion matrix for the commonsense question: ``What do you think about Trump's travel ban?''} \begin{tabular}[ht]{|c||c|c|} \hline \backslashbox{\footnotesize{Correct}}{\footnotesize{Predicted}} & \textbf{Agree} & \textbf{Disagree} \\\hline \newline \textbf{Agree} & 31 & 19 \newline \\\hline \textbf{Disagree} & 9 & 81 \newline \\\hline \end{tabular} \label{tbl:trump} \end{table} \begin{table}[H] \centering \caption{Confusion matrix for the commonsense question: ``Tell me the most important habit a mom should teach her son?''} \begin{tabular}[ht]{|c||c|c|} \hline \backslashbox{\footnotesize{Correct}}{\footnotesize{Predicted}} & \textbf{Respect} & \textbf{Others} \\\hline \newline \textbf{Respect} & 47 & 21 \newline \\\hline \textbf{Others} & 30 & 41 \newline \\\hline \end{tabular} \label{tbl:son} \end{table} The confusion matrix for each commonsense reasoning question is shown in \tblref{healthscore} to \tblref{son}. \section{Concluding Remarks} The methodologies proposed in this article address important problems in the area of behavioral analysis through two novel approaches based on machine learning and probability density functions. The proposed system may have many different applications, including mental health care and suicide/homicide prevention. In this work, we applied our methodologies on personality assessment and commonsense reasoning. Scores from IBM Watson Personality Insights were utilized for ground-truth labeling. However, our goal in this work was to match or surpass the performance of Watson with a system requiring far less computational resources. The proposed approaches achieved a comparable result to the ground truth labels. For the PDF approach with the confidence factor of higher than 3, the accuracy reached 97\%. The best results achieved by ML modeling was 88.2\% through the multilayer perceptron. In this article, we utilized 345 adjectives in order to train accurate models for personality analysis. 345 adjectives were outcome of our experiments based on the available text. We are planning on collecting more text data and include other words such as verbs, nouns, and pronouns in our experiments. Furthermore, by increasing the samples more adjectives can be added to the list. Although 345 input features are not ideal for training a model, in this work we targeted a low-complexity solution for running the proposed method on smartphones rather than an alternative for IBM Watson that needs a supercomputer to run. In this work, commonsense decisions were predicted based upon an individual's personality trait. For performing commonsense reasoning, we proposed an approach utilizing ML techniques. We collected data from $345$ people through Amazon Mechanical Turk and Facebook. Two sets of questions were provided. The first set contained the personality analysis questions which were utilized as input features for the commonsense reasoning problem. The second set contained the commonsense questions. Each commonsense question was modeled separately. In this context, commonsense questions had a number of reasonable and justifiable answers. Each answer was a class label for training a model. Based on the evaluations, Random Forest Classifier achieved 82.3\% accuracy in predicting the answers to some commonsense questions. We note that commonsense questions, which may target different political point-of-views, ethical priorities, marketing practices, and other personal choices, preferences, and habits, may have a number of reasonable and justifiable answers instead of a unique factual answer. In this study, we performed experiments to generate convincing evidences that the proposed low-complexity approach is in fact functional. However, more complex and comprehensive experiments are needed to assess large scale adoption of these technologies. We focused on a computationally simple method that can be easily implemented as a mobile application. Our goal in this study was not to develop an alternative approach to the IBM Watson tool, which uses a supercomputer to run. In the future, we plan to utilize a comprehensive set of word categories (e.g., verbs, nouns) throughout the text samples and use those data for design and development of our computational models. Moreover, in this study, we utilized one personality trait in our experiments. A future study will involve collecting data from various sources to incorporate all five personality traits in our experiments. There were few sources of error in designing the algorithms. The number of subjects participated in the data collection was limited so that we could not cover a large number of personality traits at a large scale. To train commonsense reasoning models, we collected data through Amazon mechanical Turk; however, we were able to provide only a nominal amount of monetary incentive to the participants. This may have potentially impacted the quality of the collected data. Moreover, the number of subjects taking the survey was limited, and the survey results may have been affected by many factors such as personal biases. In our ongoing research, we are currently designing a data collection framework, which prompts the user with questions throughout the day, asking them to express their daily activities such as their experiences, their dietary intake, and interactions. The inputs to this system are in form of spoken language. The speech is then converted to text and utilized for personality analysis. For the commonsense reasoning analysis, we plan on recruiting more participants to train highly accurate models for commonsense reasoning. \section{Discussion and Future Direction} In this work IBM Watson Personality Insight tool, which authors modeled by two low-complexity approaches, only provides 5 FFM scores instead of providing probable responses to a standard FFM questionnaire. However, there are $5^{50}$ distinct cases when a standard FFM questionnaire consisting of 50 questions and 5 possible answers per question is filled, thus the questionnaire conveys more information than only 5 FFM percentiles. Questions in a standard FFM questionnaire, are expected to be independent and orthogonal to each other meaning that each question targets a unique dimension of human personality and closely mimic Eigenvectors in an N-dimensional space. Authors built the commonsense reasoning scheme directly based on responses to the questionnaire. As stated, personalizing the algorithms and services in most efficient way has been the focus of many recent researches in human-centered applications \cite{active,ferwerda2015predicting,efficient,ma2019cyclepro}. Therefore, assessing the personality of humans would be a helpful and necessary step. This work is the first step towards integrating personality analysis and commonsense reasoning with all the limitations that research in academia has Nevertheless. However, it has achieved its objective to establish the connection between personality trait and common-sense reasoning. In this work, we have not achieved the ultimate goal to directly extract commonsense reasoning from text. To achieve this ultimate goal, one should exceed IBM Watson and need to have access to a really large number of text samples. Although, authors did not have access to the required resources; they highlighted the missing parts and will pursue these in their future direction. Although this study clearly showed that commonsense reasoning is related to personality trait, the authors do/did not have the means to fill the FFM questionnaire directly from a text sample. Authors believe FFM scores, that are easier to use, convey less information than the questionnaire and therefore, IBM Watson as well as our method cannot rigorously revive the loss of information and fill the questionnaire using FFM percentiles. This is an interesting topic that can be explored in the future and requires a large number of text samples and responses to questionnaires to facilitate predicting responses to questions based on text features. Although applications need many words to learn personalities, it does not need to happen instantaneously. The users do not need to write an essay every time. The final product can use people’s voice, text, and other modalities and collect data overtime. As more users adopt the system and add more data to the applications, the performance improves. In our ongoing work, we are collecting data from users in real-time on daily basis by prompting them with specific questions throughout the day. For example, how was your day? What did you eat? Tell me about a movie you watched, a book you read, or a conversation you had. Then this data is utilized for personality assessment and commonsense reasoning. We expect that the amount of data collected over time will be an order of magnitude greater than what we have right now. Huge amounts of data will be available to improve the performance dramatically. In this work, the questionnaire is filled by a small number of users with different personality traits, rather than a large number of people in the society. The connection between a commonsense question and a specific feature in the personality trait is established using machine learning. In general, people in the society will not need to fill a questionnaire if their personality can be estimated by other means including their digital footprint. \bibliographystyle{IEEEtran}
{'timestamp': '2020-04-21T02:26:58', 'yymm': '2004', 'arxiv_id': '2004.09275', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09275'}
arxiv
\section{Introduction}\label{sec_1} With the development of wireless communication technologies, multicast communication including multicast broadcasting has been an attractive research field. In multicast communication, a base station (BS) tries to send identical information to multiple users simultaneously. In physical layer networks, \emph{multicast beamforming} is proposed as a multicast communication technique in which the BS with multiple antennas generates a beamformer depending on channel state information (CSI)~\cite{Kari}. Although multicast beamforming is featured as a promising technology for the 5th generation wireless networks~\cite{Aran}, providing an efficient and powerful beamforming design algorithm has been a crucial issue in the literature because the multicast beamforming problem is NP-hard in general. For example,~\cite{Kari} proposes a semidefinite programming (SDP)-based algorithm for a quality-of-service (QoS) beamforming problem. However, because of the SDP relaxation, there is often a large gap between the performance of a designed beamforming vector and its theoretical upper bound. In addition, because the algorithm uses a SDP solver and samples a large number of candidates of beamforming vectors, it is sometimes inefficient in terms of a computational cost. Recently, deep learning (DL) has been regarded as a promising approach to beamforming design similar to other research fields in physical-layer wireless communications~\cite{Wang}. The main problem when we apply DL techniques to beamforming design is that it is impossible to obtain an optimal solution for supervised data in general, which is totally different from the end-to-end approach for signal detection or channel coding~\cite{Hoy}. Several studies tackled this problem from different perspectives. For example, \cite{Alk} proposes a DL framework for coordinated beamforming based on hybrid learning using training pilot sequences. The authors of~\cite{Kwon} propose a DL architecture in which users choose two beamforming methods effectively. In~\cite{Xia}, a DL framework for efficient beamforming design and improving its performance is proposed using hybrid learning based on a sub-optimal weighted minimum mean squared error algorithm. In addition,~\cite{Xia2} discusses a general ``model-driven'' approach using deep neural networks (DNNs) for beamforming design. These approaches exhibit reasonable performance with a lower computational cost compared with conventional optimization-based algorithms usually in relatively small systems. However, these algorithms are based on learning DNNs whose number of trainable parameters grows as the system size such as the number of antennas and/or users increases. This means that the scalability of training costs possibly becomes a critical problem if we consider a larger system in which beamforming design is a more difficult task. In this sense, it is important to investigate a \emph{scalable} and unsupervised DL technique applicable to beamforming design for a large communication system. \emph{Deep unfolding}~\cite{LISTA, DU} is another powerful DL technique especially for signal processing and wireless communication~\cite{Stam}. Unlike standard DNNs, deep unfolding is based on an existing iterative algorithm. By expanding the recursive structure of the algorithm, a signal-flow graph similar to a feed-forward network is obtained. Then, we can embed trainable internal parameters that control the convergence speed and possibly fixed point. In this sense, deep unfolding is a model-driven DL technique in a direct way rather than other DNN-based approaches. In the supervised learning scenario, these parameters are trained using training data that contain a pair of input and corresponding ideal output. As an advantage of deep unfolding, we can reduce the number of trainable parameters drastically, which leads to a scalable and stable training process. Deep unfolding has been applied to various problems such as sparse signal recovery~\cite{LISTA, TISTA, TISTA2}, MIMO signal detection~\cite{He, TPG,TPG2}, decoding of error-correcting codes~\cite{Com2,LDPC}, and signature design and signal detection in sparsely code division multiple access~\cite{Yama}. Results of these works suggest that deep unfolding is also expected to be an effective and scalable approach for multicast beamforming although unsupervised learning of deep unfolding has not been studied extensively. The goal of this paper is to propose a novel deep unfolding-based algorithm for multicast beamforming design, namely max-min-fair problems. As described above, the absence of optimal beamforming vectors prevents us to employ supervised training. We thus attempt \emph{unsupervised learning of a deep-unfolded algorithm}, which is a challenging task compared with previous studies based on supervised learning. As a base of the proposed algorithm, we borrow the structure of projection onto convex set (POCS) with bounded perturbation proposed by Fink {\it et al.}~\cite{Fink}. This iterative algorithm searches a candidate of a beamforming vector satisfying a convex feasibility problem with adding perturbation to the candidate, which shows remarkable performance improvement compared with a SDP-based algorithm. By applying deep unfolding, we will train the internal parameters of the algorithm in an unsupervised manner for fast and better approximation. The outline of the paper is as follows. Section~\ref{sec_2} describes a multicast beamforming problem and the POCS algorithm. In Sec.~\ref{sec_3}, we numerically study deep-unfolded POCS for a convex feasibility problem. Section~\ref{sec_4} describes the proposed deep unfolding-based beamforming design and shows numerical results compared with other baseline algorithms. Section~\ref{sec_5} is a summary of this paper. \section{Preliminaries}\label{sec_2} In this section, we first define multicast beamforming problems and then introduce POCS and POCS-BP for approximating the problems. \subsection{Multicast beamforming} In this paper, we assume a wireless communication system in which a BS with $N$ antennas sends $ x\in \mathbb{C}$ to a multicast group $\mathcal{K}=\{1,\dots,K\}$ containing $K$ users with a single receive antenna. Let $\bm{h}_k, \bm{w}\in\mathbb{C}^N$ be a channel vector for the $k$th user ($k\in\mathcal{K}$) and beamforming vector, respectively. Then, the received signal for the $k$th user is given as $y_k = \bm{w}^\lH\bm h_k x + n_k$, where $n_k\sim \mathcal{CN}(0,\sigma^2)$ represents a complex additive white Gaussian noise with zero mean and variance $\sigma^2$. In addition, we assume that the BS knows CSI perfectly. We consider the so-called max-min-fair (MMF) beamforming problem given as \begin{equation} \mbox{Maximize}_{\bm{w}\in\mathbb{C}^N }\mbox{min}_{k\in\mathcal{K}} \frac{|\bm w^\lH \bm h_k|^2}{\|\bm w\|_2^2\sigma^2}. \label{eq_mmf1} \end{equation} In this problem, one searches a complex beamforming vector to maximize the minimum SNR among $K$ users. The solution of the problem is identical to that of the following QoS problem up to scaling~\cite{Kari}: \begin{align} \mbox{Minimize}_{\bm{w}\in\mathbb{C}^N }\,& \|\bm w\|_2^2 \nonumber \\ \mbox{subject to }& |\bm{w}^\lH\bm h_k|^2\ge \gamma\, (\forall k \in\mathcal K), \label{eq_be1} \end{align} where $\gamma$ is a SNR requirement for all users. In the QoS beamforming problem, one searches a beamforming vector to maximize the energy efficiency in the system under SNR constraints~\footnote{We can extend the following discussions straightforwardly to the case in which the SNR requirement of the $k$th user is given by $\gamma_k$.}. It is computationally hard to exactly obtain optimal solutions of these problems because they are NP-hard. To solve these problems approximately, SDP relaxation is often used~\cite{Kari}. First, using an identity $\mathrm{tr}(\bm v\bm v^\lH) = \bm v^\lH\bm v$ for $\forall \bm v\in\mathbb{C}^N$, the QoS problem (\ref{eq_be1}) is recast as \begin{align} \mbox{Minimize}_{\bm{X}\in\mathbb{C}^{N\times N} }\,& \mathrm{tr}(\bm X) \nonumber \\ \mbox{subject to }& \mathrm{tr}(\bm X\bm Q_k) \ge \gamma\, (\forall k \in\mathcal K), \nonumber \\ & \bm X = \bm X^\lH,\quad \bm X\succeq \bm{0},\nonumber\\ &\mathrm{rank}(\bm X) = 1, \label{eq_be2} \end{align} where $\bm Q_k = \bm h_k\bm h_k^\lH$. Then, the relation between the solution $\bm{w}^\ast$ of (\ref{eq_be1}) and $\bm X^\ast$ of (\ref{eq_be2}) is given as $\bm{X}^\ast = \bm{w}^\ast(\bm{w}^\ast)^\lH$. Consequently, we can obtain $\bm{w}^\ast$ using $\bm{X}^\ast$ because $\bm{X}^\ast$ is a rank-1 matrix. However, the rank-1 constraint of (\ref{eq_be2}) makes the problem intractable. To approximately solve (\ref{eq_be2}) in polynomial time, we instead solve the following relaxed problem without the rank-1 constraint: \begin{align} \mbox{Minimize}_{\bm{X}\in\mathbb{C}^{N\times N} }\,& \mathrm{tr}(\bm X) \nonumber \\ \mbox{subject to }& \mathrm{tr}(\bm X\bm Q_k) \ge \gamma\, (\forall k \in\mathcal K), \nonumber \\ & \bm X = \bm X^\lH,\quad \bm X\succeq \bm{0}.\label{eq_be3} \end{align} This problem is a SDP problem which can be solved in polynomial time using the interior-point method, for example. In contrast, obtaining a beamforming vector from the solution $\bm{X}_{\mathrm{SDP}}$ of (\ref{eq_be3}) is not straightforward because $\bm{X}_{\mathrm{SDP}}$ is no longer a rank-1 matrix. In~\cite{Kari}, some randomization techniques are introduced to generate candidates of a beamforming vector from the approximate solution $\bm{X}_{\mathrm{SDP}}$. Among the candidates, the vector which satisfies all the QoS constraints and has the lowest power is chosen as an approximate solution. \subsection{Beamforming design by projections onto convex sets} Recently, Fink {\it et al.} proposed a promising approximation algorithm for solving (\ref{eq_be2}) based on POCS for a convex feasibility problem and bounded perturbation resilience~\cite{Fink}. To apply POCS to the problem, we consider a convex feasibility problem corresponding to (\ref{eq_be3}), not an optimization problem itself. First, we define the real Hilbert space $\mathcal{H}:=\bm{X}\in\mathbb{C}^{N\times N}; \bm{X}=\bm{X}^\lH\}$ of complex Hermitian matrices with the inner product \begin{equation} \langle \bm X,\bm Y\rangle := \mathrm{Re}\{\mathrm{tr}(\bm X\bm Y)\}, \end{equation} and consequent Frobenius norm \begin{equation} \|\bm X\| :=\sqrt{\langle \bm X,\bm X\rangle} = \sqrt{\mathrm{tr}(\bm X^2)}. \end{equation} Then, a convex feasibility problem finding a matrix $\bm X\in\mathcal{H}$ satisfying all the constraints of (\ref{eq_be3}) and a power constraint is defined. POCS is a sequential projection method to solve such a convex feasibility problem. It is given as \begin{equation} \bm{X}_{t+1} = T_\ast(\bm X_t) := P_{C_{+}} T_{B_P}^\lambda T_{C_K}^\lambda \dots T_{C_1}^\lambda(\bm{X}_{t}), \label{eq_pocs} \end{equation} where $P_B$ represents a projection operator onto the convex set $B$ and $T_{B}^\lambda(\bm{X})$ is an operator given by \begin{equation} T_{B}^\lambda (\bm{X}) = \bm{X} + \lambda (P_B(\bm{X})-\bm X), \end{equation} for a real scalar $\lambda$ which controls the convergence speed of POCS. In addition, $C_{+}$, $B_P$, and $C_k$ ($\forall k\in\mathcal{K}$) are convex sets. The set $C_{+}$ is a positive semidefinite cone corresponding to the constraint $\bm X\succeq \bm{0}$. $B_P$ is the half-space $\{\bm X\in\mathcal{H}; \mathrm{tr}(\bm X) \le P\}$ with a parameter $P(>0)$ representing the target power of beamforming vector. $C_k$ is the half-space for the QoS constraint of the $k$th user, i.e, $ \mathrm{tr}(\bm X\bm Q_k) \ge \gamma$. It is shown that the sequence $(\bm X_t)_{t\ge 1}$ updated by (\ref{eq_pocs}) converges to a solution of the problem if $\lambda\in(0,2)$. It is noted, however, that this POCS is practically hard to obtain a good beamforming vector because we need to search the value of $P$ corresponding to a solution of (\ref{eq_be3}). Moreover, the approximation gap due to the lack of the rank-1 constraint is still inevitable even if we tune the value of $P$ appropriately. To compensate the lack of the rank-1 constraint, the authors of~\cite{Fink} combine POCS with bounded perturbation (BP). In the algorithm, which is called POCS-BP in this paper, an ad-hoc perturbation toward a rank-1 matrix is added to the matrix $\bm X_t$. This perturbation is executed by subtracting all the principal components of $\bm X_t$ except for the largest one from $\bm X_t$. Then, the update rule of POCS-BP is given as \begin{equation} \bm{X}_{t+1} = T_\ast( \bm X_t -\tilde \beta_t \bm{\tilde X}_t ), \label{eq_pocsbp} \end{equation} where $(\tilde \beta_t)_{t\ge 1}$ is a real non-negative bounded sequence satisfying $\sum_{t=1}^\infty \tilde \beta_t <\infty $, and $\bm{\tilde X}_t $ is all the principal components of $\bm{\tilde X}_t $ except for the largest one given as \begin{equation} \bm{\tilde X}_t = \bm X_t - \lambda_{\mathrm{max}}^t \bm{u}_t\bm{u}_t^\lH , \label{eq_pocsbp2} \end{equation} with the largest eigenvalue $\lambda_{\mathrm{max}}^t$ and corresponding eigenvector $\bm{u}_t$ of $\bm{X}_t$. A beamforming vector after $T$ iterations is then obtained as the eigenvector corresponding to the largest eigenvalue of $\bm X_T$. In~\cite{Fink}, it is shown that POCS is bounded perturbation resilient, i.e, POCS-BP always converges to a solution of the convex feasibility problem. Moreover, it is numerically shown that manually tuned POCS-BP outperforms the SDP-based algorithms with randomization techniques. In addition, they also propose a simple version of POCS-BP by omitting $P_{C_+}$ and $P_{B_P}$, which is given by \begin{equation} \bm{X}_{t+1} = T_{C_K}^{\lambda} \dots T_{C_1}^\lambda( \bm X_t -\tilde \beta_t \bm{\tilde X}_t ), \label{eq_pocsbp3} \end{equation} where $\lambda$ and $\{\tilde \beta_t\}$ are parameters of the algorithm. As an advantage of (\ref{eq_pocsbp3}), it reduces the computational complexity related to eigendecomposition for $T_{C_+}^\lambda(\cdot)$ and parameter tuning of $P$, which practically do not affect to the performance of a beamforming vector. In the rest of this paper, we use (\ref{eq_pocsbp3}) as the update rule of BP-POCS. \section{Acceleration of POCS by deep unfolding}\label{sec_3} In this section, we demonstrate a deep-unfolded algorithm based on POCS because POCS itself is a useful algorithm for other wireless communication problems~\cite{po}. The aim of this section is to verify whether unsupervised learning of deep unfolding can accelerate the convergence speed of POCS. As an example, we here consider POCS given by \begin{equation} \bm{X}_{t+1} = T_{B_P}^\lambda T_{C_K}^\lambda \dots T_{C_1}^\lambda(\bm{X}_{t}), \label{eq_pocs2} \end{equation} where the projection $P_{C_+}(\cdot)$ onto a semidefinite cone constraint is omitted from (\ref{eq_pocs}) for simplicity. This POCS solves the following convex feasibility problem. \begin{equation} \mbox{Find } \bm{X} \mbox{ s.t. } \bm{X}\in \mathcal S :=\cap_{k\in\mathcal K} C_k\cap B_P. \label{eq_pocs3} \end{equation} The architecture of deep-unfolded POCS (DU-POCS) is obtained by embedding iteration-dependent trainable parameters to (\ref{eq_pocs2}). Here, we define DU-POCS as \begin{equation} \bm{X}_{t+1} = T_{B_P}^{\lambda_t} T_{C_K}^{\lambda_t} \dots T_{C_1}^{\lambda_t}(\bm{X}_{t}), \label{eq_pocs2du} \end{equation} where $\{\lambda_t\}_{t=1}^T$ is a set of trainable parameters in the algorithm. Although one can embed independent trainable parameters to each operator $T_{B}(\cdot)$, we use the same parameter $\lambda_t$ in the $t$th iteration to reduce the number of trainable parameter. As a result, DU-POCS has only $T$ trainable parameters, which is constant to the system size such as $N$ and $K$. The training process of deep-unfolded algorithms is usually executed as supervised learning, i.e., minimizing a loss function of their output and a given true solution. On the other hand, in the training process of DU-POCS, such supervised data are unavailable because an arbitrary point in the convex set is a possibly true solution. We thus train DU-POCS in an unsupervised manner. We use a loss function between a point $\bm X\in \mathcal H$ and half spaces defined by \begin{equation} L(\bm{X};\mathcal S) := \sum_{k\in\mathcal K}\mathrm{ReLU}(\gamma-\langle \bm X, \bm Q_k \rangle) + \mathrm{ReLU}(\mathrm{tr}(\bm X)-P), \label{eq_pocs3} \end{equation} where $\mathrm{ReLU}(x):=\max (x,0)$ and thus $L(\bm{X};\mathcal S)\ge 0$. This function takes zero iff $\bm{X}\in\mathcal S$ because each term represents the gap between $\bm X$ and a constraint of $\mathcal{S}$. In the numerical experiment, we set $N=5$, $K=15$, $\sigma=1.0$, $\gamma=1.0$, and $P=0.5$. The number of iterations of DU-POCS is set to $T=20$. The initial values of $\{\lambda_t\}_{t=1}^T$ are set to $1.0$. DU-POCS is implemented using PyTorch 1.4~\cite{Pytorch}. In the training process, $L(\bm{X}_T;\mathcal S)$ is minimized using the Adam optimizer~\cite{Adam} with learning rate $0.003$. As a mini-batch training, $1000$ mini batches of size 30 are fed to DU-POCS. These batches contain random channel vectors $\{\bm h_k\}_{k=1}^K$. \begin{figure}[t] \centering \includegraphics[width=0.9\hsize]{./zPOCS_dist} \caption{Average loss values of $L(\bm{X}_t;\mathcal{S})$ over 50 realizations as functions of iteration steps $t$. Circles and squares respectively represent DU-POCS and POCS ($\lambda=1.9$). They find a feasible point of a problem within 19 and 28 iterations, respectively. Dotted line represents POCS ($\lambda=1.0$), which does not converge within 5000 iterations. } \label{fig_pocs1} \end{figure} Figure~\ref{fig_pocs1} shows the average loss $L(\bm{X}_t;\mathcal S)$ of DU-POCS over 50 realizations. As a comparison, we show results of POCS (\ref{eq_pocs2}) with $\lambda=1.9$ and $1.0$. We find that POCS with $\lambda=1.0$, which corresponds to DU-POCS with initial $\lambda_t$'s, converges very slowly possibly because a projection onto a half space will break other constraints. It cannot converges to a fixed point within 5000 iterations. On the other hand, DU-POCS and POCS with $\lambda=1.9$ successfully converges to a point in $\mathcal S$ such that $L(\bm{X}_t;\mathcal S)=0$ within 30 iterations. Namely, DU-POCS converges within 19 iterations whereas POCS with $\lambda=1.9$ does within 28 iterations. This result suggests that unsupervised learning of DU-POCS successfully accelerates the convergence speed of POCS. Fig.~\ref{fig_pocs2} shows the trained parameters $\{\lambda_t\}_{t=1}^T$ of DU-POCS. We find that the parameters take different values depending on the iteration index $t$, which is usually observed in deep-unfolded algorithms. Recently, the authors theoretically investigate trained parameters of deep unfolded gradient descent and a class of fixed-point iteration algorithms. As a result, it is shown that the so-called Chebyshev steps can reproduce the trained parameters and accelerate the convergence speed~\cite{ch, ch2}. Although these analyses do not cover POCS (\ref{eq_pocs2du}) in the real Hilbert space, this result suggests that the convergence speed of POCS can also be accelerated by deep unfolding. The theoretical analysis is an interesting future task. \begin{figure}[t] \centering \includegraphics[width=0.9\hsize]{./zPOCS_dist_params} \caption{The trained parameters $\{\lambda_t\}_{t=1}^T$ in DU-POCS ($T=20$). The solid line represents $\lambda_t=1.0$ used for the initial values of trainable parameters. The dotted line represents $\lambda_t=1.9$ used in Fig.~\ref{fig_pocs1} for comparison. } \label{fig_pocs2} \end{figure} \section{Deep-unfolded POCS-BP}\label{sec_4} Now we describe the deep-unfolded POCS-BP for multicast beamforming. From (\ref{eq_pocsbp3}), the update rule of DU-POCS-BP is given by \begin{equation} \bm{X}_{t+1} = T_{C_K}^{\lambda_t} \dots T_{C_1}^{\lambda_t}( \bm X_t -\beta_t^2 \bm{\tilde X}_t ), \label{eq_dupocs} \end{equation} where $\bm{\tilde X}$ is defined as (\ref{eq_pocsbp2}). The trainable parameters of DU-POCS-BP are $\{\lambda_t,\beta_t\}_{t=1}^T$. Thus, DU-POCS-BP of $T$ iterations has $2T$ trainable parameters, which is constant to the system size, $N$ and $K$. Note that the parameter $\tilde \beta_t$ in POCS-BP is replaced to $\beta_t^2$ to keep coefficients of bounded perturbation non-negative. The pseudo-code of DU-POCS-BP is shown in Alg. 1. In the algorithm, we need to obtain the maximum eigenvalue and corresponding eigenvector of a matrix. Since Pytorch 1.4 has no function with backward pass for eigendecomposition of a complex matrix, we alternatively use the power method in Alg. 2 to estimate them. In the following simulations, we use $T_{\mathrm{PM}}=50$ and $\epsilon=10^{-8}$ as parameters of the power method. \begin{figure}[t]\label{alg} \removelatexerror \begin{algorithm}[H] \caption{DU-POCS-BP} \begin{algorithmic}[1] \INPUT Channel vectors $\{\bm h_k\}_{k\in\mathcal{K}}$, number of antennas $N$ \OUTPUT Normalized beamforming vector $\bm w_T\in\mathbb{C}^N$ \State Initialization: $\bm X =\bm O$ \For{$t= 1$ to $T$} \State{Call POWER METHOD to get $\lambda_{\mathrm{max}}$ and $\bm{u}$ of $\bm X$. } \State{$\bm X := \bm X -\beta_t^2\lambda_{\mathrm{max}} \bm{u}_t\bm{u}^\lH$ }\Comment{Bounded perturbation} \For{$k=1$ to $K$} \State{$\bm X := T_{C_{k}}^{\lambda_t}(\bm X) $} \Comment{Projection onto $C_k$} \EndFor \EndFor \State{Call POWER METHOD to get $\bm{u}$ of $\bm X$.} \State{$\bm w_T := \bm{u}$ } \end{algorithmic} \end{algorithm} \begin{algorithm}[H] \caption{POWER METHOD} \begin{algorithmic}[1] \INPUT Diagonalizable matrix $\bm A$ \OUTPUT Maximum eigenvalue $\lambda_{\mathrm{max}}$ and corresponding normalized eigenvector $\bm u$ \State Initialization: $\bm u \neq \bm 0$ \For{$t= 1$ to $T_{\mathrm{PM}}$} \State{$\bm u' := \bm u$} \State{$\bm u := \bm A\bm u/ \|\bm A\bm u\|_2$} \State{$\lambda_{\mathrm{max}} := \bm u^\lH \bm A\bm u/ \|\bm u\|_2^2$} \If {$\|\bm u-\bm u'\|_\infty<\epsilon$} \State{\textbf{break}} \EndIf \EndFor \end{algorithmic} \end{algorithm} \end{figure} Similar to the case of DU-POCS, it is difficult to obtain an optimal beamforming vector in advance. We thus train DU-POCS-BP by unsupervised learning. Namely, we try to minimize a target loss function related to the MMF problem (\ref{eq_mmf1}) given by \begin{equation} L(\bm{w}_t) := -\eta\left(\left\{\frac{|\bm w_t\bm h_k|^2}{\sigma^2\|\bm w_t\|_2^2}\right\}_{k\in\mathcal K}; \beta\right), \label{eq_dupocs_l1} \end{equation} where $\bm{w}_t$ is the eigenvector corresponding to the largest eigenvalue of $\bm{X}_t$ and $\eta(\{s_k\}_{k\in\mathcal{K}};\beta)$ is the weighted softmin function defined by \begin{equation} \eta\left(\{s_k\}_{k\in\mathcal{K}}; \beta\right):=\frac{\sum_{k\in\mathcal{K}} s_ke^{-\beta s_k}}{\sum_{k\in\mathcal{K}} e^{-\beta s_k}}, \label{eq_dupocs_l2} \end{equation} with the weight $\beta\in\mathbb R$. Note that the softmin function is used to avoid the differentiable problem of the original min function. The softmin function is identical to the min function when $\beta\rightarrow\infty$. In the following experiment, we use $\beta=3$ by tuning it as a hyperparamer (see Fig.~\ref{fig_dupocs3} for details). Other conditions of the experiments are as follows: we fix $N=30$, $\sigma=1.0$, and $\gamma=1.0$, and consider two cases in which $K=20$ and $50$. The number of iterations of DU-POCS-BP is set to $T=35$. The initial values of $\{\beta_t\}_{t=1}^T$ and $\{\lambda_t\}_{t=1}^T$ are respectively set to $0.9^{1/2}=0.948\dots$ and $1.0$. In mini-batch training, we use incremental training~\cite{TISTA} for stable training. In incremental training, randomly generated mini batches are fed to DU-POCS-BP of $T=1$ to train $\beta_1$ and $\lambda_1$. After finishing this, mini batches are fed to DU-POCS-BP of $T=2$ to train $\beta_1$, $\beta_2$, $\lambda_1$, and $\lambda_2$. In this case, the initial values of $\beta_1$ and $\lambda_1$ are set to trained values in the last mini-batch training. This procedure is repeated in an incremental manner until $T$ reaches to a given value, 35 in this experiment. In each mini-batch training, we used $1000$ mini batches of size $30$. The Adam optimizer with learning rate $0.003$ is executed to minimize the loss function (\ref{eq_dupocs_l1}). \begin{figure}[t] \centering \includegraphics[width=0.9\hsize]{./zDUPOCS_30_20_ins} \caption{SNR performance of beamforming design algorithms as a function of iteration steps $t$ when $(N,K)=(30,20)$. SNR is averaged over 50 realizations. Circles and squares respectively represent DU-POCS-BP and POCS-BP. Dotted and dashed lines respectively represent the SDP upper bound (\ref{eq_snr2}) and SNR performance of a SDP-based algorithm. } \label{fig_dupocs1} \end{figure} As a performance measure, we used the minimum SNR among $K$ users given by \begin{equation} \min_{k\in\mathcal{K}} \frac{|\bm w_t\bm h_k|^2}{\sigma^2\|\bm w_t\|_2^2}, \label{eq_snr} \end{equation} which is identical to the object function of the MMF problem (\ref{eq_mmf1}). The minimum SNR is averaged over 50 realizations of channel vectors. As a baseline, we execute the original POCS-BP following~\cite{Fink}. In POCS-BP, $\tilde \beta_t=0.9e^{-t/500}$ and $\lambda=1.9$ are used. In addition, we also execute the SDP-based beamforming design with randomization in~\cite{Kari}. In the algorithm (called randA in~\cite{Kari}), we first obtain the optimal solution $\bm X_{\mathrm{SDP}}$ of the SDP problem (\ref{eq_be3}). Then, using the eigendecomposition $\bm X_{\mathrm{SDP}}=\bm V\bm \Sigma\bm V^\lH$, we sample candidates of beamforming vectors $\bm{w}=\bm V\bm \Sigma^{1/2} \bm e$, where $\bm e\in\mathbb{C}^N$ is a random vector distributed uniformly on the unit sphere. The sampled $\bm w$ with the largest value of (\ref{eq_snr}) is chosen as the beamforming vector. In the experiments, we sample 5000 candidates. The SDP-based algorithm also provides a SDP upper bound of the MMF problem, which is given by \begin{equation} \min_{k\in\mathcal{K}} \frac{\bm h_k^\lH\bm X_{\mathrm{SDP}}\bm h_k}{\mathrm{tr}(\bm X_{\mathrm{SDP}})\sigma^2}. \label{eq_snr2} \end{equation} It is emphasized that this upper bound is not strict in general because the relaxed problem (\ref{eq_be3}) neglects the rank-1 constraint. Figure~\ref{fig_dupocs1} shows the SNR performance as a function of the iteration step $t$ when $K=20$. We find that DU-POCS-BP successfully designs a beamforming vector with smaller number of iterations than POCS-BP. Namely, DU-POCS-BP takes 31 iterations for convergence whereas POCS-BP takes 54 iterations. As for the convergent SNR, DU-POCS-BP exhibits $4.76$ dB, which is $0.22$ dB larger than POCS-BP as shown in the inset of Fig.~\ref{fig_dupocs1}. Although the gain is relatively small, DU-POCS-BP can converge faster than the original POCS-BP without knowing optimal beamforming vectors in training process. The SNR performance of these algorithms is higher than that of the SDP-based algorithm and relatively close to the SDP upper bound. \begin{figure}[t] \centering \includegraphics[width=0.9\hsize]{./zDUPOCS_30_50_ins} \caption{SNR performance of beamforming design algorithms as a function of iteration steps $t$ when $(N,K)=(30,50)$. SNR is averaged over 50 realizations. Circles and squares respectively represent DU-POCS-BP and POCS-BP. Dotted and dashed lines respectively represent the SDP upper bound (\ref{eq_snr2}) and SNR performance of a SDP-based algorithm. } \label{fig_dupocs2} \end{figure} Figure~\ref{fig_dupocs2} shows the SNR performance when $K=50$, which is more demanding setting for multicast beamforming. Similar to Fig.~\ref{fig_dupocs1}, DU-POCS-BP rapidly converges to a fixed point; DU-POCS-BP converges within 34 iterations whereas POCS-BP takes 139 iterations for convergence. The SNR gain of DU-POCS-BP is about $0.11$ dB compared with BOCS-BP and about $3.96$ dB compared with SDP. The results suggest that DU-POCS-BP is effective when the number of users becomes large. Figure~\ref{fig_dupocs3} shows SNR performance of DU-POCS-BP with different values of hyperparameter $\beta$ for $\eta(\cdot;\beta)$ in the loss function (\ref{eq_dupocs_l1}). The resulting SNR performance largely depends on the value of $\beta$ because $\beta$ decides the ratio between the minimum SNR and other SNRs among users. In particular, when $\beta=0$, the function $\eta(\cdot;\beta)$ becomes an average, which results in a poor training result. From this observation, it is crucial to check the $\beta$-dependency in advance, and use the proper value to maximize the convergent SNR performance. \begin{figure}[t] \centering \includegraphics[width=0.9\hsize]{./zDUPOCS_30_50_soft} \caption{SNR performance of DU-POCS-BP with different values of hyperparameter $\beta$ in the loss function (\ref{eq_dupocs_l1}) when $(N,K)\!=\!(30,50)$. SNR is averaged over 50 realizations. The hyperparameter $\beta=3$ is used in other experiments. } \label{fig_dupocs3} \end{figure} \section{Concluding remarks}\label{sec_5} In this paper, we propose a deep unfolded multicast beamforming design based on POCS-BP, which is trained by unsupervised learning. We first demonstrate that deep unfolding can accelerate the convergence speed of POCS without knowing an optimal solution. Then, we propose a deep unfolded multicast beamforming design called DU-POCS-BP. Because DU-POCS-BP has only $2T$ trainable parameters in $T$ iterations, its training process is stable and highly scalable with respect to the system size, $N$ and $K$. Numerical results show that DU-POCS-BP exhibits acceleration of the convergence speed and small SNR gain compared with the original POCS-BP, which suggests that DU-POCS-BP is an efficient DL-based beamforming design. It is a future task to analyze the behavior of DU-POCS and DU-POCS-BP theoretically and extend the proposed method to general multicast beamforming design such as multi-group multicast beamforming. It would also be an interesting work to demonstrate other applications of unsupervised learning of deep unfolding in wireless communication. \section*{Acknowledgement} This work was partly supported by JSPS Grant-in-Aid for Scientific Research (B) Grant Number 19H02138 (TW) and Grant-in-Aid for Early-Career Scientists Grant Number 19K14613, and the Telecommunications Advancement Foundation (ST). \vfill\pagebreak
{'timestamp': '2020-04-21T02:28:27', 'yymm': '2004', 'arxiv_id': '2004.09345', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09345'}
arxiv
\section{How to Build up Cross-lingual Ability} \label{section:align} Cross-lingual alignment of words in m-BERT representation has been observed and credited with cross-lingual transferability~\citep{Cao:20}. The transferbility come from semantically similar words are encoded into similar latent representations, regardless of languages. Considering that m-BERT was trained on masked language modeling and there are a bunch of subwords shared by languages that could be used as anchors, it is hypothesized that m-BERT exploited the co-occurrence information to align word pairs having similar contexts or usage statistics~\citep{pires2019multilingual}. However, m-BERT seems to be the only model succeeding in aligning cross-lingual word pairs simply trained on concatenated monolingual corpora with a monolingual objective. Similar methods for training cross-lingual word embeddings, called unsupervised joint training, often fail to generate high-quality alignments, especially for embeddings of non-shared words, due to a lack of explicit clues~\citep{Wang:20}. \citet{Wang:20} show that supervised post-hoc alignment effectively boosts unsupervised joint training in the case of traditional non-contextualized embeddings, but is not as beneficial in the case of m-BERT, suggesting that pretraining alone generates strong alignments even without supervision. Several key components have been studied why m-BERT generalize across languages so well~\citep{Karth:20}. In an analysis of the two-language version of BERT, it was shown that depth and the total number of network parameters affect cross-lingual ability a lot. Performance on the XNLI dataset significantly degrades when model architecture becomes shallower or more-parsimonious. Wordpiece tokenization also contributes to cross-lingual ability, compared with character-level or word-level tokenization. Surprisingly, shared vocabulary was found to be unnecessary in the same study. Pre-trained BERT successfully transfers from English to a lexical-modified version of English, although it failed when word ordering or n-gram statistics were randomly manipulated. This suggests that some structural similarity is possibly what BERT has learned from, while further definition should be developed and discovered. It's also unclear if the above findings hold for other non-contextualized embedding models, since the pre-training process and dataset could make a crucial difference in cross-lingual ability. In this section, we calibrate the external factors when pretraining the representations to give a fair discussion focusing on the architecture of the embedding models and study two key components that are dominant in building up cross-lingual ability of m-BERT. \subsection{Metrics for Cross-lingual Ability} There are two main paradigms for evaluating cross-lingual representations:~{\it word retrieval} and {\it downstream task transfer}. Here we use both word retrieval and downstream task transfer as the indicators of cross-lingual ability for both contextualized and non-contextualized embeddings. Although word retrieval is a task originally proposed to measure cross-lingual alignment at the word level, therefore naturally more suitable for non-contextualized embeddings, contextual version of word retrieval has been proposed for contextualized embeddings and consistent with downstream task transfer performance~\citep{Cao:20}. \subsubsection{Word Retrieval} Given a word and a bilingual dictionary~$D=\{(x_1,y_1),(x_2,y_2),\ldots,(x_n,y_n)\}$, listing all parallel word pairs from source and target languages, word retrieval is the task to retrieve the corresponding word in target language considering information provided by embedding vectors~$\{(u_1,v_1),(u_2,v_2),...(u_n,v_n)\}$. Specifically we consider a nearest neighbor retrieval function \begin{equation} neighbor(i)=\mathop{\arg\max}_{j}sim(u_i,v_j), \end{equation} where $u_i$ is the embedding of source word $x_i$ and we want to find its counterpart $y_i$ among all candidates~$y_1,y_2,...y_n$. And we use cosine similarity as the similarity function $sim$ . Then we have{\it~mean reciprocal rank }(MRR) as evaluation metrics. MRR is defined as \begin{equation} mean~reciprocal~rank = \frac{1}{n}\sum_{i}^{n}\frac{1}{rank(y_i)} \end{equation} where $rank(y_i)$ is a ranking function based on retrieval results. For contextualized embeddings, we simply average embeddings in all contexts and use the mean vector to represent each word, so that contextualized embeddings could also be evaluated with the task defined above. \subsubsection{Downstream Task Transfer} We consider XNLI as our downstream task to evaluate cross-lingual transfer. The XNLI dataset was constructed from the English MultiNLI dataset by keeping the original training set but human-translating development and test sets into other 14 languages~\citep{conneau:18, williams:18}. Given a pair of sentences, the task is to predict the relation of the sentence pair among three classes: entailment, neutral, or contradiction. As there are only training data in English, models should perform zero-shot cross-lingual transfer on development and test sets. \subsection{Experiments} To compare non-contextualized and contextualized embedding models, we conducted experiments with GloVe, Word2Vec and, BERT, where the number of dimensions was all set to 768. Embeddings were first pretrained from scratch and then evaluated on word retrieval and XNLI, to assess their cross-lingual ability. For pretraining data, we used Wikipedia from 15 languages~(English, French, Spanish, German, Greek, Bulgarian, Russian, Turkish, Arabic, Vietnamese, Thai, Chinese, Hindi, Swahili, and Urdu) to pre-train all word embeddings following unsupervised joint training scenario, assuring each target language in the downstream task has been well pre-trained. For word retrieval task, we evaluated cross-lingual alignment between English and each of the remaining 14 languages, using bilingual dictionaries from MUSE\footnote{https://github.com/facebookresearch/MUSE}. For XNLI zero-shot transfer task, the training set is in English, and the target languages of testing sets are the same as those used in the word retrieval task. To eliminate the effect of tokenization, we tokenized data uniformly with the vocabulary of m-BERT, especially the cased one, which is essentially wordpiece tokenization. Also, we experimented with different amounts of data: {\it 200k} and {\it 1000k} sentences per language to study the results under different data sizes. The results with {\it 200k} and {\it 1000k} sentences are shown in Sections~\ref{subsubsection:small} and~\ref{subsubsection:big}, respectively. \subsubsection{Small Pretraining Data} \label{subsubsection:small} \begin{figure}[ht!] \centering \includegraphics[width=\linewidth]{sections/figs/mrr_small.pdf} \caption{Evaluating alignment with Word Retrieval, compared between different representation models. For reference, Google BERT is the m-BERT pre-trained by Google. Except for Google Bert, other embeddings were pre-trained on the same data (200k sentences per language).} \label{fig:3_1} \vspace{-0.25cm} \end{figure} Surprisingly, when pre-trained on small pretraining data (200k sentences per language), BERT didn't show its extraordinary cross-lingual ability as shown in Figure~\ref{fig:3_1} and \ref{fig:3_2}. For example, GloVe and Word2Vec achieved stronger cross-lingual alignment than BERT in terms of MRR score on word retrieval task on every language paired with English. And although BERT achieved better accuracies on XNLI zero-shot transfer on several languages, the margins were very small, and the overall performances were not better than GloVe and Word2Vec. This finding provides a further discussion of the literature. Work by ~\citet{Karth:20} has found that depth and the total number of network parameters were two decisive architecture elements dominating the cross-lingual ability of BERT, also supported by experiments on XNLI. When the number of attention heads and the number of total parameters were fixed, decreasing model depth degenerated cross-lingual transfer performance. On the other hand, when the number of attention heads and depth were fixed, decreasing the number of network parameters degenerated performance, either. It seems that the expressiveness or capacity of models is crucial to building up cross-lingual ability. However, is it really the case that the bigger, the better? From results in this experiment, the capacity of BERT is definitely much bigger than GloVe and Word2Vec, but in the case of pretraining on the limited size of data, BERT didn't achieve superior performance as expected, suggesting that the relation of model capacity and cross-lingual ability may not be monotonic and the size of pretraining data also comes into play. \begin{figure}[ht!] \centering \includegraphics[width=\linewidth]{sections/figs/XNLI_small.pdf} \caption{Performance comparison on XNLI zero-shot cross-lingual transfer task} \label{fig:3_2} \end{figure} \vspace{-0.25cm} \subsubsection{Big Pretraining Data} \label{subsubsection:big} \begin{figure}[ht!] \centering \includegraphics[width=\linewidth]{sections/figs/mrr_big.pdf} \caption{Evaluating alignment with Word Retrieval, compared between different representation models. For reference, Google BERT is the m-BERT pre-trained by Google. Except for Google BERT, other embeddings were pre-trained on the same data (1000k sentences per language).} \label{fig:3_3} \vspace{-0.25cm} \end{figure} When pre-trained on big pretraining data (1000k sentences per language), there was a dramatic turn as shown in Figure~\ref{fig:3_3} and~\ref{fig:3_4}. BERT achieved an overwhelmingly higher MRR score than other embeddings on every XX-En language pairs, showing that it did a much better job in aligning semantically similar words from different languages. Testing results on XNLI were also consistent with word retrieval task, BERT reached higher accuracies than GloVe and Word2Vec, demonstrating that it had the better cross-lingual ability. It was noticeable that the increase in pretraining data size largely improved the cross-lingual alignment and transferability of BERT, while it was not the same case for GloVe and BERT. And the bounding performance of Google BERT, which is the pretrained parameters released by Google, shows that there is still room for improvement if given even more pretraining data. Besides the effect of amount of data, in the next subsection, we further studied other key components making BERT capable of learning a good cross-lingual representation space. \begin{figure}[ht!] \centering \includegraphics[width=\linewidth]{sections/figs/XNLI_big.pdf} \caption{Performance comparison on XNLI zero-shot cross-lingual transfer task} \label{fig:3_4} \vspace{-0.25cm} \end{figure} \subsubsection{Breaking Down Long Dependency} We noticed that the typical co-occurrence window size of non-contextualized embeddings, like GloVe and Word2Vec, are often limited to 5$\sim$30 tokens, but BERT could attend to hundreds of tokens, which means that BERT could learn from longer dependency and richer co-occurrence statistics. So we experimented with a smaller window size to find out if longer dependency is also necessary for learning cross-lingual structures. We directly sliced sentences in original pretraining data into smaller segments, limiting input length to 20 tokens for each example. And then we evaluated embeddings pretrained on these segments for cross-lingual ability\footnote{Limiting the number of tokens attended by attention heads may not work because the information from far tokens could still flow through layers and be collected at deeper layers.}. \begin{figure}[ht!] \begin{subfigure}{\linewidth} \includegraphics[clip,width=\linewidth]{sections/figs/windowsize_200.pdf}% \end{subfigure} \begin{subfigure}{\linewidth} \includegraphics[clip,width=\linewidth]{sections/figs/windowsize_1000.pdf}% \end{subfigure} \caption{The Effect of Window Size} \label{fig:3_5} \vspace{-0.25cm} \end{figure} Results are shown as figure~\ref{fig:3_5}. In the case of big pretraining data, pretraining BERT with shortened inputs drastically hurt the cross-lingual ability of BERT, indicated by lower MRR score on word retrieval task compared to BERT pre-trained on normal-lengthed data. It should be noticed that the total number of tokens in pretraining data stayed unchanged. However, in the case of small pretraining data, pretraining BERT with shortened inputs yielded to better cross-lingual alignment on several languages, suggesting that breaking down long dependency helps BERT to learn better cross-lingual alignment when only limited data is available. In Figure~\ref{fig:3_6}, it is shown that when there were no long dependencies to learn, the benefit of increasing the datasize became minor. The results on XNLI also show that breaking down long dependency was more harmful when there were more pretraining data. Considering the above observations, we hypothesized that cross-lingual alignment or cross-lingual transferability of BERT are learned not only from local co-occurrence relations but also from co-occurrence relations of global scope, with a larger amount of data and model capacity required. \begin{figure}[ht] \begin{subfigure}[b]{\linewidth} \includegraphics[clip,width=\linewidth]{sections/figs/windowsize_xnli_all.pdf} \subcaption{When limiting context window, the effect of pretraining datasize is less significant on XNLI transfer performance} \end{subfigure} \begin{subfigure}[b]{\linewidth} \includegraphics[clip,width=\linewidth]{sections/figs/windowsize_xnli_decrease_per.pdf} \subcaption{Performance drop on XNLI due to limiting context window size (original 512$\rightarrow$20) is shown in percentage. It is shown that the performance decrease of BERT pre-trained on small data is less than big data and even negative on some languages, which means there is an increase in transfer} \end{subfigure} \caption{The Effect of Window Size} \label{fig:3_6} \vspace{-0.25cm} \end{figure} \section{Conclusion} In this paper, we compare non-contextualized word embeddings with m-BERT. We find out that the cross-lingual ability of m-BERT has been learned from longer dependency (hundreds of tokens) instead of local co-occurrence information, and a massive amount of data is necessary. We also find out that we could make m-BERT align better between languages by just making a shift to its embeddings, which is demonstrated in the context of unsupervised translation and the performance improvement of cross-lingual transfer learning. Our work opens a new direction that strengthens cross-lingual ability different from previous alignment-based methods. \section{Introduction} Recently, multilingual BERT (m-BERT) \cite{devlin:19} has shown its superior ability in cross-lingual transfer on many downstream tasks, either in a way it is used as a feature extractor or finetuned end-to-end~\citep{conneau:18, wu:19, hsu-etal:19, pires:19}. It seems that m-BERT has successfully learned a set of cross-lingual representations in a shared vector space for multiple languages. However, given the way how m-BERT was pre-trained, it is unclear how it succeeded in building up cross-lingual ability without parallel resources and learning on supervised objectives explicitly. Some key components of BERT model architecture, such as {\it depth} and {\it total number of parameters}, have been found correlated with the cross-lingual ability of m-BERT~\citep{Cao:20}, but there are still some critical factors in pretraining yet to be recognized. For example, ~{\it massive amount of data} and {\it relatively long context window when training} are two key components specific to m-BERT but haven't been discussed in the literature. In Section~\ref{section:align}, we study the impacts of these components on the cross-lingual ability of m-BERT to enrich our understandings of how to build a powerful cross-lingual model. Also, there is another question we want to answer in this work. It has been widely proven that m-BERT's cross-lingual ability is related to its success in aligning cross-lingual word pairs, but does language-specific information still exist in the representation of m-BERT? In Section~\ref{section:trans}, we show that language-specific information is still encoded in m-BERT. By just adding one fixed vector to all latent representations, we can make m-BERT output sentences in another language semantically close to English input sentences. Moreover, this allows us to boost the zero-shot transferability of m-BERT without any extra efforts. The contributions of this work can be summarized as the following: \begin{itemize} \item We evaluated the cross-lingual ability of m-BERT influenced by different datasizes and window sizes. \item We compared the cross-lingual ability of m-BERT with non-contextualized word embedding trained. \item We developed an approach to extract language-specific representations in m-BERT, so we can make m-BERT decode a different language from input language. \item We improved the performance of m-BERT on a cross-lingual transfer downstream task by language-specific representations. \end{itemize} \section{Related Work} \textbf{Multilingual BERT.} BERT~\citep{devlin:19} is a Transformer-based~\citep{vaswani:17} large pre-trained language model that has been widely applied in numerous NLP tasks, showing great potentials in transfer learning. And m-BERT, which is pre-trained on Wikipedia text from 104 languages without cross-lingual objective or parallel data, serves as a good cross-lingual representation model that generalizes well across languages for a variety of downstream tasks~\cite{wu:19, hsu-etal:19, pires:19}. There are a line of works studying the key components contributing to the cross-lingual ability of m-BERT~\citep{Karth:20, tran:20, Cao:20, singh:19}, sometimes coming with inconsistent observations, showing that our understandings about it are still in the early stages.\\ \noindent\textbf{Cross-lingual Word Embedding.} The goal of cross-lingual word embedding is to learn embeddings in a shared vector space for two or more languages. A line of works assumes that monolingual word embeddings share similar structures across different languages and try to impose post-hoc alignment through a mapping~\citep{mikolov:13, Smith:17, joulin:18, Lample:18, artetxe:18, Zhou:19}. Another line of works considers joint training, which optimizes monolingual objective with or without cross-lingual constraints when training word embeddings~\citep{luong:15,gouws:15,Ammar:16,duong:16,lample:18b}. Cross-lingual word embedding methods above were initially proposed for non-contextualized embedding such as GloVe~\citep{pennington:14} and Word2Vec~\citep{mikolov:13w2v}, and later adapted to contextualized word representation~\citep{schuster:19, aldarmaki-diab:19}. Recently, token representations from m-BERT also serve a similar role as cross-lingual word embedding in many works. \section{Language Information} \label{section:trans} In this section, we first analyzed m-BERT using the mean difference between 15 languages, and then show that m-BERT can decode other languages by modifying the hidden representation. \subsection{Language Information in BERT} Although, in Section~\ref{section:align} we showed that m-BERT does extremely well on aligning cross-lingual representation, the representations of tokens from different languages are still able to be distinguished easily. For example, when masking one token from an English sentence, the probability of decoding a Chinese token in that position is very low for m-BERT model. This phenomenon is largely different from non-contextualized word representation alignment, which makes different language indistinguishable in the embedding space. We believed that m-BERT reserves some implicit language-specific information in the embedding space that can be disentangled from semantic embedding. As a result, we wanted to find out the language-specific component in the hidden representation. \input{sections/tables/examples} \subsubsection{Language-specific Representation} We assumed that we have $n$ languages denoted by $\{L_1, L_2, \ldots, L_n\}$ and their corresponding corpora. For each language, there is a language-specific representation $R^l_{L_i}$ in each layer $l$. To describe our method of finding language-specific representations and the use of language-specific representations, we defined the following notation \begin{itemize} \item \textbf{Context-Dependent Representation:} Given an input sequence $x$ and token index $i$, we denote the hidden representation in layer $l$ by $\bm{h}^l_{x,i}$. \item \textbf{Mean of Language:} Given a language $L$ and its corresponding corpora $C$ contain $n$ inputs $x_1, x_2,\ldots x_n$, we denote the language-specific representation of layer $l$ by $$R^l_{L}=\mathop{E}_{x \in C, \\ i \in I}\left[\bm{h}^l_{x,i}\right]$$ which represents the mean of all the context-dependent representation in the corpora. \item \textbf{Mean Difference Shift:} Given two languages $L_1, L_2$, we defined the mean difference shift of layer $l$ as $$D^l_{L_1\veryshortarrow L_2}=R^l_{L_2}-R^l_{L_1}$$ \end{itemize} In this paper, as the first exploration on language-specific representation, we simply took Mean of Language (MoL) as the language-specific representation and used Mean Difference Shift (MDS) to swift the representation from one language to another language. \input{sections/tables/translations} \subsection{Unsupervised Token Translation} \subsubsection{Method} We used MDS to force m-BERT to decode in target language $L_2$ different from input language $L_1$. For example, we fed an English sentence into m-BERT, extracted the hidden representation of each token at layer $l$, and then added weighted $D^l_{L_{1}\veryshortarrow L_{2}}$ to the hidden representation of each token. The modified hidden representation $\hat{\bm{h}}^l_{x_i}$can be written as $$\hat{\bm{h}}^l_{x_i} = \bm{h}^l_{x_i} + \alpha D^l_{L_{1}\veryshortarrow L_{2}}$$ where $\alpha$ is a hyperparameter. Finally, we used the modified hidden representation to forward to the remaining layers after $l+1$-th layer and predicted tokens by computing masked language model probabilities, although we did not mask any token at input sequence. Surprisingly, we can get predicted tokens in another language in this way, and most of them are the token level translation of the input English words. Interestingly, we observe that as $\alpha$ grows from 0, the model decodes more tokens to target language and never decodes the tokens which not belong to $L_1$ and $L_2$. When given a negative $\alpha$, the model always decodes the tokens belong to $L_1$. The sample outputs are reported in Table~\ref{tab:ex}. \subsubsection{Evaluation} Although we could force the model to decode in target language, the quality of translation was not acceptable. Instead of measuring the translation quality, we calculateed how many tokens can be converted from source language to target language. We used BLEU-1 and convert rate as our evaluation metrics. Convert rate (CR) is defined as following $$ \mathrm{convert \ rate} = \frac{\text{\# of } y \in V_t-V_s}{\text{\# of } y - \text{\# of } y \in V_s\cap V_t}$$ where $y$ is the output tokens of the model, $V_s, V_t$ is the token set of the source and target language. Shared tokens in both vocabularies were not taken into account therefore excluded from the numerator and denominator term. We computed the BLEU-1 score using ground truth reference translation of and the convert rate each sentence in XNLI test-set. We showed the result of the best setting (layer=11, $\alpha$=3), and the best score of each language pair and its weight and $\alpha$ in Table~\ref{tab:mt}. Although the translation results were not comparable to any unsupervised translation methods that usually apply denoising pretraining before translation~\citep{kim2018improving}, it shows strong evidence that we can manipulate the language-specific information in the representations by MDS, and force m-BERT to switch to another language. The covert rate shows that most of the tokens can be converted into another language. The BLEU-1 scores also show that many of the converted tokens are their translated words without considering the fluency of the converted sequence. \begin{figure}[ht] \centering \includegraphics[width=1.0\linewidth]{sections/figs/convert_rate_en-el.pdf} \caption{Convert rate on \textit{en $\veryshortarrow$ el} data when applying different $\alpha$ on different layers for MDS.} \label{fig:convert} \end{figure} We present an example of \textit{en $\veryshortarrow$ el} in an Figure~\ref{fig:convert} and ~\ref{fig:bleuchange} to show that how convert rate and BLEU-1 score changed with different weights $\alpha$ and different layers. We observed the influences of weight increase on convert rate were monotonic increase, there are more converted tokens as weight increasing. Although, the influences of weight increase on BLEU-1 score were mixed, it is worth mentioning that in the last few layers (10 or 11), the BLEU-1 of most languages obviously rose when $\alpha$ was set to $3.0$ (also shown in the best layer row in Table~\ref{tab:mt}). It indicates that the last few layers may be better for disentangling language-specific representations, which is consistent with the observation in the literature that the last few layers contain more language-specific information for predicting masked words~\citep{pires:19}. \input{sections/tables/common} \input{sections/tables/shift_xnli} \subsection{Cross-lingual Transfer} In previous works~\citep{pires2019multilingual, conneau2019cross}, people attempted to solve cross-lingual transfer tasks like XNLI in a purely zero-shot setting by training on English dataset and then testing on the dataset of other languages. However, as we have shown, the representation has language-specific information, so the training language and the testing languages still have mismatched representations. We tried to eliminate the difference in language-specific information using MDS. For XNLI task, we finetuned the m-BERT model on the English dataset while fixing the first six layers of it, as the transfer results of finetuning the last 6 layers are slightly better than finetuning the whole BERT model. On the testing set, we fed the tuned model with datasets from a new language and added MDS to the hidden representations of the 6-th layer of our model. And then we can get prediction by forwarding the modified representation to the remaining layers after the 6-th layer. When applying MDS, we used different shifting weights $\alpha$ for different languages considering the sensitivity may differ among languages. We found the best shifting weight $\alpha$ on XNLI development sets and reported the accuracy when applying the same weight on XNLI testing sets in Table~\ref{tab:xnli}. We got a slight improvement on the testing sets from most of the languages, except Spanish (es) and French (fr). The results show that by simply using MDS on the XNLI dataset, the language-specific information can be eliminated to some extent, and the modified representations can preserve more semantic information instead of mixed with language-specific information. As for Spanish (es) and French (fr), MDS did not bring any advantages. We speculated that the results came from the higher subword overlapping with English. Some shared subwords have the same meaning no matter in English or target language, but others don't. Because MDS used one mean vector to present language-specific representation without considering the difference among vocabularies, simply apply MDS to all vocabularies of these languages may hurt performance instead. A more delicate mechanism should be considered to apply different shifts for different vocabularies. We leave this research topic for future work. \input{sections/tables/en-el.tex}
{'timestamp': '2020-04-21T02:25:08', 'yymm': '2004', 'arxiv_id': '2004.09205', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09205'}
arxiv
\section{The NP-hardness proof of {\sc Steiner Tree}\xspace on unit disk graphs stated in Theorem~\ref{nphard}}\label{secapp:nphard} \begin{proof} We show a reduction from the {\sc Connected Vertex Cover} in planar graphs with maximum degree $4$ problem, which is known to be \textsf{NP}-hard\xspace \cite{garey1977rectilinear}. Given a planar graph $G$ with maximum degree $4$ and an integer $k$, the {\sc Connected Vertex Cover} problem asks to find if there exists a vertex cover $D$ for $G$ such that the subgraph induced by $D$ is connected and $|D|\le k$. We adopt the proof of Abu-Affash \cite{abu2015euclidean}, where it was shown that the $k$-{\sc Bottleneck Full Steiner Tree} problem is \textsf{NP}-hard\xspace. We make this reduction compatible for unit disk graphs. Given a planar graph $G$ with maximum degree $4$ and an integer $k$, we construct an unit disk graph $G_{\mathcal{C}}$ where $V(G_{\mathcal{C}})=\mathcal{C}$ in polynomial time, where $V(G_{\mathcal{C}})$ is divided into two sets of unit disks $R$ and $S$, denoted by Steiner and terminals, respectively. Let $V(G)=\{v_1,v_2,\ldots,v_n\}$ and let $E(G)=\{e_1,e_2,\ldots,e_m\}$. Then, we compute an integer $k'$ such that $G$ has a connected vertex cover $D$ of size $k$ if and only if there exists a {\sc Steiner Tree}\xspace with at most $k'$ Steiner vertices of $G_{\mathcal{C}}$. As as an intermediate step we build a rectangular grid graph $G'$. First, we embed $G$ on a rectangular grid, with distance at least $8$ between adjacent vertices. Each vertex $v_i\in V(G)$ corresponds to a grid vertex, and each edge $e=v_iv_j\in E(G)$ corresponds to a rectilinear path comprised of some horizontal and vertical grid segments with endpoints corresponding to $v_i$ and $v_j$. Let $V(G')=\{v'_1,\ldots,v'_n\}$ be the grid points corresponding to the vertices of $V(G)$, and let $E(G')=\{p_{e_1},\ldots,p_{e_m}\}$ be the set of paths corresponding to the edges of $E(G)$ Moreover, these paths are pairwise disjoint; see Figure~\ref{np1}(b). This embedding can be done in $O(n)$ time and the size of the grid is at most $n-2$ by $n-2$; see \cite{schnyder1990embedding}. Next, we construct an unit disk graph $G_{\mathcal{C}}$ from $G'$. First, we replace each grid vertex $v'_i\in V(G')$ by an unit disk. Let $C=\{c_1,\ldots,c_n\}$ be the set of unit disks centered at the grid points corresponding to the vertices of $V(G')$. For the sake of explanation we call these disks grid point disks. At this point, the unit disk graph is not connected due to the edge length which we have taken between any two adjacent vertices in the grid graph. In fact this length ensures that there are no undesirable paths other than the ones in $G$. Next, we place two sets of disks on each path $p_{e_i}\in E(G')$. Let $|p_{e_i}|$ be the total length of the grid segments of $p_{e_i}$. We place two Steiner disks on $p_{e_i}$, such that each one of them is adjacent to a grid point disk corresponding to $p_{e_i}$ and the distance between their centers is exactly $2$. Next, we place $|p_{e_i}|-6/2$ many terminals disks on $p_{e_i}$ such that the distance between any two adjacent centers is exactly $2$. See Figure~\ref{np1}(c) for detailed explanation. Let $s(e_i)$ be the set of Steiner disks and $t(e_i)$ be the set of terminal disks placed to $p_{e_i}$. The terminal set $R=\underset{e_i\in E(G')}{\bigcup} t(e_i)$; the Steiner set $S=C\cup \underset{e_i\in E(G')}{\bigcup} s(e_i)$. $V(G_{\mathcal{C}})=R\cup S$ and $G_{\mathcal{C}}$ is the intersection graph induced by $V(G_{\mathcal{C}})$. Finally, we set $k'=m+2k-1$. Observe that, for any path $p_{e_i}$, the terminal set $t(e_i)$ itself form a Steiner tree without any Steiner disks. However, in order to make that tree connected we need at least one of Steiner disks from $s(e_i)$. This completes the construction. \begin{figure}[h] \centering \includegraphics{np-all} \caption{(a) A planar graph $G$ of maximum degree $4$, (b) the intermediate rectilinear embedding $G'$ of $G$, (c) the unit disk graph $G_{\mathcal{C}}$; the black disks are corresponding to the grid vertices of $G'$, the blue disks are Steiner disks and the red disks are the terminal disks.} \label{np1} \end{figure} In the forward direction, suppose $G$ has a connected vertex cover $D$ of size at most $k$. We construct a Steiner tree of $R$ in the following manner. For each edge $e_i$, we simply take the terminal path induced by $t(e_i)$. Now, let $T_S$ be any spanning tree of the subgraph of $G$ induced by $D$, containing $|D|-1$ edges. The existence of such a spanning tree is ensured since $D$ is a connected vertex cover of $G$. For each edge $e=v_iv_j\in T_S$ we connect the corresponding disks $c_i,c_j$ by two Steiner red disks adjacent to them. Then, for each edge $e=v_iv_j\in G\setminus T_S$ we select one endpoint that is in $D$ (say $v_i$) and connect $c_i$ to the tree by its adjacent disk. The constructed tree is a Steiner tree of $R$ consisting $|D|+2(|D|-1)+(m-(|D|-1))$ which is $m+2k-1$. Conversely, let there exists a Steiner tree $T$ of $R$ with at most $k'$ Steiner disks. Let $D\subseteq C$ be the set of vertices that appear in $T$, and let $T'$ be the subtree of $T$ spanning over $D$. For each subset $t(e_i)\subseteq R$, let $T_{e_i}$ be the subtree of $T_{e_i}$ spanning the vertices in $t(e_i)$. By the above construction, $T_{e_i}$ does not require any Steiner disk. Moreover, it is easy to see that in any valid solution $T_{e_i}$ must be connected to at least one endpoint of $D$. This implies that the set of vertices in $G$ corresponding to the vertices in $D$ is a connected vertex cover of $G$. Moreover a tree $T_{e_i}$ which also a subtree of $T$ is connected to $D$ via two Steiner disks of $s(e_i)$. Therefore, $T_S$ contains $|D|+2(|D|-1)+(m-(|D|-1))$ many Steiner disks. We started with the tree $T$ with at most $k'=m+2k-1$ many Steiner disks. This completes the proof. \end{proof} } \old{ \section{Missing Proofs of Section~\ref{sec:subexp}}\label{secapp:subexp} \begin{proof}[Proof of Observation~\ref{obs:cell-cell-edge}] We claim that in the $k$-Steiner tree where the set $\{uv\in E(T) \vert f(u) \neq f(v)\}$ is minimised, there can be at most one neighbour of $\mathcal{C}$ in each cell $\mathcal{C}'\neq \mathcal{C}$. Suppose that $\mathcal{C}'$ is a cell that contains at least two neighbours of $\mathcal{C}$. Let two such neighbours be $u',v'$. Note that $u'v'$ is an edge in $E(G)$. Let $u,v$ (may be the same) be the neighbours of $u,v$, respectively in $\mathcal{C}$. Note that $uv$ is an edge in $E(G)$. Thus adding the edge $u'v'$ and removing the edge $uu'$ results in a connected graph containing all the terminals. The spanning tree of this connected graph has strictly less number of edges with endpoints in different cells, which is a contradiction to the choice of $T$. By the definition of clique-grid graphs, $\vert i-i'\vert , \vert j-j'\vert \leq 2$. Thus, when we fix a cell $\mathcal{C}$ there are at most $$24$ \xspace$ cells that can have neighbours of vertices in $\mathcal{C}$. Putting everything together, for the $k$-Steiner tree $T$ where the set $\{uv\in E(T) \vert f(u) \neq f(v)\}$ is minimised, $\vert \{v \vert f(v) \neq (i,j), \exists u$ such that $f(u) = (i,j), uv \in E(G) \} \vert \leq $24$ \xspace$. \end{proof} } \old{ \begin{proof}[Proof of Observation~\ref{obs:cell-bd}] For the sake of contradiction, let $\mathcal{C}=(i,j)$ be a cell such that $\vert f^{-1}(i,j) \cap V(T) \vert \geq $24$ \xspace +1$. Then by Observation~\ref{obs:cell-cell-edge}, there is at least one Steiner vertex $v \in f^{-1}(i,j) \cap V(T)$ such that it does not have any neighbours in $T \setminus f^{-1}(i,j)$. Consider the subgraph $T \setminus \{v\}$. Since the vertices of $f^{-1}(i,j)$ induce a clique, $T \setminus \{v\}$ is still a connected subgraph that contains all the terminals and strictly less number of Steiner vertices. Thus, a spanning tree of this connected subgraph contradicts the choice of $T$. \end{proof} } \old{ \begin{proof}[Proof of Claim~\ref{clm:NCPD-graph}] Suppose we are able to show that for each $i \in \{1,\ldots, n/\sqrt{t+k}\}$ $G_i$ has a $$6$ \xspace \sqrt{t+k}$-CPD. This results in a $$6$ \xspace \sqrt{t+k}$-CPD for $G \setminus (S \cup Y) = G_1\uplus \ldots\uplus G_{n/\sqrt{t+k}}$. Finally, note that $\vert Y \vert \leq \sqrt{t+k}$ and therefore the vertices of $Y$ can belong to at most $\sqrt{t+k}$ cells. We add $Y$ to all the bags in the $$6$ \xspace\sqrt{t+k}$-CPD for $G \setminus (S \cup Y)$ to obtain a $$7$ \xspace \sqrt{t+k}$-CPD for $G \setminus S$. We convert the $$7$ \xspace\sqrt{t+k}$-CPD of $G \setminus S$ into a NCPD using the known algorithm of~\cite{Bodlaender96alinear}. Note that this results in a $$7$ \xspace \sqrt{t+k}$-NCPD. What is left to show is that for each $G_i$ there is a $$6$ \xspace \sqrt{t+k}$-CPD. First, for each $G_i$, we give a path decomposition with the following sequence of bags: $\{X_1,X_2,\ldots, X_{n-2}\}$. This is done by defining each $X_i = f^{-1}(i,*) \cup f^{-1}(i+1,*) \cup f^{-1}(i+2,*)$. It is easy to check that this is a path decomposition of $G_i$. Note that since $G_i$ has at most $2\sqrt{t+k}$ columns, the number of cells contained in each $X_j, j \in [n-1]$ is at most $$6$ \xspace \sqrt{t+k}$. \end{proof} } \old{ \begin{proof}[Proof of Lemma~\ref{lem:subexp-CGG}] As a first step of the algorithm, by Lemma~\ref{lem:compute-good-fam} in $n^{O(\sqrt{t+k})}$ time we compute a good family of instances $\mathcal{F}$ for the given instance $(G,R,t,k)$ of {\sc Steiner Tree}\xspace on clique-grid graphs. From Definition~\ref{def:good-fam}(2), $(G,R,t,k)$ is a yes-instance of {\sc Steiner Tree}\xspace if and only if there is an instance $(H,R,t,k') \in \mathcal{F}$ that is a yes-instance of {\sc Exact Steiner Tree}\xspace. Deriving from Definition~\ref{def:good-fam}(3), Lemma~\ref{lem:compute-good-fam} and the construction of a modified NCPD, for each instance $(H,R,t,k') \in \mathcal{F}$, there is a modified $O(\sqrt{t+k})$-NCPD for $H$, due to a guessed label $\ell$ and a guessed set $Y$ of non-terminal vertices from columns labelled by $\ell$ such that the following hold: (i) $\vert Y \vert \leq \sqrt{t+k}$, (ii) if $(H,R,t,k')$ is a yes-instance then there is an exact $k'$-Steiner tree $T$ such that all vertices of $Y$ are Steiner vertices in $T$. Let the modified NCPD using the set $Y$ have the sequence of bags $\{X_1,X_2,\ldots, X_q\}$. Recall that the definition of the modified NCPD ensures that $X_1 = X_q = Y$. In the next step, our algorithm for {\sc Steiner Tree}\xspace considers every instance $(H,R,t,k') \in \mathcal{F}$ and checks if it is a yes-instance of {\sc Exact Steiner Tree}\xspace. By Definition~\ref{def:good-fam}(2), this is sufficient to determine if $(G,R,t,k)$ is a yes-instance of {\sc Steiner Tree}\xspace. For the rest of the proof we design a dynamic programming subroutine algorithm $\mathcal{A}$ for {\sc Exact Steiner Tree}\xspace that takes as input an instance $(H,R,t,k') \in \mathcal{F}$ and uses its modified $O(\sqrt{t+k})$-NCPD to determine whether it is a yes-instance of {\sc Exact Steiner Tree}\xspace. Suppose $(G,R,t,k)$ is a yes-instance and consider a $k$-Steiner tree $T$ for $(G,R,t,k)$ where $\{uv\in E(T) \vert f(u) \neq f(v)\}$ is minimised and then the number of Steiner vertices in $T$ is minimised. Using Observation~\ref{obs:exact}, this is an exact $k'$-Steiner tree of $G$ for some $k' \leq k$. By the construction in Lemma~\ref{lem:compute-good-fam} note that there is an instance $(H,R,t,k') \in \mathcal{F}$ such that $T$ is an exact $k'$-Steiner tree for $(H,R,t,k')$. The aim of the dynamic programming algorithm is to correctly determine that this particular instance $(H,R,t,k')$ is a yes-instance. The algorithm $\mathcal{A}$ is designed in such a manner that for such a yes-instance $(H,R,t,k')$ the tree $T$ will be the potential solution Steiner tree that behaves as a certificate of correctness. The states of the dynamic programming algorithm store information required to represent the partial solution Steiner tree, which is the potential solution Steiner tree restricted to the graph seen so far. The states are of the form $\mathcal{A}$[$\ell, Q, \mathcal{Q} =Q_1\uplus Q_2 \ldots \uplus Q_b, \mathcal{P} = P_1\uplus\ldots P_b,k''$] where: \begin{itemize} \item $\ell \in [q]$ denotes the index of the bag $X_\ell$ of the modified NCPD of $H$. \item $Q \subseteq X_\ell \setminus R$ is a set of at most $$24$ \xspace \cdot $7$ \xspace$ non-terminal vertices. For each cell $\mathcal{C} = (i,j)$ that belongs to $X_\ell$, $\vert Q \cap f^{-1}(i,j) \vert \leq $24$ \xspace $. \item $\mathcal{Q} = Q_1\uplus Q_2 \ldots \uplus Q_b$ is a partition of $Q$ with the property that for each cell $\mathcal{C} = (i,j)$, $Q \cap f^{-1}(i,j)$ is contained completely in exactly one part of $\mathcal{Q}$. \item The partition $\mathcal{P}$ is over the vertex set $Q \cup (R \cap X_\ell)$. $Q \cap P_i = Q_i$. Also for each cell $\mathcal{C}$ in $X_\ell$, $\mathcal{C} \cap (Q \cup R)$ is completely contained in exactly one part of $\mathcal{P}$. \item The value $k''$ represents the total number of Steiner vertices used so far in this partial solution Steiner tree. $\vert Q \vert \leq k''$ holds. \end{itemize} Essentially, let $T$ be an exact $k'$-Steiner tree for $(H,R,t,k')$ if it is a yes-instance. For $\ell \in [q]$, let $T_{\sf ptl}^\ell$ represent the partial solution Steiner tree when $T$ is restricted to $H[\bigcup_{j=1}^{\ell} X_j]$. The partition $\mathcal{P}$ represents the intersection of a component of $T_{\sc ptl}^{\ell}$ with $X_\ell$. The set $Q$ is the set of Steiner vertices of $T_{\sf ptl}^{\ell}$ in the bag $X_\ell$ and $\mathcal{Q}$ is the partition of $Q$ with respect to the components of $T_{\sc ptl}^{\ell}$. The number $k''$ denotes the total number of Steiner vertices in $T_{\sf ptl}^\ell$. In order to show the correctness of $\mathcal{A}$ we need to maintain the following invariant throughout the algorithm: (LHS) $\mathcal{A}[\ell,Q,\mathcal{Q}=Q_1 \uplus Q_2,\ldots Q_b,\mathcal{P} = P_1\uplus P_2 \uplus P_b,k']=1$ if and only if (RHS) there is a forest $T'$ as a subgraph of $H[\bigcup_{j=1}^{\ell}]$ with $b$ connected components $D_1,\ldots,D_b$: $D_i \cap X_\ell = P_i$, $(D_i \setminus R) \cap X_\ell = Q_i$, the total number of non-terminal points in $T'$ is $k''$, for each cell $\mathcal{C}$ the number of nonterminal vertices in $\mathcal{C} \cap T'$ is at most $$24$ \xspace$, and $R \cap (\bigcup_{j=1}^{\ell} X_j) \subseteq V(T')$. Suppose the algorithm invariant is true. This means that if $\mathcal{A}[q,Y, {Y},{Y},k']=1$ then there is an exact $k'$-Steiner tree for $(H,R,t,k')$. On the other hand, suppose $(G,R,t,k)$ is a yes-instance and has a $k$-Steiner tree $T$ where $\{uv\in E(T) \vert f(u) \neq f(v)\}$ is minimised and then the number of Steiner vertices in $T$ is minimised. By Observation~\ref{obs:cell-bd}, the number of Steiner vertices of $T$ in each cell of $G$ is bounded by $$24$ \xspace$. By Observation~\ref{obs:exact} and the construction in Lemma~\ref{lem:compute-good-fam} note that there is a subset $Y$ and an instance $(H,R,t,k') \in mathcal{F}$ such that $T$ is an exact $k'$-Steiner tree for $(H,R,t,k')$ and $Y \subseteq V(T)$. Suppose the invariant of the algorithm is true. This means that if $(G,R,t,k)$ is a yes-instance of {\sc Steiner Tree}\xspace then there is a $(H,R,t,k')$ for which $\mathcal{A}[q,Y,{Y},{Y},k']=1$. Thus, proving the correctness of the algorithm $\mathcal{A}$ amounts to proving the correctness of the invariant of $\mathcal{A}$. We prove the correctness of the invariant by induction on $\ell$. If $\ell =1$ then $X_\ell$ must be a {\bf leaf bag}. By definition of the modified NCPD, the bag contains $Y$. $\mathcal{A}[1,Q,\mathcal{Q},\mathcal{P},k''] = 1$ if $Q = Y$, $\mathcal{Q}$ is the partition of $Y$ into the connected components in $H[Y]$, $\mathcal{P} = \mathcal{Q}$, $k'' = \vert Y \vert$. In all other cases, $\mathcal{A}[1,Q,\mathcal{Q},\mathcal{P},k''] = 0$. First, suppose $\mathcal{A}[1,Q,\mathcal{Q},\mathcal{P},k''] = 1$. Then as $X_1$ does not contain any terminal vertices, (RHS) trivially is true for the cases when $\mathcal{A}[1,Q,\mathcal{Q},\mathcal{P},k''] = 1$. On the other hand, suppose (RHS) is true for $\ell = 1$. Again considering the cases when $\mathcal{A}[1,Q,\mathcal{Q},\mathcal{P},k''] = 1$, (LHS) holds. So the invariant holds when $\ell =1$. Now, we assume that $\ell >1$. Our induction hypothesis is that the invariant of the algorithm is true for all $1 \leq \ell' <\ell$. We show that the invariant is true for $\ell$. There can be two cases: \subparagraph*{Case 1:} $X_\ell$ is a {\bf forget bag} with exactly one child $X_{\ell-1}$ : Let $\mathcal{C}$ be the cell being forgotten in $X_\ell$. Consider $\mathcal{A}[\ell,Q, \mathcal{Q}=Q_1,\ldots Q_b,\mathcal{P}=P_1\ldots P_b,k'']$. Let $Q' \subseteq X_{\ell-1} \setminus R$ such that $Q \subseteq Q'$ and $Q' \setminus Q$ consists of a set of at most $$24$ \xspace$ non-terminal vertices from $\mathcal{C}$. Let $\mathcal{P}'=P'_1 \ldots P'_b$ be a partition of $(Q' \cup R) \cap X_{\ell-1})$ such for each cell $\mathcal{C}'$ in $X_{\ell-1}$, $\mathcal{C}' \cap (Q' \cup R)$ is completely contained in exactly one part. Also, $P_i = P_i' \setminus \mathcal{C}$. Moreover, consider the part $P'_i$ such that $\mathcal{C} \cap (Q' \cup R) \subseteq P'_i$: $P'_i \setminus (\mathcal{C} \cap (Q' \cup R)) \neq \emptyset$. Let $\mathcal{Q}'$ be the partition of $Q'$ such that $Q' \cap P'_i = Q'_i$. If $\mathcal{A}[\ell-1,Q',\mathcal{Q}',\mathcal{P}',k''] = 1$ then $\mathcal{A}[\ell,Q,\mathcal{Q},\mathcal{P},k'']=1$. Otherwise, $\mathcal{A}[\ell,Q,\mathcal{P},k'']=0$. Suppose (LHS) of the invariant is true for $\mathcal{A}[\ell,Q,\mathcal{Q},\mathcal{P},k'']$: $\mathcal{A}[\ell,Q,\mathcal{Q},\mathcal{P},k'']=1$. By definition, there is a $\mathcal{A}[\ell-1,Q',\mathcal{Q}',\mathcal{P}',k''] = 1$ for a $Q',\mathcal{Q}',\mathcal{P}'$ as described above. By induction hypothesis, (RHS) corresponding to $\mathcal{A}[\ell-1,Q',\mathcal{Q}',\mathcal{P}',k''] = 1$ holds. Thus, there is a witness forest $T'$ in $H[\bigcup_{j=1}^{\ell-1} X_j] = H[\bigcup_{j=1}^{\ell}]$ (By definition of a forget bag). By definition of $Q,\mathcal{Q},\mathcal{P}$, $T'$ is also a witness forest in $H[\bigcup_{j=1}^{\ell} X_j]$ and therefore (RHS) is true for $\mathcal{A}[\ell,Q,\mathcal{Q},\mathcal{P},k'']$. On the other hand, suppose (RHS) is true for $\mathcal{A}[\ell,Q,\mathcal{Q},\mathcal{P},k'']$. Then there is a witness forest $T'$ in $H[\bigcup_{j=1}^{\ell} X_j] = H[\bigcup_{j=1}^{\ell-1}]$. Moreover, $T'$ has $b$ connected components $D_1,\ldots,D_b$: $D_i \cap X_\ell = P_i$, $(D_i \setminus R) \cap X_\ell = Q_i$, the total number of non-terminal points in $T'$ is $k''$ and $R \cap (\bigcup_{j=1}^{\ell} X_j) \subseteq V(T')$. Let $D_i \cap X_{\ell -1} =P'_i$, $(D_i \setminus R) \cap X_{\ell-1} = Q'_i$, $Q' = \bigcup_{j=1}^{b} Q'_i$. Note that the total number of non-terminal points in $T'$ is $k''$ and by definition of a forget node it is still true that $R \cap (\bigcup_{j=1}^{\ell-1} X_j) \subseteq V(T')$. By induction hypothesis, (LHS) is true for $\mathcal{A}[\ell-1,Q',\mathcal{Q}',\mathcal{P}',k'']$ and $\mathcal{A}[\ell-1,Q',\mathcal{Q}',\mathcal{P}',k'']=1$. By the description above, this implies that $\mathcal{A}[\ell,Q,\mathcal{Q},\mathcal{P},k'']=1$. Therefore, (LHS) is true for $\mathcal{A}[\ell,Q,\mathcal{Q},\mathcal{P},k'']$. \subparagraph*{Case 2:} $X_\ell$ is an {\bf introduce bag} with exactly one child $X_{\ell -1}$. Let $\mathcal{C}$ be the cell being introduced in $X_\ell$. Consider $\mathcal{A}[\ell,Q, \mathcal{Q}=Q_1,\ldots Q_b,\mathcal{P}=P_1\ldots P_b,k'']$. Without loss of generality, let $P_b$ contain all the vertices in $\mathcal{C} \cap (Q \cup R)$. By definition of a state, $\vert \mathcal{C} \cap Q \vert \leq $24$ \xspace$. Let ${\sf St} = \mathcal{C} \cap Q$ and $Q' = Q \setminus {\sf St}$. Let $\mathcal{P}' = P'_1\uplus P'_2\ldots \uplus P'_b \uplus \ldots P'_{d}$ be a partition of $Q' \cup (R \cap X_{\ell-1})$ such that for $j < b, P_j = P'_j$, and $P_b = \mathcal{C} \cap (Q \cup R) \cup \bigcup_{j=b}^{d} P'_j$. Moreover, $\mathcal{C} \cap (Q \cup R)$ has a neighbour in each $P'_j, b \leq j \leq d$. Let $\mathcal{Q}'$ be the partition of $Q'$ such that $Q' \cap P'_i = Q'_i$. Let $k^* = k'' - \vert {\sf St} \vert$. If $\mathcal{A}[\ell-1,Q',\mathcal{Q}',\mathcal{P}',k^*] = 1$ then $\mathcal{A}[\ell,Q,\mathcal{Q},\mathcal{P},k'']=1$. Otherwise, $\mathcal{A}[\ell,Q,\mathcal{P},k'']=0$. Suppose (LHS) of the invariant is true for $\mathcal{A}[\ell,Q,\mathcal{Q},\mathcal{P},k'']$: $\mathcal{A}[\ell,Q,\mathcal{Q},\mathcal{P},k'']=1$. By definition, there is a $\mathcal{A}[\ell-1,Q',\mathcal{Q}',\mathcal{P}',k^*] = 1$ for a $Q',\mathcal{Q}',\mathcal{P}'$ as described above. By induction hypothesis, (RHS) corresponding to $\mathcal{A}[\ell-1,Q',\mathcal{Q}',\mathcal{P}',k^*] = 1$ holds. Thus, there is a witness forest $T'$ in $H[\bigcup_{j=1}^{\ell-1} X_j]$. By definition of $Q,\mathcal{Q},\mathcal{P}$, $H[V(T') \cup (\mathcal{C} \cap (Q \cup R))]$ is a connected graph. Consider a spanning tree of this connected graph. By definition of $k^*$, this spanning tree has all vertices of $R$ and exactly $k''$ non-terminal vertices. Therefore, this spanning tree is a witness forest in $H[\bigcup_{j=1}^{\ell} X_j]$ and therefore (RHS) is true for $\mathcal{A}[\ell,Q,\mathcal{Q},\mathcal{P},k'']$. On the other hand, suppose (RHS) is true for $\mathcal{A}[\ell,Q,\mathcal{Q},\mathcal{P},k'']$. Then there is a witness forest $T'$ in $H[\bigcup_{j=1}^{\ell} X_j]$. Moreover, $T'$ has $b$ connected components $D_1,\ldots,D_b$: $D_i \cap X_\ell = P_i$, $(D_i \setminus R) \cap X_\ell = Q_i$, the total number of non-terminal points in $T'$ is $k''$ and $R \cap (\bigcup_{j=1}^{\ell} X_j) \subseteq V(T')$. Without loss of generality, let $D_b$ contain $T' \cap \mathcal{C}$. Let $D'_1,D'_2,\ldots D'_b,\ldots, D'_d$ be the connected components of $T'$ restricted to $H[\bigcup_{j=1}^{\ell-1} X_j]$. Let $D'_i \cap X_{\ell -1} =P'_i$, $(D'_i \setminus R) \cap X_{\ell-1} = Q'_i$, $Q' = \bigcup_{j=1}^{d} Q'_i$. Note that the total number of non-terminal points in $T'$ is $k^* = k'' - \vert {\sf St} \vert $ and by definition of an introduce node it is true that $R \cap (\bigcup_{j=1}^{\ell-1} X_j) \subseteq V(T') \cap (\bigcup_{j=1}^{\ell-1} X_j)$. By induction hypothesis, (LHS) is true for $\mathcal{A}[\ell-1,Q',\mathcal{Q}',\mathcal{P}',k^*]$ and $\mathcal{A}[\ell-1,Q',\mathcal{Q}',\mathcal{P}',k^*]=1$. By the description above, this implies that $\mathcal{A}[\ell,Q,\mathcal{Q},\mathcal{P},k'']=1$. Therefore, (LHS) is true for $\mathcal{A}[\ell,Q,\mathcal{Q},\mathcal{P},k'']$. Finally, we analyse the time complexity of the algorithm. First, the good family $\mathcal{F}$ is computed in $n^{O(\sqrt{t+k})}$ time as per Lemma~\ref{lem:compute-good-fam}, and the number of instances in the good family $\mathcal{F}$ is $n^{O(\sqrt{t+k})}$. For one such instance $(H,R,t,k')$ the possible states for the algorithm $\mathcal{A}$ are of the form $[\ell, Q,\mathcal{Q},\mathcal{P},k'']$. By definition, $\ell \leq n$, $k'' \leq k'$ and $Q = O(\sqrt{t+k})$. Again, by definition $\mathcal{P}$ is upper bounded by the number of partitions of cells contained in a bag of the modified NCPD of $(H,R,t,k')$. Thus, the number of possibilities of $\mathcal{P}$ is $\sqrt{t+k}^{O(\sqrt{t+k})})$. Also by definition, $\mathcal{Q}$ is fixed once $Q$ and $\mathcal{P}$ are fixed. Therefore, the number of possible states is $n^{O(\sqrt{t+k})}$. From the description of $\mathcal{A}$, the computation of $\mathcal{A}[\ell,Q,\mathcal{Q},\mathcal{P},k'']$ may look up the solution for $n^{O(\sqrt{t+k})}$ instances of the form $\mathcal{A}[\ell-1,Q',\mathcal{Q}',\mathcal{P}',k^*]$ and therefore takes $n^{O(\sqrt{t+k})}$ time. Thus, the total time for the dynamic programming is $O(n^{\sqrt{t+k}})$. \end{proof}} \old{ \section{Missing Proofs of Section~\ref{sec:FPT}}\label{secapp:FPT} \begin{proof}[Proof of Observation~\ref{obs:terminal-comps}] Consider the $k$-Steiner tree $T$ and let $S = V(T) \setminus R$ be the set of Steiner vertices of $T$. Note that in $G[R \cup S]$, $T$ is a spanning tree and therefore $G[R \cup S]$ is a connected graph. Similarly, for each $i \in [q]$, $T_i$ is a subgraph of $G[R \cup S]$. Consider the subgraph $H = T' \cup \bigcup_{i\in[q]} T_i$. As $T'$ is a spanning tree, $T' \cup \bigcup_{i\in[q]} T_i$ is a connected graph. We consider an arbitrary ordering $\mathcal{O}$ of the edges in $E(H) \setminus (\bigcup_{i\in [q]} E(T_i))$. In this order we iteratively throw away an edge $e_j \in E(H) \setminus (\bigcup_{i\in [q]} E(T_i))$ if the resulting graph remains connected upon throwing $e_j$ away. Let $H'$ be the graph at the end of considering all the edges in the order $\mathcal{O}$. We prove that $H'$ must be a tree. Suppose for the sake of contradiction, there is a cycle $C$ as a subgraph of $H'$. As for each $i\in [q]$, $T_i$ is a tree and for each $i \neq i' \in [q]$, $V(T_i) \cap V(T_{i'}) = \emptyset$, there must be an edge from $E(H) \setminus (\bigcup_{i\in [q]} E(T_i))$ in $E(C)$. Consider the edge $e \in (E(H) \setminus (\bigcup_{i\in [q]} E(T_i))) \cap E(C)$ with the largest index according to $\mathcal{O}$. This edge was throwable as $C \setminus \{e\}$ ensured any connectivity due to $e$. Thus, there can be no cycle in $H'$ and it is a spanning tree of $V(H)$. This implies that $T=H'$ is a $k$-Steiner tree for $G$, $S$ being the set of at most $k$ Steiner vertices, such that for each $i \in [q]$, $T_i$ is a subtree of $T$. Finally, we show that if a $k$-Steiner tree $T$ exists then $q \leq $25$ \xspace k$. Let $f$ be a representation of the clique-grid graph $G$. Note that for any cell $(a,b)$ $f^{-1}(a,b)$ is a clique, Therefore, there can be at most one component $C_i$ intersecting with a cell $(a,b)$. By property $(2)$ of Definition~\ref{def:clique-grid}, there are at most $$24$ \xspace$ cells that can have neighbours of any vertex in $(a,b)$. Thus, for any Steiner vertex, there can be at most $$25$ \xspace$ components of $G[R]$ it can have neighbours in. Putting everything together, if there are at most $k$ Steiner vertices that are used to connect the $q$ connected components of $G[R]$ and each Steiner vertex can have neighbours in at most $$25$ \xspace$ components, then it must be that $q \leq $25$ \xspace k$. \end{proof} } \old{ \section{Missing Proofs of Section~\ref{sec:whard}}\label{secapp:whard} \begin{proof}[Full Proof of Theorem~\ref{w1-hard}] We prove Theorem~\ref{w1-hard} by giving a parameterized reduction from the \textsc{Grid Tiling with} $\ge$ problem which is known to be W[1]-hard\footnote{$k\times k$ \textsc{Grid Tiling with} $\ge$ problem is W[1]-hard, assuming ETH, cannot be solved in $f(k)n^{o(k)}$ for any function $f$} \cite{cygan2015parameterized}. In the \textsc{Grid Tiling with} $\ge$ problem, we are given an integer n, a $k\times k$ matrix for an integer $k$ and a set of pairs $S_{ij}\subseteq [n]\times [n]$ of each cell. The objective is to find, for each $1\le i,j\le k$, a value $s_{ij}\in S_{ij}$ such that if $s_{ij}=(a,b)$ and $s_{i+1,j}=(a',b')$ then $a\ge a'$; if $s_{ij}=(a,b)$ and $s_{i,j+1}=(a',b')$ then $b\ge b'$. Let $I=(n,k,\mathcal{S})$ be an instance of the \textsc{Grid Tiling with} $\ge$. We construct a set of unit disks $D$, that is divided into three sets of unit disks $D_1, D_2, D_3$; $D=D_1\uplus D_2\uplus D_3$. Each disk in $D_1, D_2, D_3$ is of radius $1$, $\delta$ and $\kappa$, respectively. We will define the value of $\delta$ and $\kappa$ shortly. The construction of the set $D=D_1\uplus D_2\uplus D_3$ will ensure that $D$ contains a {\sc Steiner Tree}\xspace with $k^2$ Steiner vertices if and only if $I$ is a yes instance of \textsc{Grid Tiling with} $\ge$. Let $\epsilon = 1/n^{10}$, and $\delta =\epsilon/4$. Here, we point out that the value of $\kappa, \epsilon$ are independent of each other. First, we move the cells away from each other, such that the horizontal (resp. vertical) distance between the left columns (resp. top rows) any two consecutive cell is $2+\epsilon$. Let $100\delta$ be the side of length of each cell. Then, we introduce diagonal chains of terminal disks into $D_3$ of radius $\kappa=\sqrt{2}(2+\epsilon - 100\delta)/1000$ to connect the cells diagonally; see Figure~\ref{W-hard-connected}(a). For every $1\le x, y\le k$, and every $(a,b)\in S(x,y)\subseteq [n]\times [n]$, we introduce into $D_1$ a disk of radius $1$ centered at $(2x+\epsilon x+\epsilon a, 2y+\epsilon y+\epsilon b)$. Let $D[x,y]\subseteq D_1$ be the set of disks introduced for a fixed $x$ and $y$, and notice that they mutually intersect each other. Next, for $1\le x, y\le k$, we introduce into $D_2$, disks of radius $\delta$ between consecutive cells of coordinate $(2x+1+\epsilon x+\epsilon a, 2y+\epsilon y)$ (placed horizontally); and $(2x+\epsilon x, 2y+1+\epsilon y+\epsilon b)$ (placed vertically). For every cell $S[x,y]$, we denote the top, bottom, left, right cluster of terminal disks of radius $\delta$ from $D_2$ by $L[x,y], R[x,y], T[x,y], B[x,y]$, respectively. Moreover, for each cell $S[x,y]$, we introduce a disk of radius $\delta$ at a coordinate that is completely inside the rectangle bounding the centres of disks in $D[x,y]$. This is to enforce that at least one disk is chosen form each $D[x,y]$. See Figure~\ref{W-hard-connected}(b) for an illustration. We proceed with the following observation. Consider a disk $p$ that is centered at $(2x+\epsilon x+\epsilon a, 2y+\epsilon y+\epsilon b)$ for some $(a,b)\in [n]\times [n]$. Now, consider a disk $q$ from $R[x,y]$ centered at $(2x+1+\epsilon x+\epsilon a, 2y+\epsilon y)$. The distance between their centers are $\sqrt{1+\epsilon^2 b^2}$. We need to show that this is less than $(1+\epsilon/4)$. This is true because $1+\epsilon^2 b^2$ is less than $(1+\epsilon/4)$ as the value of $b$ goes to $n$, $\epsilon = 1/n^{10}$ and the value of $n$ is large. Hence, $q$ is covered by the disk $p$ from $S[x,y]$ centered at $(a,b)$. Next, consider a disk $q'$ from $R[x,y]$ centered at $(2x+1+\epsilon x+\epsilon (a+1), 2y+\epsilon y)$. The distance between their centers are $\sqrt{(1+\epsilon)^2+\epsilon^2 b^2}$. We show that this value is bigger than $(1+\epsilon/4)$. This means $(1+\epsilon)^2+\epsilon^2 b^2$ is bigger than $(1+\epsilon/4)^2$. As the value of $b$ goes to $n$, it is not hard to see the left side is bigger since $\epsilon=1/n^{10}$ and the value of $n$ is large. Therefore, $q'$ is not covered by the disk $p$ from $S[x,y]$ centered at $(a,b)$. The same calculation holds for $L[x,y]$, $T[x,y]$ and $B[x,y]$. In the forward direction, let the pairs $s[x,y]\in S[x,y]$ form a solution for instance $I$, and let $s[x,y]=(a[x,y],b[x,y])$. For every $1\le x,y\le k$, we select the disk $d[x,y]$ from $D_1$ of radius $1$ centered at $(2x+\epsilon x+\epsilon a[x,y], 2y+\epsilon y+\epsilon b[x,y])$. We have seen in the previous paragraph that this disk cover any disk from $R[x,y]$ of center with $(2x+1+\epsilon x+\epsilon a[x,y], 2y+\epsilon y)$ but does not covers disks with coordinate $(2x+1+\epsilon x+\epsilon (a[x,y]+1), 2y+\epsilon y)$. Similarly, this holds for $L[x,y],T[x,y],B[x,y]$. $s[x,y]$'s forms a solution of $I$, then we have $a[x,y]\ge a[x+1,y]$. Therefore, the disks $d[x,y]$ and $d[x+1,y]$ will cover all disks from $R[x,y]$. Similarly, we have $b[x,y]\ge b[x,y+1]$ which implies that $d[x,y]$ and $d[x,y+1]$ will cover $T[x,y]$ and form a component them. Now, the diagonals chains consisting of terminal disks of radius $\kappa$, we have taken to join the cells (see Figure~\ref{W-hard-connected}(a)) ensures that all cells are connected. Moreover, we have shown that if $s[x,y]$'s form a solution of instance $I$, then all terminals in $L[x,y], R[x,y], T[x,y], B[x,y]$ (for any $1\le x, y\le k$) are covered. Therefore, this will form a connected Steiner tree with $k^2$ many Steiner disks. In the reverse direction, let $D'\subseteq D_1$ be a set of $k^2$ Steiner disks that spans over all terminals in $D_2\cup D_3$. This is true when for every $1\le x,y\le k$, the set $D'$ contains a disk $d[x,y]\in D[x,y]$ that is centered at $(2x+\epsilon x+\epsilon a[x,y], 2y+\epsilon y+\epsilon b[x,y])$ for some $(a[x,y],b[x,y]) \in [n]\times [n]$. Indeed, we are required to choose one disk from $D[x,y]$ due to the reason that there is a terminal disk lying inside the rectangle bounding the centres of disks in $D[x,y]$. The claim is that $s[x,y]=(a[x,y],b[x,y])$'s form a solution of $I$. First of all, $d[x,y]\in D[x,y]$ implies that $s[x,y]\in S[x,y]$. Consider a cell $S[x,y]$. We have observed that it covers disk $q$ from $R[x,y]$ centered at $(2x+1+\epsilon x+\epsilon a, 2y+\epsilon y)$, but a disk $q'$ from $R[x,y]$ centered at $(2x+1+\epsilon x+\epsilon (a+1), 2y+\epsilon y)$ is not covered. This is true for $L[x,y], T[x,y], B[x,y]$. Hence, if all terminals points from inside $S[x,y]$'s and $L[x,y], R[x,y], T[x,y], B[x,y]$ are covered by $k^2$ many Steiner disks, it would imply that $a[x,y]\ge a[x+1,y]$ and $b[x,y]\ge b[x,y+1]$. Therefore, $s[x,y]$'s form the solution for \textsc{Grid Tiling with} $\ge$ instance $I$. This completes the proof. \end{proof}} \section{Introduction}\label{sec:intro} \input{intro} \section{Preliminaries}\label{sec:prelims} \input{prelims} \section{NP-Hardness of {\sc Steiner Tree}\xspace on Unit Disk Graphs}\label{sec:nph} \input{np-hardness} \section{Subexponential Exact Algorithm for {\sc Steiner Tree}\xspace on Unit Disk Graphs}\label{sec:subexp} \input{UDG-subexp} \section{FPT Algorithm for {\sc Steiner Tree}\xspace on Unit Disk Graphs}\label{sec:FPT} \input{UDG-FPT.tex} \section{W[1]-Hardness for {\sc Steiner Tree}\xspace on Disk Graphs}\label{sec:whard} \input{w-hardness-new} \paragraph*{Conclusion} \input{conclusion}
{'timestamp': '2020-04-21T02:25:48', 'yymm': '2004', 'arxiv_id': '2004.09220', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09220'}
arxiv
\section{The new Approach: Tracemax} In reference to the scenario in Section \ref{scenario}, a user sends a specific request to his ISP to start labeling packets. This activates the novel traceback algorithm \textit{Tracemax} for a predefined number of routers. These routers have to cooperate and have to be configured for it. \textit{Tracemax} consists mainly of a marking scheme and a reconstruction method. The routers are marking packets on the path during the transmission. The reconstruction method determines the path of a packet afterwards. \subsection{Pre-configuration and ID assignment} Before the \textit{Tracemax} system is rolled out, every physical port $n$ of every router $T_{i}$ gets his own \textit{Tracemax} $ID_{i,n}$. An $ID$ is not necessarily unique in the entire system. Still the $ID$ numbers have to defined in a way that the path reconstruction is uniquely possible. In analogy of the logical port number, an assigned \textit{Tracemax} $ID$ is oriented on it. But for every router is not allowed to get the same incoming ID of several connected routers. The generation of the IDs is still easy under this condition. An automatic algorithm is described in \mbox{Listing \ref{lst:IDGeneration}}. The algorithm prevents that a preselected router gets the same ID on direct links from two neighboring routers. This is achieved by incrementing one of the intended IDs. \lstset{ % backgroundcolor=\color{white}, basicstyle=\footnotesize, frame=single, keywordstyle=\footnotesize, keywords={}, deletekeywords={all}, numbers=none, numbersep=5pt, stepnumber=1, tabsize=2, } \lstset{aboveskip=10pt} \begin{lstlisting}[frame=single,caption={Algorithm for automatic ID assignment.},label=lst:IDGeneration,float=htbp, belowskip=-2.2 \baselineskip] 1. Select randomly the first node. 2. Assign every port the ID as their port number n. 3. do { 4. selectedNode = a connected node to the already selected node(s), which has not selected. 5. for ( all free ports of selectedNode ) { 6. isAssigned = false; 7. ID = 1; 8. do { 9. if ( ID is unused at selectedNode ) { 10. if ( ID != all incoming IDs at the connected node){ 11. selectedNode.portID = ID; 12. isAssigned = true; 13. } 14. } 15. ID++; 16. } until ( !isAssigned ) 17. } 18. } until ( all nodes are selected ) \end{lstlisting} Two possible valid ID assignments with minimal bit size and with an automatic assigned version can be seen in \mbox{Figure \ref{Tracemax}} and \ref{Tracemax2}. An invalid example of ID assignment is shown in \mbox{Figure \ref{Tracemaxfail}}. The encircled router has twice the incoming ID number 3. Thereby the simple reconstruction function is not able to decide between the two routers as source of a packet. \begin{figure}[hbtp] \vspace*{-2mm} \begin{minipage} [hbt]{4.22cm} \begin{center} \includegraphics[width=0.9\textwidth]{fig/Tracemax.png}\\ \caption{Valid configuration.} \label{Tracemax} \end{center} \end{minipage} \textbf{or}\hfill \begin{minipage} [hbt]{4.22cm} \begin{center} \includegraphics[width=0.9\textwidth]{fig/Tracemax2.png}\\ \caption{Valid configuration.} \label{Tracemax2} \end{center} \end{minipage} \vspace*{-3mm} \end{figure} A strong reconstruction algorithm, which gives attention on the transfer direction of a packet, is possible to resolve even some conflicted IDs. Nevertheless, every router in the network should mark packets. This avoids unclear or incomplete ID sequences, which can not be reconstructed to a transmission path. But it is not mandatory for a clear path reconstruction that the entire network is completely configured to mark packets. With genial predefined and assigned IDs single routers can be bridged, see \mbox{Figure \ref{szenarioBridge}}. This ID assignment allows a unique path reconstruction even the network device in the middle do not marking transfered packets. \begin{figure}[hbtp] \vspace*{-2mm} \begin{minipage} [hbt]{4.7cm} \begin{center} \includegraphics[width=0.78\textwidth]{fig/Tracemax2fail.png} \caption{Invalid ID assignment.} \label{Tracemaxfail} \end{center} \end{minipage} \hfill \begin{minipage} [hbt]{3.9cm} \vspace*{3mm} \begin{center} \includegraphics[width=0.75\textwidth]{fig/szenarioBridge.png} \caption{A bridged router.} \label{szenarioBridge} \end{center} \end{minipage} \vspace*{-5mm} \end{figure} \subsection{Marking scheme} Every router $T_{i}$ on the path writes the predefined $ID_{i,n}$ in the \textit{Option Field} of the IP packet. Even if the size is very limited (40 bytes), the \textit{Option Field} in our case is best choice and the size is sufficient. This increases the network load only slightly and has no side effects. Our defined unique $ID_{i,n}$ number with less than 6 bits for labeling every port $n$ of an active network device $i$ is much smaller than 32 bits of an IPv4 address. In this way we can store many more hops in form of $ID$s into the \textit{Option Field}. The precise necessary bit size of the $ID$ number ($n = 1..k$) depends on the situation. The bit size hangs indirectly on the router $T_{i}$ with most physical connections $k$, which is in the predefined area of \textit{Tracemax}. For performance improvement, single network devices with many ports can be virtually split in multiple devices to lower the maximum necessary bit size for an $ID$ number. The $ID_{i,n}$ can be seen as a lower ISO/OSI layer information, for example the port number of a physical connection on a router. In the process of development, the \textit{Tracemax} $ID$ is declared as an abstract number, which is independent from the port number. This allows improvements during the $ID$ assignment and leads to a reduced bit size for the $ID$s. Every router $T_{i}$ writes the assigned and predefined $ID$ of the physical port into the packets \textit{Option Field} at the outgoing interface. The next router can prove the value. \subsection{Reconstruction scheme} The reconstruction function extracts the IDs out of the IP header. The sequence of IDs defines the used connections between the routers and thereby the path of the packet. The function needs information about the endpoint where the packet is captured. This information can be stored with the packets or the user already knows it. In most cases the reconstruction is running at the same system as the endpoint. Otherwise, the last and closest IP address to the destination could be stored completely into the \textit{Option Field} as well. The function correlates the sequence of the IDs with the knowledge of the network infrastructure and the predefined IDs. This is done step-by-step backwards, starting from the receiver node until the last marked node is found. Due to the precise ID assignment only one possible connection is valid in every step of the backward path reconstruction. The administrator of \textit{Tracemax} has all necessary information allowing the complete reconstruction of the path. The function can also map these routers to their IP addresses. In the end, the order of the routers and the IP addresses of the path are known. \subsection{Additional extensions} If an incoming packet is entered into the managed \textit{Tracemax} system, the information in the \textit{Option Field} has to be deleted. This prevents injecting of false information and generates space for the own traceback information. This is the case at the borders of different \textit{Tracemax} systems or ISPs. An incoming packet at a \textit{Tracemax} system edge router should be labeled with the sending router IP address from the routing table or with an additional ID. Thus the path reconstruction is extended with reference to the first external routing device. Also if a packet leaves the managed \textit{Tracemax} components the last marking edge router can store an information about the next network device without marking functionality into the \textit{Option Field}. This also supports to bridge network devices. In summary, the \textit{Option Field} includes in the complete version the following information: [Preamble : IP-Sender : $1^{st}$ ID : $2^{nd}$ ID : $3^{rd}$ ID : ..... : n-1. ID : n. ID : IP-Receiver]. A stepwise roll out or limited deployment of the \textit{Tracemax} System is possible. Thus it allows to trace the path of a transfered packet only partly. A large advantage of \textit{Tracemax} is that it does not provide any information about the private topology information of an ISP even if someone gets access to the IDs in the \textit{Option Field}. The IDs could also be changed in a short interval to avoid reverse engineering. In the scenario of DDoS we have to assume that IP spoofing is used by the attacker. This aspect does not influence our \textit{Tracemax} strategy because it is not based on IP source addresses. \subsection{Storing the information in the IP header}\label{Option-Field} In the following, the Preamble and the entire \textit{Option Field} is explained in more detail, because not all of the available bytes are free and flexible usable. The IP header in version 4 is 20 bytes large and offers an additional \textit{Option Field} with the variable length of up to 40 bytes, dependent on Padding. There are two different formatting styles to add information in the \textit{Option Field . The traceback information can either be added as single octet. \textit{Tracemax} on the other hand uses the defined option-length to be able to predefine the necessary space. The Preamble of all option-type parts is: 1 bit \textit{Copied Flag}, 2 bits \textit{Option Class}, and 5 bits \textit{Option Number}. The 1 bit \textit{Copied Flag} defines that this option part is copied into all fragments. Thus every single packet is traced so it will be set to $0_{2}$. For the 2 bit \textit{Class Field} exists different valid possibilities. The measurement parameter with $10_{2}$ is most fitting for our case. A list of all different specified 5 bits \textit{Option Number} parameters can be found at \cite{ipparameters}. We have to find a value, which do not create conflicts. \textit{Tracemax} uses the unassigned option number $1 0110_{2}$ ($22_{10}$). In combination, the $1^{st}$ octet is: $86_{10}$ = 0x56 = $0 1 0 1 0 1 1 0_{2}$ The \textit{Option Number} parameters has a \textit{traceroute option}, but it offers only the possibility to count the hops and do not allow to traceback a packet. It is very important to give attention on this formatting, because of possible malformed packets or the unintentionally mapping with some other option values. For example, the two option values \textit{Loose Source Route} and \textit{Strict Source Route} are discouraged because of security concerns\cite{faqs14} and will be dropped. Furthermore, this octet is followed by the \textit{option-length} octet, which specifies the length of the current option part including the option part heade . The size can be between 0 and 40 byte. It is possible to extend the header according to the demand. % The $2^{nd}$ octet is: $40_{10}$ = 0x28 = $0 0 1 0 1 0 0 0_{2}$ This concept can be easily adapted to IP version 6. For this, it is necessary to define a new \textit{Next Header} to store the traceback information. \section{Introduction}\label{introduction} One of the most publicly recognized distributed denial of service (DDoS) attacks took place in 2010. As protest reaction on inhibition of WikiLeaks bank accounts, MasterCard, Visa and PayPal as well as other large finance institutes got attacked \cite{forbes10}. The coordinated action named \glqq Operation Payback\grqq{} has stopped aforesaid services for several hours causing great financial loss. In 2014, the largest detected DDoS attack had consumed a bandwidth of over 500 Gbit/s\cite{forbes14}. Nowadays, no service infrastructure can handle such large amount of data. The power and danger of DDoS attacks is an increasingly frequent problem in the global Internet. Attacks are not only focused against single services but entire countries and infrastructures. An adequate traceback and defense strategy is needed in order to identify multiple sources and to reveal spoofed IP addresses. It is important to get provable identification and localization of the attackers for law enforcement and forensic analysis. Of large interest for states is especially the source of military cyber operations or protest groups. \section{PROBLEM DESCRIPTION} \section{Related work}\label{relatedwork} Over the past years, many traceback and defense strategies have been developed. The approach of Deterministic Router Stamping (DRS)\cite{25} is only able to trace up to 9 hops whereas Probabilistic Router Stamping (PRS) need many packets to reconstruct the path. Packet Marking (PM) \cite{27} is differentiated in Node-Sampling and Edge-Sampling. They are not efficient with respect to the capacity. The marking information in the payload can cause errors. Link Testing by Input Debugging (LTID) \cite{29} and Link Testing by Controlled Flooding (LTCF) \cite{30} require a continuous attack for complete attack path identification and limit immediate live defense actions. The approach of Logging at a router \cite{35} creates a large amount of data, needs a lot resources and limit live response actions. The backward discovered path of the Internet Control Message Protocol (ICMP) traceback approach \cite{36} does not necessarily match the real path of a packet, because of load balancing and other influences. The ISP Traceback \cite{stelte13, Khan} allows the identification of the source ISP, but not track the direct path. There are more algorithms and hybrid solutions to trace packets as in \cite{Gong2008}. All in all, the known traceback strategies do not fulfill the identified requirements to trace the path of network packets. \section{Requirements and assumptions}\label{sec:requirements} For our analysis, we assume that routes can dynamically change during an attack. Furthermore, packets can get lost, and the order of the packets within a connection can be changed. Finally, attackers are able to generate any packet with any faked parameters. Attackers are able to cooperate and have knowledge of traceback strategies. According to the scenario and the various application areas, we address traceback strategies concerning to the following main aspects: \begin{itemize} \vspace*{1mm} \item \textbf{Single packet traceback} \item Detect and Differentiate \textbf{multiple attackers} \item \textbf{Fast path reconstruction} and \textbf{preventive applicable} \item \textbf{Traced Hops / Locations} of more than 50 hops\\ \vspace*{-3mm} \end{itemize} \newpage A call of the website \textit{''torproject.org''} from our location is transferred over more than 18 routers. It does not include proxy servers or anonymizing techniques. The worst case number of nodes traversed by a packet was about 56 hops in 2011 \cite{Chinnery2010}. \section{Proof of concept and evaluation}\label{simulation} The evaluation of the \textit{Tracemax} is based on experiments using a prototypic implementation. Our approach is implemented with the interactive packet manipulation and generation tool \textit{Scapy}, which is written in Python. We have set up trial installations with multiple network components and several computer. The network components for packet marking are realized by computer with appropriate router configuration. Thus, the tests are very realistic. The Python Script, Listing \ref{lst:python}, describes the marking algorithm of \textit{Tracemax}, which is used at every router. First, the script detects whether the incoming packet has an \textit{Option Field} or not. Accordingly, the \textit{Option Field} is copied or added with the Preamble '\textbackslash x56\textbackslash x28'. It extends the \textit{Option Field} with its specific ID defined in the variable 'myindex', here the value '\textbackslash x12'. For simplification, every router has only one ID to mark the packets with. We also avoid a dynamic extension of the \textit{Option Field} for the tests. After a new packet is generated, it will be send to the next network hop. For the experiments, the Script filters on ICMP packets.\\ \lstset{aboveskip=-8pt} \lstset{language=Python} \lstset{ % backgroundcolor=\color{white}, basicstyle=\footnotesize, frame=single, numbers=none, numbersep=5pt, stepnumber=1, } \begin{lstlisting}[frame=single,caption={Python script for Tracemax.},label=lst:python,float=htbp, belowskip=-1.4 \baselineskip] from scapy.all import * def chgSend(x): myindex = '\x12' # Assigned Port Identifier optionsarray = x[IP].options #Option Field if optionsarray.count(1) == 0 and str(optionsarray) != '[]' : optionsstring = str(optionsarray[0]) else: optionsstring = '\x56\x28' #Generate packet y=IP(src=x[IP].src,dst=x[IP].dst,len=60,options= IPOption(optionsstring+myindex))/x[IP].payload send(y) while 1: # Listen to the network interface sniff(prn=chgSend, lfilter=lambda x: x.haslayer(ICMP), count=1) \end{lstlisting} During the evaluation, every machine runs \textit{Wireshark} for packet capturing. The reconstruction of the path is done manually to examine and resolve possible problems. The \textit{Wireshark} traces show the packet marking in the \textit{Option Field} after each hop. The transmission path can be reconstructed in combination with the known information about the ID assignment. The experiments validate our concept and show the easy implementation as well as the practicability. To extend the IP-Header with the entire 40 bytes, it creates a small additional network load of \mbox{2.$\overline{\text{6}}$ \%} for a 1500 bytes packet. To summarize the results, Table \ref{tab:comparison} compares our \textit{Tracemax} system with the existing strategies. The symbols have the following meaning in comparison to the other traceback techniques: + advantage; - disadvantage; o neutral. \vspace{-1mm} \begin{table}[htb] \centering \caption{Comparison of different traceback strategies} \setlength{\tabcolsep}{1pt} \small \begin{tabular}{|c!{\vrule width 0.8pt}c|c|c|c|c|c|c|c|c|c|c|c|c|} \hline \rotatebox{90}{\textbf{Algorithms}} & \rotatebox{90}{\parbox{2.1cm}{\textbf{Traced Hops /\ \\ Locations}}} & \rotatebox{90}{\textbf{Effectiveness}} & \rotatebox{90}{\textbf{Efficiency}} & \rotatebox{90}{\textbf{Robustness}} & \rotatebox{90}{\textbf{Scalability}} & \rotatebox{90}{\textbf{Costs}} & \rotatebox{90}{\parbox{1.9cm}{\textbf{No ISP\\ cooperation}}} & \rotatebox{90}{\parbox{1.9cm}{\textbf{Deploy entire\\ Sub-Network}}} & \rotatebox{90}{\parbox{2.2cm}{\textbf{Short Detection\\ Time}}} & \rotatebox{90}{\parbox{1.9cm}{\textbf{Preventive\\ usable}}} & \rotatebox{90}{\parbox{1.9cm}{\textbf{Single Packet\\ Traceback}}} & \rotatebox{90}{\parbox{2.1cm}{\textbf{Detect multiple\\ senders}}} \\ \hline \hhline{-------------} Ingress Filtering & 0 & - & + & + & + & + & - & + & + & + & + & + \\\hline RS-DRS & 9 & + & o & o & o & + & + & o & + & + & + & + \\\hline RS-PRS & $\infty$ & + & o & o & o & + & + & o & - & + & - & - \\\hline PM-Node-Samp. & $\infty$ & + & + & o & + & o & + & o & o & + & + & + \\\hline PM-Edge-Samp. & 1 edge & o & - & o & + & o & + & o & - & + & - & - \\\hline LT-Input Debug. & $\infty$ & o & - & + & o & o & o & - & - & - & - & - \\ \hline LT-Cont. Flood. & $\infty$ & - & - & o & - & + & o & + & - & - & - & - \\ \hline Logging & $\infty$ & + & + & + & + & - & - & + & - & + & + & + \\ \hline ICMP & $<$256 & o & o & - & + & + & + & + & + & - & + & + \\ \hline ISP Traceback & ISP & - & o & - & + & + & + & + & + & + & + & o \\ \hline\hline \textbf{Tracemax} & \textbf{$>$50} & \textbf{+} & \textbf{+} & \textbf{+} & \textbf{+} & \textbf{+} & \textbf{+} & \textbf{o} & \textbf{+} & \textbf{+} & \textbf{+} & \textbf{+} \\ \hline \end{tabular} \label{tab:comparison} \vspace{-6mm} \end{table} \section{Conclusion} We presented the concept of a strong traceback strategy \textit{Tracemax} and an idea to defense against DDoS attacks. It can track the path of just a single packet through the network and address forensic intentions. \textit{Tracemax} can trace significant longer paths than existing methods, detect variable routes during a communication, and distinguish multiple attackers. The technique does not affect the payload data of the packet. Therefore, the labeling information does not need to be cleared before delivery. The novel strategy reduces the impact of an attack on the victim and the entire network. The presented solution focus directly on the unwanted traffic with negligible influence on good users. Due to its minimal additional overhead and simple requirements the system results in good scalability and allow a preventive usage. \section{Scenario}\label{scenario} The idea of an traceback strategy provided by an Internet service provider (ISP) is illustrated by using the following real world scenario, see Figure \ref{TracebackAttacker}. A DDoS attack and malicious traffic are detected at a terminal system by an intrusion detection systems (IDS). The associated alarm vector triggers the labeling service at the victims own edge router. It propagates self-organizing this labeling task through the network. The service is secured by cryptographic authentication. After the configuration of the routers, all messages can be traced back. The traffic data, path labeling data and attack meta data are prepared and stored with time stamp to cope with the forensic needs for trustworthy and transparent path reconstruction of law enforcement. The service extends the data for digital forensics in a live response scenario. In parallel, the system starts defense actions by propagating the attack signature to the routers. It is used for filtering, blocking or delaying of corresponding incoming traffic and reduces the network load. Other use cases are the verification of traffic shaping configured in the network management system and identification of hidden channels. Load balancing and zone routing can be verified by packet tracking as well. In addition, the technique provides an approach to detect Cormelt attacks with currently no defense mechanisms existing. Thereby, a Botnet generate pseudo realistic traffic between the bots at a specific network node and overload it. \begin{figure}[htbp] { \vspace{-3mm} \centering \includegraphics[width=0.34\textwidth]{fig/SzenarioP.png} \caption{Traceback of sophisticated attackers.} \label{TracebackAttacker} \vspace*{-4mm} } \end{figure} \section{SCENARIO}\label{scenario} We imagine on a scenario that someone starts attacking a user at a different ISP zone than himself. If the victim is under pressure of a network consumption attack, the massive inbound traffic blocks a normal communication to other systems, which could support to defend. Such attacks can be very easily detected at the end user or vicitim \cite{Li2003, Sanmorino13}. At this moment, the host system of the victim has still enough resources to analyze the incoming traffic and to filter wrong and normal requests. Otherwise, the victim has to send these data to an Host Intrusion Detection System or a Network Intrusion Detection System, which would detect by its own that the server is under attack. Depending on the signature of the bad request, which could be something very simple like IP addresses, Ports or special Protocols, the system will store this information with a time stamp in a database. The victim or the operator of the local network activate the traceback configuration to find the source of the attack and start defending against it. The router propagate the activation through the entire network by themself, also to the ISP routers. Therefore, an cooperation with the ISP is necessary. ISPs should be self interested in reducing their load on their network and defending against bandwidth consumption attacks. These configuration messages are cryptographic authenticated. Furthermore, the signature of the bad packets is also propagated. The routers use this signature to start filtering and blocking such incoming messages. After the configuration of the router, all messages will be traced. The traceback information is prepared in a kind that the victim, ISP and network management is able to address the forensic needs of law enforcement. Figure \ref{TracebackAttacker} shows an example of necessary components for traceback and the different attack paths of the attacker. \vspace{1mm} \begin{figure}[htb] { \centering \includegraphics[width=0.5\textwidth]{fig/SzenarioP.png} \caption{Traceback of an attacker.} \label{TracebackAttacker} } \end{figure} \section*{Acknowledgment} This work was partly funded by ''FLAMINGO'', a Network of Excellence project (ICT-318488) supported by the European Commission under its Seventh Framework program. \bibliographystyle{IEEEtranS}
{'timestamp': '2020-04-21T02:28:04', 'yymm': '2004', 'arxiv_id': '2004.09327', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09327'}
arxiv
\section{Introduction} Thanks to recent research efforts~\cite{wei2017glad,su2017pose,kalayeh2018human,hermans2017defense,wang2018mancs,sun2018beyond,yang2019towards,zheng2019re,zheng2018Pyramidal}, the performance of person re-Identification (reID) has been significantly improved. However, one potential issue with current reID setting is that, it treats person detection and reID as two isolated steps. This issue can be compensated by person search~\cite{tong2017Joint,zheng2017Person,chen2018Person,xu2018Person,han2019Re,munjal2019Query} to jointly accomplish person detection and reID. Being able to jointly optimize person detection and reID, person search is attracting more and more attention, and is potential to present advantages in flexibility, efficiency, and accuracy. Compared with reID, person search needs to design pedestrian detectors robust to variances of scales, illuminations, backgrounds, occlusions, \emph{etc}. Some person search works refine detectors by jointly training detectors and reID models~\cite{tong2017Joint,munjal2019Query,hao2017Neural,han2019Re}. Although strong detectors are generally helpful for reID, they may still produce misaligned person bounding boxes. As shown in Fig.~\ref{fig:motivation}, occlusions and limited camera viewing field lead to many accurate but misaligned bounding boxes covering portions of pedestrians. Most of existing person search methods extracts global feature from the detected bounding boxes, no matter the joint models~\cite{tong2017Joint,munjal2019Query} or the separate models~\cite{chen2018Person,xu2018Person,han2019Re}. As shown in Fig.~\ref{fig:motivation}, misalignment degrades the performance of global features, because it is not reasonable to match partial features against global features. More detailed reviews to person search works can be found in Sec.~\ref{sec:relatedwork}. \begin{figure}[t] \centering \begin{center} \includegraphics[width=0.46\textwidth]{aligndiscard}\\ \end{center} \caption{Illustration of misaligned person bounding boxes and issues of person matching with global feature. Misalignments commonly occur in person search and can not be eliminated by training stronger detectors. This paper addresses this issue with bounding box alignment and partial matching.} \label{fig:motivation} \vspace{-0.2cm} \end{figure} This paper targets to design a unified person search framework robust to the misaligned bounding boxes. As shown in Fig.~\ref{fig:motivation}, the basic idea is to refine detected bounding boxes to cover the estimated holistic body regions to eliminate misalignment errors. Then, aligned part features could be extracted from refined bounding boxes with simple region division. Part features hence allow for robust partial matching across bounding boxes, where features on the mutual visible regions are matched for similarity computation, and features on noisy regions are not considered for matching. In other words, our strategy improves both the feature resolution and robustness to misalignment errors. The above idea leads to the Align-to-Part Network (APNet) for person search. Built on OIM~\cite{tong2017Joint}, APNet consists of the additional Bounding Box Aligner (BBA) and Region Sensitive Feature Extractor (RSFE). The BBA module is implemented by predicting 4 bounding box offset values. It can be trained by automatic data augmentation without requiring manual annotations. Because of enlarged receptive fields of neurons in feature extraction CNN layer, noisy or occluded parts would affect features of their adjacent parts in the same bounding box. We further design the RSFE module to extract part features. RSFE reinforces local cues in each part feature, hence effectively alleviates the negative effects of adjacent noises in part feature learning. We test our approach on current person search benchmarks, \emph{i.e.}, PRW~\cite{zheng2017Person} and CUHK-SYSU~\cite{tong2017Joint}. Experiment results show that, our APNet achieves competitive performance compared with recent works. To test our approach in more challenging scenarios, we contribute a new person search dataset named as Large-Scale dataset for Person Search in the wild (LSPS). Compared with PRW and CUHK-SYSU, LSPS presents several new features that would encourage the research towards more realistic person search: 1) large scale: it contains a large number of pedestrians and bounding boxes; 2) automatically detected bounding boxes, which differ with the manually annotated ones in PRW and CUHK-SYSU; 3) collected in scenarios with occlusions and crowdings. On this challenging LSPS, our method exhibits substantial advantages. Compared with reID, person search is still relatively under-explored. It is critical to deal with the challenge occuring in both person detection and reID. To the best of our knowledge, the proposed APNet is an early attempt in boosting the robustness to misalignment issue in person search. As shown in our experiments, the APNet brings considerable performance gains. The proposed LSPS dataset simulates realistic scenarios and presents a more challenging person search task than existing datasets. We believe that, the proposed methods and the contributed LSPS can inspire more research efforts in person search. \section{Related Work} \label{sec:relatedwork} This paper is closely related to person reID and person search. The following parts review those two lines of works. \emph{Person reID} extracts robust and discriminative features from given person bounding boxes. Current fully supervised reID methods can be briefly summarized into the following categories. 1) Learn local features of regions utilizing offline detector to split body into several regions~\cite{wei2017glad,su2017pose,kalayeh2018human,li2019pose}, or uniformly split the body into several stripes~\cite{zheng2018Pyramidal,sun2018beyond,wang2018Learning}; 2) Learn the robust feature utilizing additional attribute annotation~\cite{su2016deep,su2015multi,su2017attributes,tay2019aanet}; 3) Enhance the discriminativeness of feature by attention mechanism~\cite{li2018harmonious,hou2019interaction,wang2018mancs}; 4) Impose constraints on feature space with loss functions, like verification loss~\cite{zheng2018discriminatively} and triplet loss~\cite{hermans2017defense}. Among the above methods, PCB~\cite{sun2018beyond} and its variants~\cite{zheng2018Pyramidal,wang2018Learning} dominate the state-of-the-art performance. PCB uniformly splits the feature map into stripes and supervises them to ensure their discriminative power. However, PCB requires a strict alignment of the input images since misalignment breaks the correspondence of stripes on the same spatial position. The performance of PCB thus degrades substantially when misalignments exist~\cite{sun2019Perceive}. There are some reID works focusing on partial reID. Zheng \textit{et al.}~\cite{zheng2016Partial} propose AMC+SWM to solve the partial reID. AMC collects patches from all gallery images and set up a dictionary for patch level matching. He \textit{et al.}~\cite{he2018Deep} propose DSR to reconstruct the partial image by holistic image and utilize the reconstruction error as the similarity. Both AMC~\cite{zheng2016Partial} and DSR~\cite{he2018Deep} are optimisation-based thus it is expensive to get the similarity of each query-gallery pair. PGFA~\cite{miao2019pose} applies partial matching scheme with the aligned input images, whose occluded parts are indicated by the expensive offline keypoint detector. Sun \textit{et al.}~\cite{sun2019Perceive} propose a VPM to extract local features while simutaneously being aware of the visibility of each body part. However, VPM does not consider the deformation mentioned in DSR. Our method address the deformation by an explicit alignment step and gets rid of the time-consuming comparsion of each query-gallery pair during the inference stage. \emph{Person search} considers the detection stage in raw video frames before reID. Current methods of person search can be divided into two categories. One integrates detection and reID into a unified framework~\cite{tong2017Joint,munjal2019Query,hao2017Neural,yichaoLearning}. Based on Faster-RCNN~\cite{ren2015faster}, OIM proposed by Xiao \textit{et al.}~\cite{tong2017Joint} inserts an additional feature extraction branch on top of the detector head, which is the first end-to-end learning framework for person search. Similar to NPSM of Liu \textit{et al.}~\cite{hao2017Neural}, Munjal \textit{et al.}~\cite{munjal2019Query} apply a query-guided method for person search while it is end-to-end optimized compared to NPSM. The other category solves detection and re-identification with two separate models, \emph{i.e.}, performing person search in a sequential manner~\cite{chen2018Person,xu2018Person,han2019Re}. Chen \textit{et al.}~\cite{chen2018Person} propose a mask-guided feature learning method to make the reID network focus more on foregrounds. Lan \textit{et al.}~\cite{xu2018Person} propose CLSA which utilizes multi-level features from reID network to solve the multi-scale matching problem. Han \textit{et al.}~\cite{han2019Re} claim that bounding box from detector might not be optimal for re-identification, they thus refine the detector results driven by re-identification loss. Our work belongs to the first category of person search, integrating detection and reID into a unified framework. Different from existing person search works, this work further addresses the misalignment issue of detected bounding boxes and optimizes aligned part feature learning to achieve robust partial matching in person search.\vspace{-0.2cm} \begin{figure*}[t] \centering \begin{center} \includegraphics[width=0.96\textwidth]{ADNet}\\ \end{center} \caption{Architecture of the proposed Align-to-Part Network (APNet), which consists of person detector, Bounding Box Aligner (BBA), and Region Sensitive Feature Extractor (RSFE). The detection branch returns bounding boxes $\mathcal{B}$ and global feature $F$. BBA refines detected boxes $\mathcal{B}$ to aligned ones, \emph{i.e.}, $\hat{\mathcal{B}}$. Red and green bounding boxes denotes detected boxes $\mathcal{B}$ and refined boxes $\hat{\mathcal{B}}$, respectively. RSFE extracts part features $\{f^{(k)}\}_{k=1:K}$ from refined boxes and alleviates negative effects of adjacent noises. RAP and GAP denote Regional Average Pooling and Global Average Pooling, respectively. $F_{\operatorname{RSM}}$ is the global feature from Region Sensitive Map, which is only used for training RSFE. } \label{fig:adnet} \vspace{-0.2cm} \end{figure*} \section{Problem Formulation}\label{sec:formulation} Given a query person image $q$ and a gallery set $\mathcal G = \{g_i\}_{i=1:N}$ containing $N$ frames, person search aims at detecting a collection of person bounding boxes $\mathcal B = \{b_i\}_{i=1:M}$ from $\mathcal G$, then matching $q$ against the bounding boxes in $\mathcal B$. Suppose a person can be divided into $K$ body parts, we could represent the bounding box $b_i$ containing a complete person as a collection of $K$ parts,\emph{ i.e.}, $\mathcal P_i= \{p_i^{(k)}\}_{k=1:K}$, where $p_i^{(k)}$ denotes the $k$-th part. With the above formulation, person detection is expected to return bounding boxes containing complete persons with $K$ parts. Person reID targets to extract a discriminative feature to identify the same identity of $q$ in $\mathcal B$. Most of existing works extract a global feature $F$ and performs reID by L2-distance. Due to the occlusions or background clutters, certain bounding boxes only contain portions of body parts, making the global feature degrades to a partial feature, \emph{i.e.}, the global feature is extracted from $l, l<K$ visible parts. Such partial features lead to inaccurate person matching when compared with global features. Our solution is to introduce a part identifier $\operatorname E(\cdot)$ to identify visible parts in each detected bounding box, \emph{i.e.}, $\mathcal P_i = \operatorname E(b_i)$. With identified parts, the person image matching could be treated as a part feature matching task, where features on mutual visible parts of two bounding boxes are matched. The distance between $q$ and $b_i$ can be denoted as, \emph{i.e.}, \begin{equation}\label{eq:robust} \operatorname{dist}_P(q, b_i)=\frac{\sum\limits_{k\in \mathcal P_q\cap \mathcal P_i}\operatorname D(f_q^{(k)}, f_i^{(k)})}{|\mathcal P_q\cap \mathcal P_i|}, \end{equation} where $f_q^{(k)}$ and $f_i^{(k)}$ are features extracted from $k$-th part from $q$ and $b_i$, and $\operatorname D(\cdot)$ refers the L2-distance. The training of our person search model should guarantee an accurate person detector, the reliable part identifier, and discriminative part features. We formulate our training objective as, \begin{equation}\label{eq:loss} \mathcal L= \mathcal L_D + \mathcal L_P + \sum\limits_{k=1}^{K} \mathcal L_{f^{(k)}}, \end{equation} where $\mathcal L_D$ denotes loss of the detector, which is optimized with both bounding box locations and person reID. $\mathcal L_P$ denotes the loss of part identification. $\mathcal L_f^{(k)}$ evaluates the discriminative power of the $k$-th part feature, which can be implemented with reID loss. The following section presents details of our implementation to person detector, part identifier, part feature extraction, as well as the network optimization. \section{Proposed Methods} We propose the Align-to-Part Network (APNet) to implement the formulation in Sec.~\ref{sec:formulation}. The architecture of APNet is shown in Fig.~\ref{fig:adnet}. APNet consists of a person detector, Bounding Box Aligner (BBA), and the Region Sensitive Feature Extractor (RSFE), respectively. The following parts present details of those components. The detector is built upon OIM~\cite{tong2017Joint}, which is an end-to-end person detector returning bounding boxes $\mathcal {B}$ as well as their corresponding global feature $F$. As shown in Fig.~\ref{fig:adnet}, the detector is trained with RPN loss ($\mathcal{L}_{\operatorname{rpncls}}$, $\mathcal{L}_{\operatorname{rpnreg}}$)~\cite{ren2015faster}, ROI Head loss ($\mathcal{L}_{\operatorname{cls}}$, $\mathcal{L}_{\operatorname{reg}}$), as well as reID loss. We denote the detector training loss as \begin{equation}\label{eq:oimloss} \mathcal L_D= \mathcal{L}_{\operatorname{cls}}+\mathcal{L}_{\operatorname{reg}}+\mathcal{L}_{\operatorname{rpncls}}+\mathcal{L}_{\operatorname{rpnreg}}+\mathcal{L}_{\operatorname{ID}}, \end{equation} where $\mathcal{L}_{\operatorname{cls}}$ and $\mathcal{L}_{\operatorname{reg}}$ denotes the person classification loss and bounding box regression loss in ROI Head. $\mathcal{L}_{\operatorname{rpncls}}$ and $\mathcal{L}_{\operatorname{rpnreg}}$ denote the objectiveness loss and proposal regression loss in RPN. $\mathcal{L}_{\operatorname{ID}}$ is the reID loss computed on the global feature. We refer readers to OIM~\cite{tong2017Joint} for more details of the loss computation. As shown in Fig.~\ref{fig:motivation}, a well trained detector may produce misaligned person bounding boxes. We hence design a part estimator with BBA to estimate visible body parts of each detected box. \begin{figure}[t] \begin{center} \centering \includegraphics[width=0.9\linewidth]{bve}\\ \end{center} \caption{Illustration of BBA for bounding box refinement. Red and green boxes refer to detected boxes and refined boxes, respectively. BBA predicts four bounding box offset values $o_t$, $o_b$, $o_l$, and $o_r$, which shift the detected bounding boxes to cover the estimated holistic body region. 0, 1 indicate the validity of each part. } \label{fig:bve} \vspace{-0.2cm} \end{figure} \subsection{Bounding Box Aligner}\label{sec:bba} BBA implements part identifier $\operatorname E(\cdot)$ in Sec.~\ref{sec:formulation} to identify visible parts in each bounding box. This could be achieved with various methods, \emph{e.g.}, through segmenting person foregrounds~\cite{liFully} or estimating body keypoints~\cite{fang2017rmpe}. However, those methods require extra annotations and considerable computations. We implement BBA with a more efficient solution. Because most pedestrians show upright posture in surveillance videos, aligned body parts can be extracted by dividing a holistic body region into horizontal and vertical stripes. This operation generates aligned part regions, \emph{e.g.}, top and bottom horizontal stripes correspond to head and foot, respectively. With this intuition, BBA first refines detected bounding boxes, then extracts horizontal and vertical stripes as body parts. We illustrate this procedure in Fig.~\ref{fig:bve}. BBA estimates an offset vector $O=\{o_t, o_b, o_l, o_r\}$ to refine each detected bounding box to cover the holistic body region, where each offset value is in the range of $[-1, 1]$. The four offset values move the top, bottom, left, and right boundaries of each bounding box. Fig.~\ref{fig:bve} shows examples of moving the boundaries by $o_t$ and $o_b$. Suppose the coordinate of a bounding box $b$ is $\{x_{min}, y_{min}, x_{max}, y_{max}\}$, its coordinate after refinement with $O$ can be denoted as $\{\hat{x}_{min}, \hat{y}_{min}, \hat{x}_{max}, \hat{y}_{max}\}$, \emph{e.g.}, \begin{equation}\label{eq:bve} \begin{split} \hat{y}_{min} = y_{min}-\frac{h\cdot o_t}{1-o_t-o_b}\\ \hat{y}_{max} = y_{max}+\frac{h\cdot o_b}{1-o_t-o_b}, \end{split} \end{equation} where $h$ is the height of detected bounding box, computed as $y_{max}-y_{min}$. Similar computation can be applied to compute the $\hat{x}_{min}$ and $\hat{x}_{max}$ with $o_l$ and $o_r$. We denote the refined bounding box as $\hat b$, which is used to extracted horizontal and vertical stripes as parts. As shown in Fig.~\ref{fig:bve}, refinements may introduce occluded parts and noises into $\hat b$. To extract $K$ horizontal stripes, we introduce a $K$-dim validity vector $v$ to record the visibility of each stripe. The $k$-th stripe is considered as valid, \emph{i.e.}, $v[k]=1$, if \begin{equation}\label{eq:bve_identifier} \lceil K\cdot \max(0,o_t) \rceil \leq k \leq K-\lfloor K\cdot \max(0,o_b) \rfloor\\. \end{equation} Similar computation is applied to extract valid vertical stripes. The final valid part collection $\mathcal{P}$ of each bounding box collects valid stripes. As shown in Fig.~\ref{fig:adnet}, BBA predicts $O$ based on the bounding box feature extracted with ROIAlign. BBA can be trained by automatically generating training data. We first crop bounding boxes from frames by their groundtruth coordinates, which we denote as $\mathcal{B}_{gt}$. AlphaPose~\cite{fang2017rmpe} is utilized to estimate the keypoints of each bounding box, which provide cues about missing body parts. We then transform $\mathcal{B}_{gt}$ to $\hat{\mathcal{B}}_{gt}$ to cover the holistic body region. Comparing $\mathcal{B}_{gt}$ and $\hat{\mathcal{B}}_{gt}$ generates the groundtruth offset labels $O_{gt}=\{o_{gt-t}, o_{gt-b}, o_{gt-l}, o_{gt-r}\}$. The training of BBA can thus be supervised by following loss \begin{equation}\label{eq:bve_train} \mathcal{L}_{P}=\sum\limits_{i\in\{t,b,l,r\}}\operatorname {smooth}_{l1}(o_i, o_{gt-i}), \end{equation} where $\operatorname {smooth}_{l1}$ computes differences between predicted offset values and the groundtruth values. More details of $\operatorname {smooth}_{l1}$ can be found in ~\cite{ren2015faster}. \subsection{Region Sensitive Feature Extractor}\label{sec:rse} The part collection $\mathcal{P}$ makes it possible to extract part features for partial matching. The following section shows our method to extract horizontal stripe features. Vertical stripe features can be extracted with similar way. \textbf{Vanilla Part Feature Extractor:} Part features can be extracted by applying Region Average Pooling (RAP) on the feature map of video frame. As shown in Fig.~\ref{fig:adnet}, for a refined bounding box $\hat{b_i}$, we first extract its feature map from the frame feature map $\mathcal M$ with ROIAlign, which is then input into a convolutional block to generate a feature map $T\in \mathbb{R}^{H\times W\times D}$. We denote part features of $\hat {b_i}$ extracted by RAP as, \begin{equation}\label{eq:bce_pcb_van} \{\bar f_i^{(k)}\}_{k=1:l}=\operatorname{RAP}(T, \mathcal P_i), l=|\mathcal P_i|, \end{equation} where $l$ denotes the number of valid horizontal stripes of bounding box $\hat{b_i}$. Part feature learning can be achieved by computing the reID loss on each valid part feature, \emph{i.e.}, \begin{equation}\label{eq:bba_rap} \mathcal{L}_{f}^{(k)}=\mathcal{L}_{\operatorname{ID}}(\bar {f}^{(k)}, y), \end{equation} where $\mathcal{L}_{\operatorname{ID}}$ refers to reID loss which is implemented with OIM loss~\cite{tong2017Joint}. $y$ is the ground truth person ID label. Fig.~\ref{fig:psmap_vis} (b) shows feature maps of aligned bounding boxes trained by the above feature extractor. It is clear that, noisy or invisible regions still have strong responses. This could be because the training procedure in Eq.~\eqref{eq:bba_rap} focuses on visible body parts, and can not tune the features on noisy parts. Because of enlarged receptive fields of neurons in feature extraction CNN layer, the strong CNN activations on noisy or occluded parts would affect features of their adjacent valid parts. This may degrades the validity of the above feature extractors. Therefore, part feature extractors robust to occlusions and noises are required. \begin{figure}[t] \begin{center} \centering \includegraphics[width=0.45\textwidth]{psmap_vis} \end{center} \caption{Illustration of detected boxes (red) and refined boxes (green), as well as their feature maps. (b) and (c) show feature maps of refined boxes trained with vanilla part feature extractor and our RSFE. It is clear that, RSFE depresses noises on noisy and invalid regions.} \label{fig:psmap_vis} \vspace{-0.4cm} \end{figure} \textbf{Feature Extraction with Region Sensitive Map:} Our RSFE introduces a Region Sensitive Map (RSM) to suppress responses of invalid regions. To tune the responses of each feature stripe, we generate the RSM $M\in \mathbb{R}^{H\times W\times d} $ by applying 1 $\times$ 1 convolution on each horizontal feature stripe $T[i]\in\mathbb{R}^{W\times D}, i=1:H$. The computation of $M[i]\in\mathbb{R}^{W\times d}$ can be denoted as, \begin{equation}\label{eq:bce_rsm} M[i]= \operatorname{conv^{(i)}_{1\times 1}}(T[i]), i=1:H, \end{equation} where $\operatorname{conv^{(i)}_{1\times 1}}$ refers to the $i$-th convolution kernel. Different from a global $1\times 1 $ convolution, $H$ convolutional kernels in Eq.~\eqref{eq:bce_rsm} do not share parameters to deal with complicated occlusions on different spatial locations. To suppress noisy regions, we supervise ${M}$ with a global feature. The loss can be computed by applying Average Pooling on $M$ and supervise the resulted feature $F_{\operatorname{RSM}}$, \emph{i.e.}, \begin{equation}\label{eq:bce_rsm_sup} \mathcal{L}_{\operatorname{RSM}}=\mathcal{L}_{\operatorname{ID}}(F_{\operatorname{RSM}}, y). \end{equation} This loss enforces the network to depress activations on noisy regions to generate a better $F_{\operatorname{RSM}}$, which is then used for stripe feature extraction. Fig.~\ref{fig:psmap_vis} (c) shows feature maps after training with Eq.~\eqref{eq:bce_rsm_sup}, where invalid regions are effectively suppressed. From $M$, the stripe features can be extracted by RAP as, \begin{equation}\label{eq:bce_rsm_rap} \{f_i^{(k)}\}_{k=1:l}=\operatorname{RAP}(M,\mathcal{P}_i), l=|\mathcal P_i|, \end{equation} where each part feature can be trained with part feature loss in Eq.~\eqref{eq:bce_pcb_van}. Eq.~\eqref{eq:bce_rsm} applies different $1\times1$ convolution kernels on spatial locations of $T$. This enables more specific refinements for each part feature. Besides that, different spatial locations show varied probabilities of occlusion, \emph{e.g.}, the foot area is more likely to be occluded. This property makes Eq.~\eqref{eq:bce_rsm} more effective in depressing occlusions and noises than learning a global $1\times1$ convolution kernel. The methods above extracts features from horizontal stripes. Similar procedure can be applied to extract features from vertical stripes. Given a query person image $q$ and a detected gallery bounding boxes $b_i$ to be compared, we utilize both global and part features for person reID. The part feature distance can be computed with Eq.~\eqref{eq:robust}. We also utilize the global feature $F$ from detector branch for distance computation. The overall distance between $q$ and $b_i$ can be computed as: \begin{equation}\label{eq:global_feature} \operatorname{dist}(q, b_i) = \operatorname{dist}_P(q, b_i) + \lambda \cdot\operatorname{D}(F_q, F_i), \end{equation} where $F_q$ and $F_i$ correspond to the global features of $q$ and $b_i$ respectively. We set $\lambda$ to 1 in the following experiments. \section{LSPS Dataset} \subsection{Previous Datasets} \textbf{CUHK-SYSU}~\cite{tong2017Joint} consists of 5,694 frames captured from movie snapshots, and 12,490 frames from street snap. Both bounding boxes and identities are labeled manually. The dataset provides 8,432 labeled identities, and 23,430 labeled bounding boxes. 96,143 bounding boxes are provided in total. 11,206 frames with 5,532 identities make up the training set. CUHK-SYSU does not annotate bounding boxes with partial bodies. \textbf{PRW}~\cite{zheng2017Person} is captured with six cameras deployed at a campus, containing 11,816 frames with 932 identities in total. 5,134 frames are selected as training set with 432 identities, while the rest 6,112 frames make up the test set. A total of 34,304 bounding boxes are annotated with identity. Similar to CUHK-SYSU, bounding box locations in PRW are also manually labeled. PRW includes some misaligned bounding boxes in both queries and galleries. \begin{table} \begin{center} \resizebox{0.99\linewidth}{!}{ \small \begin{tabular}{p{1.8cm}|p{1.8cm}<{\centering}|p{1.5cm}<{\centering}|p{1.5cm}<{\centering}} \hline Dataset& LSPS & PRW~\cite{zheng2017Person}& CUHK~\cite{tong2017Joint} \\ \hline frames& 51,836& 11,816& 18,184 \\ identities & 4,067& 932& 8,432 \\ anno. boxes& 60,433& 34,304& 23,430 \\ cameras& 17& 6& - \\ detector & Faster-RCNN& Hand& Hand\\ inc.query& $\sim$60\%&$\sim$6\%& $\sim$0\%\\ \hline \end{tabular}} \end{center} \caption{Comparison between LSPS and the other two person search datasets. ``detector'' refers to the way to obtain the ground truth of bounding box location. ``inc.query'' means the percentage of query bounding boxes with partial body.} \label{statistics} \vspace{-0.3cm} \end{table} \subsection{Description to LSPS} This paper contributes a new \textit{Large-Scale dataset for Person Search in the wild} (LSPS), which shows the following characteristics: \textit{Complex scene and appearance variations:} The video frames are collected from 17 cameras, deployed at both indoor and outdoor scenes. Different cameras exhibit different backgrounds, viewpoints, view fields, illuminations, pedestrian densities, \emph{etc}. Those factors lead to substantial appearance variances for the same person. Meanwhile, due to limited view fields of each camera and high person density, lots of pedestrians are occluded, leading to bounding boxed covering partial body region. LSPS includes partial bounding boxes into both query and gallery sets. Fig.~\ref{fig:rwpid} (a) compares the body completeness in queries between LSPS and PRW. It is clear that, LSPS has a substantially larger number of incomplete query bounding boxes. Compared with existing person search datasets, LSPS presents more complex scenes and appearance variations. \textit{Larger scale:} Different with previous benchmarks, where bounding boxes are manually labeled. LSPS utilizes bounding boxes detected by Faster-RCNN~\cite{ren2015faster}, based on which we manage to collect a dataset with larger number of bounding boxes. We show the comparison between LSPS and the other two datasets in Table~\ref{statistics}. In LSPS, a total number of 51,836 frames are collected, from which 60,433 bounding boxes and 4,067 identities are annotated. Table~\ref{statistics} shows that, LSPS presents the larger number of frames, annotated person bounding boxes, cameras, respectively. Moreover, about 60\% queries in LSPS cover partial body. Larger scale and incomplete query bounding boxes make LSPS a more challenging and realistic dataset than the others in Table~\ref{statistics}. \begin{figure}[t] \begin{center} \includegraphics[width=0.45\textwidth]{rwpid} \end{center}\caption{(a) compares the body completeness in queries between LSPS and PRW. (b) illustrates several query and gallery bounding boxes. It can be observed that, misalignment occurs in both query and gallery bounding boxes.} \label{fig:rwpid} \end{figure} \subsection{Evaluation Protocol} LSPS is splitted into a training set with 18,154 frames and a test set with 33,673 frames. The training and test set contain 1,041 and 3,026 identities, respectively. Statistics of the training and test set are summarized in Table~\ref{statistics_traintest}. We utilize mean Average Precision (mAP) and rank-1 accuracy as evaluation metrics, which are widely adopted in person reID ~\cite{tong2017Joint,munjal2019Query,chen2018Person,xu2018Person,han2019Re}. In person search, a retrieved bounding box is considered as true positive if it shares the same ID label with query and it has the overlap rate larger than 0.5 with the ground truth bounding box. Therefore, both mAP and rank-1 accuracy in person search are affected by the detector performance. \begin{table}[t] \begin{center} \small \begin{tabular}{p{1.cm}|p{1cm}<{\centering}|p{1.3cm}<{\centering}| p{1.1cm}<{\centering}|p{1.6cm}<{\centering}} \hline Split& frames & identities& boxes& anno. boxes\\ \hline Training& 18,163& 1,041& 71,563& 18,928 \\ Test& 33,673& 3,026& 116,170& 41,505 \\ \hline \end{tabular} \end{center} \caption{Statistics of training/test sets on LSPS. ``anno. boxes'' refers bounding boxes annotated with person ID. ``boxes'' denotes the number of provided bounding boxes.} \label{statistics_traintest} \vspace{-0.32cm} \end{table} \section{Experiment} The following parts conduct experiments on CUHK-SYSU~\cite{tong2017Joint}, PRW~\cite{zheng2017Person} and the new LSPS. \subsection{Implementation Details} Our APNet is implemented based on OIM~\cite{tong2017Joint}. We use the ResNet50~\cite{he2016deep} initialized with ImageNet pretrained model as the backbone. The backbone adopts similar setting with the one in~\cite{munjal2019Query} and it uses RoIAlign~\cite{he2017Mask} rather than RoIPooling~\cite{ren2015faster}. For all experiments, we train the APNet with SGD optimizer. We divide the training into two stages, \textit{i.e.}, the first stage trains the detector branch with $\mathcal{L}_D$. The second stage fixes parameters of the detector and trains BBA and RSFE with $\mathcal{L}_P$ and $\mathcal{L}_f$, respectively. We set $K$ to 7 for horizontal stripes. For PRW and CUHK-SYSU, we do not use features from vertical stripes since the misalignment in these two datasets mainly occurs in vertical direction. On CUHK-SYSU, the first stage lasts 40k iterations. We set the initial learning rate to 1e-3 and decay it by 0.1 at 30k. RSFE is trained for 40k with learning rate as 1e-3, decayed at 30k. On PRW, the first stage lasts 80k. We set learning rate to 1e-4, decayed at 60k. RSFE is trained for 40k with learning rate as 1e-3, decayed at 30k. On LSPS, the first stage lasts 120k, with learning rate as 1e-4 and is decayed by 0.1 at 80k and 100k, respectively. RSFE is trained for 60k with learning rate as 1e-3, decayed at 30k and 50k, respectively. BBA on three datases are trained for 30k with learning rate as 1e-3, and is decayed at 20k. \subsection{Ablation Study} \begin{table}[t] \begin{center} \resizebox{.9\linewidth}{!}{ \tiny \begin{tabular}{p{1cm}<{\centering}|p{1.8cm}<{\centering}|p{1.8cm}<{\centering}|p{1.8cm}<{\centering}} \hline \multicolumn{2}{c|}{\multirow{1}*{Methods}} & \multicolumn{1}{c|}{\multirow{2}*{mAP}} & \multicolumn{1}{c}{\multirow{2}*{rank-1}}\\ \cline {1-2} \multicolumn{1}{l|}{}&\multicolumn{1}{l|}{feature}&\multicolumn{1}{l|}{}&\multicolumn{1}{l}{}\\ \cline{1-4} \multicolumn{1}{l|}{\multirow{1}*{upper bound}}& \multicolumn{1}{l|}{global} & \multicolumn{1}{c|}{53.5}& \multicolumn{1}{c}{74.6}\\ \cline{1-4} \multicolumn{1}{l|}{\multirow{1}*{global}}& \multicolumn{1}{l|}{global} & \multicolumn{1}{c|}{13.6}& \multicolumn{1}{c}{30.4}\\ \cline {2-2} \multicolumn{1}{l|}{\multirow{1}*{matching}}& \multicolumn{1}{l|}{stripe} & \multicolumn{1}{c|}{23.1}& \multicolumn{1}{c}{52.5}\\ \cline {1-4} \multicolumn{1}{l|}{\multirow{1}*{partial}}& \multicolumn{1}{l|}{{valid region}} & \multicolumn{1}{c|}{23.9}& \multicolumn{1}{c}{46.7}\\ \cline {2-2} \multicolumn{1}{l|}{\multirow{1}*{matching}}& \multicolumn{1}{l|}{\textit{mutual} region} & \multicolumn{1}{c|}{21.4}& \multicolumn{1}{c}{48.6}\\ \cline {2-2} \multicolumn{1}{c|}{}& \multicolumn{1}{l|}{\textit{mutual} stripe} & \multicolumn{1}{c|}{\textbf{30.9}}& \multicolumn{1}{c}{\textbf{70.0}}\\ \hline \end{tabular}} \end{center} \caption{Validity of partial matching on Market1501 modified by adding artificial occlusions. ``upper bound'' refers to performance of global feature on original Market-1501. Other methods are tested on modified Market-1501. Valid region refers to common visible region of tow matched bounding boxes.} \label{exp:abla_global} \vspace{-0.2cm} \end{table} \textbf{Validity of Partial Matching.} APNet addresses misalignment issue with partial matching based on stripe features. This part demonstrates the validity of this strategy. We first modify the Market-1501~\cite{zheng2015scalable} by adding random occlusions to query and gallery images. Based on this modified dataset, we compare different feature matching strategies and summarize the results in Table~\ref{exp:abla_global}, where ``global matching'' does not differentiate occlusions in feature extraction and ``partial matching'' extracts features from valid regions. Table~\ref{exp:abla_global} shows that, occlusion is harmful for reID, \emph{e.g.}, degrades the mAP of global feature from 53.5\% to 13.6\%. Extracting stripe features from the entire bounding box boosts the reID performance. This shows the validity of part feature. Because partial matching extracts features from visible regions, it achieves better performance than global matching. Among three features used in partial matching, features extracted from mutual stripes achieve the best performance. It outperforms the feature from mutual region by large margins, \emph{e.g.}, 30.9\% vs. 21.4\% in mAP. It also significantly outperforms the global feature in global matching. The above experiments hence shows the validity of the idea illustrated in Fig.~\ref{fig:motivation}, where features on the mutual visible regions are matched for similarity computation. \begin{table}[t] \centering \begin{center} \setlength{\tabcolsep}{0.3cm} \resizebox{1.\linewidth}{!}{ \normalsize \begin{tabular}{p{2.2cm}|p{1.2cm}<{\centering}|p{1.35cm}<{\centering}|p{1.2cm}<{\centering}|p{1.35cm}<{\centering}} \hline \multicolumn{1}{l|}{\multirow{2}*{Features}} & \multicolumn{2}{c|}{PRW} & \multicolumn{2}{c}{LSPS}\\ \cline {2-5} \multicolumn{1}{c|}{}& mAP & rank-1 & mAP & rank-1\\ \hline global& 34.2 & 75.8 & 14.4 & 47.7 \\ stripe& 39.1& 79.1 & 13.0& 41.6\\ VPM~\cite{sun2019Perceive} & 40.0& 80.2& 16.0& 49.5\\ stripe (BBA) & 40.8& 81.0& 16.4& 50.2\\ RSFE (BBA)& \textbf{41.9}& \textbf{81.4}& \textbf{17.1}& \textbf{51.6}\\ \hline \end{tabular}} \end{center} \caption{Validity of BBA and RSFE in stripe feature extraction. Global refers to global feature extracted from detected bounding box. ``stripe (BBA)'' denotes extracting stripe features with vanilla part feature extractor based on BBA output. ``RSFE (BBA)'' denotes stripe feature extracted by RSFE.}\label{exp:abla} \vspace{-0.2cm} \end{table} \begin{figure}[t] \begin{center} \centering \includegraphics[width=0.45\textwidth]{nstripe} \end{center} \caption{Performance on LSPS with different stripe number $K$. } \label{fig:nstripe} \vspace{-0.2cm} \end{figure} \textbf{Validity of BBA:} BBA performs bounding box refinement and valid part estimation. We proceed to verify the validity of BBA in person search. Table~\ref{exp:abla} shows the performance of global feature and stripe feature before applying BBA. It is clear that, extracting valid stripe features from BBA refined bounding boxes, substantially boosts the reID performance. For instance, ``stripe (BBA)'' achieves mAP of 40.8\% on PRW, better than the 34.2\% and 39.1\% of original global feature and stripe feature, respectively. We also show performance of the reproduced VPM~\cite{sun2019Perceive}, which is a recent method for partial matching. As shown in Table~\ref{exp:abla}, stripe feature extracted with BBA performs better than VPM on both PRW and LSPS. This experiment hence shows the validity of BBA in bounding box refinement and valid part extraction. \textbf{Validity of RSFE:} RSFE is designed to alleviate the negative effects of noisy regions illustrated in Fig.~\ref{fig:psmap_vis} (b). It is also designed to refine each part feature. Table~\ref{exp:abla} compares the stripe feature extracted by RSFE, \emph{i.e.}, ``RSFE (BBA)'' against the one extracted by vanilla part feature extractor, i.e., ``stripe (BBA)''. It can be observed that, RSFE is important in boosting the stripe feature performance. For example, RSFE boosts the mAP by 1.1\% and 0.7\% on PRW and LSPS, respectively. The combination of BBA and RSFE achieves the best performance and outperforms the VPM by large margins. More comparisons with person search works will be presented in the next section. \textbf{Effects of part number $K$:} We proceed to study the influence of part number $K$, and summarize the results in Fig.~\ref{fig:nstripe}. $K=1$ degrades the partial feature to global feature. The maximum horizontal stripe number $K$ equals to the height of $T$, \emph{i.e.}, 7 in our experiment. The figure shows that, stripes with finer scale help to boost the performance. This might due to the fact that larger $K$ improves the feature resolution and robustness to occlusions and noises. \begin{figure}[t] \begin{center} \centering \includegraphics[width=0.45\textwidth]{padreg_vis} \end{center} \caption{Visualization of refined bounding boxes by BBA. Red and green boxes denote bounding boxes before and after refinement. BBA effectively estimates the holistic body region to eliminate misalignment errors. } \label{fig:padreg_vis} \end{figure} \textbf{Discussions:}. To show the effects of BBA in bounding boxes refinement, we visualize bounding boxes before and after refinement in Fig.~\ref{fig:padreg_vis}. The results show that, BBA effectively shifts the original bounding boxes to cover holistic body regions. This procedure eliminates misalignment errors and guarantees aligned stripe feature extraction. Besides the detector branch based on baseline OIM, APNet introduces additional BBA and RSFE modules. We compare the parameter and computational complexity between OIM and APNet in Table~\ref{exp:overhead}. The comparison shows that APNet achieves promising performance with comparable speed with baseline OIM, \emph{e.g.}, 0.397 TFLOPs of APNet vs. 0.383 TFOLPs of OIM. Although the BBA and RSFE modules bring more parameters to APNet, they do not degrade its computational speed substantially. APNet is likely to be faster than person search works that treat detection and reID in separated steps, and is faster than some works like QEEPS~\cite{munjal2019Query}, which compares each query-gallery pair for person search. \begin{table}[t] \begin{center} \small \resizebox{0.99\linewidth}{!}{ \begin{tabular}{p{1.8cm}|p{2cm}<{\centering} |p{2.cm}<{\centering}| p{1.2cm}<{\centering}} \hline Methods& \# params (\textit{M}) & speed (sec.)& TFLOPs \\ \hline OIM& 36& 0.254& 0.383\\ APNet& 67& 0.256& 0.397 \\ \hline \end{tabular}} \end{center} \caption{Comparison of parameter and computational complexity between APNet and baseline OIM~\cite{tong2017Joint}. Speed and TFLOPS are measured on the NVIDIA 2080Ti GPU. } \label{exp:overhead} \end{table} \subsection{Comparison with recent works} \begin{table}[t] \centering \begin{center} \Large \setlength{\tabcolsep}{0.3cm} \resizebox{0.99\linewidth}{!}{ \begin{tabular}{p{2.1cm}|p{1.7cm}<{\centering}|p{1.5cm}<{\centering}|p{1.5cm}<{\centering}|p{1.5cm}<{\centering}|p{1.5cm}<{\centering}} \hline \multicolumn{1}{c|}{\multirow{2}*{Methods}} & \multicolumn{1}{c|}{\multirow{2}*{Reference}}& \multicolumn{2}{c|}{\bfseries{CUHK-SYSU}} & \multicolumn{2}{c}{\bfseries{PRW}} \\ \cline {3-6} \multicolumn{1}{c|}{}& \multicolumn{1}{c|}{}& mAP & rank-1 & mAP & rank-1 \\ \hline OIM~\cite{tong2017Joint}& CVPR2017 & 75.5& 78.7& 21.3& 49.9\\ NPSM~\cite{hao2017Neural}& ICCV2017 & 77.9& 81.2& 24.2& 53.1\\ CLSA~\cite{xu2018Person}& ECCV2018& 87.2& 88.5& 38.7& 65.0\\ MGTS~\cite{chen2018Person}& ECCV2018& 83.0& 83.7& 32.6& 72.1\\ CGPS~\cite{yichaoLearning}& CVPR2019& 84.1& 86.5& 33.4& 73.6\\ QEEPS~\cite{munjal2019Query}& CVPR2019& 88.9& 89.1& 37.1& 76.7\\ RDLR~\cite{han2019Re}& ICCV2019& \textbf{93.0}& \textbf{94.2}& \textbf{42.9}& 72.1\\ \hline APNet& & 88.9& 89.3& 41.9& \textbf{81.4}\\ \hline \end{tabular}} \end{center} \caption{Comparison with recent works on CUHK-SYSU and PRW, respectively. }\label{sota} \vspace{-0.4cm} \end{table} \textbf{CUHK-SYSU.} We experiment on CUHK-SYSU with gallery size 100. APNet achieves the rank-1 accuracy of 89.3\% and mAP of 88.9\%, outperforming most of recent works. Note that RDLR~\cite{han2019Re} uses a stronger backbone ResNet50-FPN as well as ranking-based loss. Methods like CLSA~\cite{xu2018Person}, MGTS~\cite{chen2018Person}, and RDLR solve detection and reID with two separate models, which are expensive in both computation and storage. Compared with those works, our APNet is a unified model and is likely to present better computational and memory efficiencies. \textbf{PRW.} On PRW, APNet achieves competitive performance, \emph{e.g.}, 81.4\% in rank-1 accuracy and 41.9\% in mAP, outperforming most of recent works. APNet also significantly outperforms the RDLR~\cite{han2019Re} in rank-1 accuracy with a weaker backbone, \emph{i.e.}, by 9.3\% in rank-1 accuracy. Since certain query images in PRW cover partial body parts, APNet exhibits more substantial advantages with partial matching. It also outperforms CGPS~\cite{yichaoLearning} and QEEPS~\cite{munjal2019Query} by 7.8\% and 4.7\% in rank-1, respectively. Note that, CGPS~\cite{yichaoLearning} and QEEPS~\cite{munjal2019Query} input each query-gallery pair into CNN for similarity computation, hence also present inferior retrieval efficiency compared with APNet. \begin{table}[t] \centering \begin{center} \resizebox{0.9\linewidth}{!}{ \Large \begin{tabular}{p{1.4cm}|p{2cm}<{\centering}|p{2.5cm}<{\centering}|p{2cm}<{\centering}|p{2cm}<{\centering}} \hline {\bfseries LSPS}& OIM~\cite{tong2017Joint} &VPM~\cite{sun2019Perceive}& APNet& APNet+v \\ \hline mAP& 14.4& 16.0& 17.1&\textbf{18.8}\\ rank-1& 47.7& 49.5& 51.6&\textbf{55.7}\\ \hline \end{tabular}} \end{center} \caption{Comparisons with recent works on LSPS. APNet denotes our method. APNet+v considers extra vertical stripe features.}\label{sota_rwpid} \vspace{-0.3cm} \end{table} \textbf{LSPS.} We finally present experimental results on LSPS. OIM~\cite{tong2017Joint} is compared as the baseline. APNet brings 3.9\% rank-1 improvement over the baseline, achieving 51.6\% and 17.1\% in rank-1 and mAP, respectively. APNet also outperforms the recent VPM~\cite{sun2019Perceive}, which solves the partial reID problem. To consider the misalignment in horizontal direction, we further apply additional vertical stripe features. The corresponding method, \emph{i.e.}, APNet+v achieves the best performance, achieving 55.7\% and 18.8\% in rank-1 and mAP, respectively. It is also clear that, the performance of APNet on LSPS is substantially lower than the ones on PRW and CUHK-SYSU, indicating the challenges of LSPS. \vspace{-0.5cm} \section{Conclusion} This paper proposes an APNet to solve the bounding box misalignment issues in person search. APNet refines detected boxes to cover the estimated holistic body regions, meanwhile extracting part features from visible body parts. This formulates reID as a partial feature matching procedure, where valid part features are selected for similarity computation, while part features on occluded or noisy regions are discarded. This paper also contributes a LSPS dataset, which is by far the largest and the most challenging dataset for person search. Experiments show that APNet brings considerable performance improvement on LSPS. Moreover, it achieves competitive performance on existing person search benchmarks like CUHK-SYSU and PRW. \noindent \textbf{Acknowledgments} This work is supported in part by The National Key Research and Development Program of China under Grant No. 2018YFE0118400, in part by Beijing Natural Science Foundation under Grant No. JQ18012, in part by Natural Science Foundation of China under Grant No. 61936011, 61425025, 61620106009, 61572050, 91538111. {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2020-04-21T02:28:06', 'yymm': '2004', 'arxiv_id': '2004.09329', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09329'}
arxiv
\subsection{RQ1, RQ2 Best practice adoptation and correlation} \paragraph{RQ3 -- Practice correlation.}\label{sec:dicussion_RQ2}~\cite{pocatilu2002} indicates that ``test automation practices are interdependence and consecutive, as each type of practice may result in intermediate deliveries to be used by others''. By extending his research, we confirmed that all test automation practices are positively correlated in practical context. The description to some test automation practices in his research could explain some clusters of practices in our study : \begin{itemize} \item A cluster of test management related practices (SQ1-Strategy-SQ3-Roles-SQ2-Resources): Test automation strategy defines action steps that will be performed to allocate resources and define roles and responsibility of stakeholders. \item A cluster of technical related practices (SQ6-Tools-SQ12-SUT-SQ14-Testware): the use of suitable test tools may be helpful to create the maintainable testware and test automation testability features into a SUT. \end{itemize} Based on above discussion, we argue that, for practitioners, it is important to pay attention to the ripple effect of different practices, especially for the ones that are strongly correlated and closely clustered. Lack of any necessary practices may harm their test automaton maturity. \paragraph{RQ4 -- Organizational factors.} We found that the high level of test automation maturity achieved in organizational units, which are managed at the organization level with large size, have in-house test team or/and out-source test team, automate the high percentage of test cases, and follow the modern software development model Agile and/or DevOps. Those results suggest that organization factors may affect test automation maturity. Some factors like percentage of automated cases and the adoption of agile and DevOps have been examined by prior research~\citep{garousi2016}. We argue that the rest also should be studied. By identifying them and understanding their impact can help organizations to better use and implement test automation in the organizations. \paragraph{RQ5 -- Response variation.} The results of RQ5 confirmed that the roles of respondents may lead to the response variation in our survey. The previous study~\citep{wang2019} pointed the response variation is likely to introduce the bias to assessment results of test automation maturity. Consequently, we believe that, when assessing test automation maturity of an organization, it is necessary to involve practitioners with different roles to avoid the assessment bias. However, as our survey was anonymous, it is difficult to compare the impact of respondents' roles on the assessment result at a same organization. The further study is needed to validate what impact each type of roles has. \section{Threats to validity} \label{sec:threats} \noindent The threats to this study and approaches taken to minimize their impact were explored, according to a standard checklist in software engineering from \cite{wohlin2012}. \textbf{Construct validity} refers to the extent to which the study present the theory behind it. To ensure the construct validity, we developed our survey according to the prior literature, reviewed it with industry experts, and did the small-scale piloting before actually executing it. The survey was designed and executed by following the standard guidelines in software engineering. \textbf{Conclusion validity} is concerned with the extent to which correct conclusions are made through observations of the study. In this study, all the conclusions to each research question were drawn according to statistical results and are traceable to raw survey data. However, since this survey was anonymous and followed the GDPR, sharing the raw data of survey is not allowed. \textbf{Internal validity} focus on how the study really cause the outcomes. In our study, threats to internal validity lie in the convenience sampling and survey execution. The participants from diverse places are likely to bias the survey results. To avoid that, in the survey design, we studied main types of response bias and took the corresponding steps to control them, e.g., to avoid social desirability bias, the anonymity of the responses and result reporting were maintained. We measured the response quality and removed bad responses before analyzing and reporting survey results. \textbf{External validity} is concerned with how the study results can be generalized. Selection bias may be a threat to external validity of this study. As most responses were received from Europe, population differences should be considered in the generalization of study results to rest of the world. \subsection{Software test automation} \noindent Test automation is an important part of software development process~\citep{pocatilu2002}. It consists of a set of practices conducted in key process areas (KPAs), e.g., test design, test execution, test reporting~\citep{Skoomen2013tmap}. Test automation maturity refers to the level of maturity of a test automation process. Achieving the high level of test automation maturity requires that mature practices are performed in each KPA~\citep{Mitchel1994}. Several examples of the negative effects of immature practices have been reported in the literature. Selecting the wrong test tools for the problems at hand may impact the organizational performance~\citep{garousi2017software}. Automating test cases better suited for manual testing may waste time and money~\citep{garousi2017software}. Defining inappropriate metrics is likely to guide your test automation in the wrong direction~\citep{walia2017}. In prior research, ~\cite{wang2019} studied 25 sources (including 18 test maturity models, 3 journal papers, and 4 recent software testing related technical reports) that covering test automation maturity topics. Referring to their research results, based on those 25 sources, an organization should focus on 13 KPAs to conduct test automation practices. The mature practices must be performed in each KPA were synthesized, see Table~\ref{tab:KPAsofTA}. Those mature practices have been proven to be valid in the present industry by test automation experts from both academia and industry. \begin{table}[ht] \small \caption{Best practices in KPAs~\citep{wang2019}} \footnotesize \label{tab:KPAsofTA} \begin{tabular}{ l p{1.99cm} p{3.5cm} } \toprule & KPA & Mature practice\\ \midrule K01 & Test automation strategy & Set explicit strategic plans for test automation \\ \hline K02 & Resources & Provide enough resources (e.g., skilled people, costs, efforts) for test automation.\\\hline K03 & Test \newline organization & Assemble and collaborate skilled test staffs perform test automation practices.\\\hline K04 & Knowledge \newline transfer & Collect and share test automaton related knowledge\\ \hline K05 & Test tools & Use right test tools to support testing activities.\\\hline K06 & Test \newline environment & Set up test environment with required software, hardware, test data, etc., to execute automated tests\\\hline K07 &Test \newline requirements & Derive explicit test automation requirements. \\\hline K08 & Test design & Use the specific test design techniques to create maintainable test cases for test automation.\\\hline K09 &Test execution & Prioritize and execute automated test cases\\\hline K10 &Verdicts & Collect and report useful results of executing automated test cases.\\\hline K11 &Test automation \newline process & Define the specific procedures to conduct test automation. \\\hline K12 &Measurements & Use right metrics to measure the quality and performance of test automaton.\\ \hline K13 & Software Under Test (SUT) & Prepare the testable SUT to be automatically tested. \\ \bottomrule \end{tabular} \end{table} \section{\uppercase{Introduction} \footnotetext{This is the author's version of the work. It is posted here for your personal use. The definitive version was published in Proceedings of the 15th International Conference on Software Technologies (ICSOFT 2020)}} \label{sec:introduction} \input{introduction_SEC.tex} \section{\uppercase{Related work}} \label{sec:related_work} \input{relatedWork_SEC.tex} \section{\uppercase{Research method}} \label{sec:research_method} \input{researchMethod_SEC.tex} \section{Results} \label{sec:results} \input{results_SEC.tex} \section{Discussion} \label{sec:discussion} \input{discussion_SEC.tex} \section{Conclusion} \label{sec:conclusion} \input{conclusion_SEC.tex} \section*{\uppercase{Acknowledgements}} \noindent This study is supported by TESTOMAT Project (ITEA3 ID number 16032), funded by Business Finland under Grant Decision ID 3192/31/2017. \bibliographystyle{apalike} {\small
{'timestamp': '2020-04-21T02:25:18', 'yymm': '2004', 'arxiv_id': '2004.09210', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09210'}
arxiv
\section{Introduction} \label{sec:intro} Quality control is a fundamental process in the manufacturing pipeline. Since the '80s, automatizing the quality control task has been offering potentials to overcome limitations of manual inspection \cite{chin1982automated}. As a consequence, successful applications of automatic visual inspection have been emerging year after year, and nowadays inspection systems are being employed in a vast number of industries, from food \cite{wu2013colour} and fabrics \cite{li2016deformable} to railways \cite{shang2018detection} and reconstruction \cite{chen2017self}. In this regard, a standard visual inspection hardware setup is typically composed of a digital camera, optics, and an illumination system. The hardware setup is usually coupled with a customised software that controls the acquisition, evaluates the captured images, and eventually takes decisions based on the evaluated results. Hence, hardware selection is a fundamental task in the design of an automatic visual inspection system and is essentially driven by the characteristics of the object to be inspected \cite{see2017role}. \begin{figure} \centering \includegraphics[width=0.45\textwidth]{fig_setup_defects.png} \caption{The proposed lighting system and four examples of defective images in our dataset as (i) worn-out paint, (ii) dots on the metal surface, (iii) missing decorations, and (iv) unexpected glass break. } \label{fig:defects} \vspace{-1em} \end{figure} For a given manufactured object, countless different models might exist in production having various material properties (specular, diffusive, directional, transparent) or geometrical shape (flat, curved, prismatic). The surface to be inspected might also contain patterns and adornments which should be distinguished from the undesirable irregularities (see Fig. \ref{fig:defects}). We define the object to be inspected, which is the subject of this work, as a \textit{complex-object} if its variable surface characteristics cannot be determined a priori, e.g. it can appear highly reflective and curved in one instance and opaque and prismatic in a different instance. This situation is not uncommon when inspecting assembled and/or decorated products, which can have custom finishing, based on customer requests.\footnote{Due to Non-Disclosure Agreement (NDA) restrictions in place, we cannot reveal the identity of the object inspected in this study.} In this context, \textit{standard illumination techniques} comprising `front lighting', `back lighting', `diffuse lighting', `bright-field lighting' and `dark-field lighting' \cite{van1996choose} individually are not sufficient for this task as each of them is merely suitable for inspection of a few certain surface characteristics. Additionally, the surface attributes are not the only factor driving the choice of the illumination setup. In fact, \cite{martin2007practical} names \textit{immediate inspection environment} one of the three factors for an optimal lighting solution, and introduces object geometry and its support structure as two critical factors for the design of lighting solutions that may even limit the choice of standard illumination techniques. In this work, we aim to propose an illumination system which is capable of dealing with the challenges of automatic visual inspection of the complex-objects, and to define a methodology for analyzing the effect of the proposed illumination system on the final defect detection performance. In particular, we seek to study the impact of the proposed multi-lighting system when deployed in training phase only or in both training and evaluation phases. The first case is specifically relevant in the common situation where deployment of a novel acquisition system cannot be accomplished on the customer site, either due to industrial constraints or technical specifications. To summarize, our contributions are as follows: \begin{itemize} \item We propose an acquisition setup composed of a multi-illumination system (diffused, dark-field and frontal illumination techniques) to guarantee high defect visibility (over 99\%, as reported by the annotators) on a wide selection of instances of the complex-object. \item We conduct exhaustive experiments to demonstrate the importance of the the multi-lighting system, even though merely deployed in training phase. \item We experimentally show that the multi-lighting setup deployment in the evaluation phase, when coupled with late-fusion of detections in each single-lighting conditions, leads to the highest defect detection rate of the system. \end{itemize} \section{Related work} \label{sec:related} The list of successful applications of the visual inspection systems in the case of non-complex objects is long and in many cases the deployment of standard illumination techniques leads to significant improvements. For instance, \cite{chang2016development} addresses \textit{touch panel glass} defect detection using dark-field illumination coupled with image processing techniques achieving $99\%$ accuracy on edge defect type, and an ad-hoc illumination technique such as injecting light beams perpendicularly in the glass achieves $100\%$ performance in scratch defect detection and its discrimination from dust \cite{ozturk2018real}. Inspection of non-regular objects, however, has always been considered a challenging task where a combination of hardware and software techniques was required to achieve the desired outcome. For \textit{silver halide films} inspection, adopting a combination of dark-field illumination brought to the best results in detecting scratch and dust \cite{rufenacht2013automatic}. In certain inspection scenarios, such as small defects in \textit{automotive components}, standard illumination techniques were not found suitable. Thus, to ensure identifying defects when they are undetectable to the naked eyes, \cite{mery2017automatic} proposed to use x-ray imaging and achieved quality performance using SVM-linear classifier. Yet, in a similar case for detecting small defects on \textit{automobile casting aluminum parts}, deployment of x-ray imaging together with the most recent algorithms such as Feature Pyramid Networks leads to $0.51$ mAP in the best case scenario \cite{du2019approaches}. In this paper, firstly we present a custom-designed illumination system comprising several heterogeneous lighting techniques including diffused, dark-field, and front lighting, under various camera exposure values to illuminate numerous defect types on a wide range of surface characteristics that a complex-object might be made of. In addition, we discuss that collecting data under various illumination configurations can be understood as representing an artifact in different modalities, although all the modalities are in practice offered in a single data format as the \textit{RGB image}. As also suggested in \cite{guo2015microscopy}, hereafter we will thus regard images acquired under different illumination configurations as different modalities. Secondly, we provide exhaustive analysis on the potentials of the proposed system to be utilized in either training or evaluation phase. In many cases, the illumination system cannot be arbitrarily chosen or modified due to, for example, out of reach system specifications or cost related issues, especially in customer site (evaluation phase). Hence, we will investigate performance improvement brought by the developed system only in the data collection phase for training of algorithms only in provider site. Further, we experimentally demonstrate that mutual processing of multiple modalities in the form of late-fusion of single detections in each modality leads to considerable improvements in the performance of defect detection algorithms if employed in both training and evaluation phases, thus justifying the suitability of the proposed pipeline. In this regard, the work most similar to ours is the one proposed in \cite{park2016ambiguous}, where to detect and classify defects on a \textit{smartphone surface}, several images are taken with various cameras and light sources to ensure the visibility of defects in at least some of the images. However, differently from our proposal where images are taken with a single camera under varying illumination conditions, in \cite{park2016ambiguous}, as the images are taken with different cameras placed in different locations, the mutual processing of the collected images does not occur. Our motivations for proposing our design are threefold: first, in our proposal, only one camera is embedded, leading to a more cost-effective setup. Second, our proposed setup is designed to have a moderate physical weight enabling it to be carried e.g. with a robotic arm to spin around the complex-object and acquire images at different positions of it. Third, and possibly of more interest to the pattern recognition community, our proposed setup provides multiple instances of the same defective region that we empirically demonstrate to have a large improving impact on defect detection procedure. \section{Acquisition setup} \label{sec:acquisition} \begin{figure} \centering \includegraphics[width=0.5\textwidth]{fig_setup_lights.png} \caption{Illuminators in the proposed acquisition setup are set to activate and deactivate sequentially to resemble diffused, dark-field, and front lighting techniques within four illumination configurations (C, UD, LR, UDLR).} \label{fig:setup_lights} \vspace{-2em} \end{figure} \begin{figure} \centering \includegraphics[width=0.45\textwidth]{fig_modality.png} \caption{Images of a defective object in various illumination conditions. The labeled defect annotation by the annotator is shown with a green bounding-box.} \label{fig:modality} \vspace{-1em} \end{figure} Our proposed lighting setup is composed of five flat-dome lights that alternatively activate and deactivate in different combinations. The light positioning has been empirically studied such to reproduce diffused, dark-field and front lighting techniques, while producing the least possible glares on the specular surfaces. Our proposed setup can be seen in Fig. \ref{fig:setup_lights}. Dome light offers diffused, shadow-less, and uniform illumination even on shiny, curved, and uneven surfaces. In fact, flat-dome lights provide the same characteristics of dome lights, with the additional advantage of occupying less volume, as of the standard LED light. To minimize the reflectivity of the lighting system, which would make it visible when acquiring highly specular surfaces, we covered all the white flat-dome lights with dark collimator filters. We identified four lighting configurations which allow the system to produce front lighting (Fig. \ref{fig:setup_lights}.C) and dark-field lighting in vertical (Fig. \ref{fig:setup_lights}.UD), horizontal (Fig. \ref{fig:setup_lights}.LR) and all lateral (Fig. \ref{fig:setup_lights}.UDLR) directions. Front lighting is mostly suitable for detecting color irregularities or flat defects, while dark-field lighting is extremely useful for acquiring effective images of defects related with surface irregularities such as scratches, bumps, or missing pieces. In addition to the four modalities and to ensure the appropriate illumination level of the acquired images of any surface independently from their reflective characteristics, each light configuration is activated for 3 different time lengths, mimicking 3 different camera shutter speeds (low, medium, high). Camera exposure time is set to be constant and longer than the maximum time of light activation. Trigger controls are configured such that lights and the camera are properly synchronized. In our study, all the images are acquired using a Basler acA2440-75uc camera and an Edmund Optics 16mm F1.4 lens. The camera is placed at the ad-hoc hole presented in the center of the central light. In order to block out all the external environment light, the entire setup and the complex-object to be inspected were placed in a dark black box. \section{Dataset} \label{sec:dataset} Given the described acquisition setup, the system can simultaneously acquire 12 images of the same object varying the illumination conditions (4 modalities, each with 3 exposures). A defect, depending on its type and the characteristics of the surface on which it appears, might be visible in all or only some of the $12$ captured images. For example, as in the case shown in Fig. \ref{fig:modality}, the defect is visible in all the images but images captured with central light with medium and high exposures. Note the significantly different representation each one of the light configurations offers from a single defect. Without predefined instructions on image choice, for each defective object, the annotators label the defect in only one of the images on which they can spot it, as shown by a green bounding-box in Fig. \ref{fig:modality}. Fig. \ref{fig:ann_freq} shows the normalized frequency of annotations for each illumination condition. We expand the single annotation on one image to all the 11 remaining images. If the existing defect on the object is not visible in any of the 12 images captured by the setup, the annotator indicates the non-visibility of the defect in the annotation tool. It is worth mentioning that, the developed setup enabled us to visualize and correctly annotate $99.2\%$ of the defects in a freely selected collection of complex-objects. The collected dataset consists of $5,071$ defective regions of complex-objects, where each region may contain more than one defect. For each region, 12 images with varying illumination conditions are collected, obtaining a total number of $60,852$ images. For our experiments, we split the dataset object-wise in training, validation, and test set with the ratio of 70\%, 15\%, and 15\% respectively. \begin{figure} \centering \includegraphics[width=0.5\textwidth]{fig_ann_freq.png} \caption{Normalized annotations frequency per illumination condition.} \label{fig:ann_freq} \vspace{-1em} \end{figure} \section{Methodology} \label{sec:method} Depending on the defect type and on the surface characteristics, the defect might be better visible in one or more than one image out of the 12 collected using the proposed setting. Given this, is selecting a conventional single illumination technique the most effective choice that the system provider can make? Can the system provider leverage the availability of the multi-modal data in training phase for improving uni-modal testing performance? Can different light conditions be considered as a natural data augmentation technique, or the resulting images are too correlated to actually bring any contribution during the model training? Can inspection scenarios benefit from the multi-modal data availability also in evaluation phase? In the following paragraphs, we explain our proposed methodology for responding to the aforementioned questions. \subsection{Study 1: Training and evaluation on one single modality} \label{subsec:study1} The most common situation when working with visual inspection systems consists of having the same illumination setup available in both training and evaluation phase, therefore it is fundamental to assess the best performing illumination modality. This scenario will be our baseline: only one illumination modality is available for training and evaluation. In this single modality scenario, we are interested in comparing the performances that can be obtained using each of different modalities, for better understanding the characteristics of our dataset and for exploring which light configuration may better help in solving our task. Note that given the single modality scenario, only one quarter of the collected data is used, since the related images to all the other 3 modalities are discarded. Yet, in all the experiments, the selected light configuration includes all of its corresponding images taken under all the 3 exposures, unless stated differently. \subsection{Study 2: Training on multiple modalities, evaluation on a single modality} \label{subsec:study2} As mentioned earlier, in some cases, visual inspection systems cannot be arbitrarily chosen or modified in evaluation phase. In this study, we aim to verify whether deploying a multi-modal inspection system only for acquiring images to be used for model training can lead to improved performances on the unmodified single modality evaluation setup. In order to be comparable with the results of Study 1, we introduce images acquired using different illumination modalities keeping constant the number of images used during training. In other words, also in this experimental setup, only one quarter of the entire dataset is used. In this case, we choose two possible strategies to select dataset images to preserve: \begin{itemize} \item Out of the 12 images available per each defective region, preserving 3 random images each from a different modality under one randomly selected exposure value only; \item Preserving only one quarter of the defective regions in the dataset, but using all of their 12 images acquired with all the light configurations and exposures. \end{itemize} Comparing the performances obtained by training the model on these two datasets will give us an insight on the comparative effectiveness of having either more defective objects or more modalities during training phase, given any of the single modalities in evaluation phase. \subsection{Study 3: Training on all the images and modalities, test on a single modality} \label{subsec:study3} In Study 2 we discarded three quarter of the collected images for comparing the achieved results with the ones obtained in Study 1. Nevertheless, the proposed acquisition setup enables collecting 12 images per each object with no additional effort required for acquiring or annotating them in comparison to a single modality illumination system. The possibility of having a bigger training set to exploit, would raise expectations for modeling better the task to be solved. However, in complex-object defect detection scenario, it is not given that the additionally collected images, in fact, provide beneficial information for training a more effective model to be used in a single modality scenario. In case they do, it means that the system is able to transfer the information collected from one light modality to a different modality and that the system can better model the detection task even if only provided with modalities during training which are not available during evaluation. In this study, we aim to evaluate this hypothesis. In comparison to Study 1 and Study 2, in Study 3 we are using the entire training set introduced in Sec. \ref{sec:dataset} which is four times bigger, while the test set remains intact. \subsection{Study 4: Training and evaluation on multiple modalities} \label{subsec:study4} After having analyzed the impact of having a multi-modal lighting system available in training phase only, in this Study our aim is to verify the effectiveness of having the same multi-modal lighting system also in evaluation phase. It is important to highlight that the images of the same defective region collected with different light illuminations share the same annotations and should produce the same output. Combining each generated output is, therefore, essential and we expect it can positively impact the final algorithm performance, as it has been shown in other scenarios \cite{aghaei2016multi}. We propose the following fusing procedure: Let us define the set of 12 images of the same region collected varying the illumination conditions as $I = [i_1, i_2, \dots, i_{12}]$, let us define $B = [b_1, b_2, \dots, b_{M}]$ the set of the $M$ defective bounding-boxes detected in all $i_n$ images $\in I$, and let us also define $C = [c_1, c_2, \dots, c_{M}]$ the set of the corresponding detection confidences given by the detection algorithm. Our proposal is to apply Non-Maximal Suppression (NMS) algorithm over $B$ and replace on every $i_n \in I$ the output of the NMS algorithm. Given the NMS Intersection-over-Union (IoU) threshold as $\theta$, NMS algorithm operates as written in Algorithm \ref{alg:nms}. \begin{algorithm} \caption{Non-maximal Suppression} \hspace*{\algorithmicindent} \textbf{Input} $B, C, \theta$\\ \hspace*{\algorithmicindent} \textbf{Initialization} $D \leftarrow \left \{ \right \}$ \begin{algorithmic} \WHILE{$B \neq \emptyset$} \STATE $\kappa \leftarrow \argmax C$ \STATE $K \leftarrow b_{\kappa}$ \STATE $B \leftarrow B - K$ \STATE $D \leftarrow D \cup K$ \FOR{$b_\zeta \in B$} \IF{$IoU (K,b_\zeta) \geq \theta$} \STATE $B \leftarrow B - b_\zeta$ \STATE $C \leftarrow C - c_\zeta$ \ENDIF \ENDFOR \ENDWHILE \end{algorithmic} \hspace*{\algorithmicindent} \textbf{Output} $D, C.$ \label{alg:nms} \end{algorithm} NMS operates in three steps: Firstly, it sorts all of the detected boxes based on their box confidence scores from high to low; secondly, it selects the box which has the highest box confidence score as the detection result; and finally, it discards other candidate boxes whose IoU value with the selected box is beyond the threshold. Within the remaining boxes, NMS repeats the above two steps until there is no remaining box in the candidate set $B$. In Study 4 we will compare the performances of the system when the model is trained on the entire multi-modal training set and evaluated on the entire test set, with and without applying the proposed late-fusion technique. \section{Experimental setup, results and discussion} \label{sec:exp-results} In all the experiments discussed earlier in Sec.\ref{sec:method} for automatic defect detection, we used YOLO-v3 end-to-end detection pipeline \cite{redmon2018yolov3}, given its fast inference time and its ability to detect small defects.\footnote{ We would like to mention that a comparative study of detection algorithms is out of the scope of this paper.} YOLO-v3 detector has been originally trained over the COCO dataset \cite{lin2014microsoft}, then the weights of the network are adapted to our task using the transfer learning approach updating all the layers of the network. Training has been done on a NVIDIA GeForce RTX 2080 Ti GPU, with learning-rate = 0.0001, and momentum = 0.9. As mentioned in Sec. \ref{sec:dataset}, the dataset is split into training, validation, and test sets. In the experiments where a subset of data is required (Study 1, 2 and 3), that subset is selected within training, validation, and test sets independently and the splits do not vary in the experiments belonging to the same Study, or shared among various Studies (for example, Test - C is common among Study 1, 2 and 3). This allows us to retain the comparability of the experiments from one Study to another. As in standard settings, the validation set is used to tune the parameters of the algorithm and the final results are reported on the test set. Each detection bounding-box proposed by the model is compared with the ground-truth and classified as: \begin{itemize} \item True Positive (TP): the detection has IoU $\geq$ $threshold$ and it is therefore considered correct; \item False Positive (FP): the detection has IoU $<$ $threshold$ and it is therefore considered wrong; \item False Negative (FN): the ground-truth annotation has not been detected. \end{itemize} We report the results of all experiments using the standard metrics used in single-object (defect) detection as Precision, Recall, F1-score, and Average Precision (AP). Among the aforementioned metrics, Precision, Recall, and consequently, F1-score are reported after fixating the acceptance confidence threshold of the algorithm, in this work set to $0.7$. Precision is defined as $\frac{TP}{TP+FP}$, Recall as $\frac{TP}{TP+FN}$ and F1-score as $2\frac{Precision * Recall}{Precision + Recall}$. AP on the other side, summarizes the Precision-Recall curve as the weighted mean of Precision achieved at different confidence thresholds, with the increase in Recall from the previous threshold used as the weight and is calculated as $\sum_{t} (R_t - R_{t-1})P_t$, where $P_t$ and $R_t$ are the Precision and Recall at the $t$-th threshold. To compare the results in the next sections, we will mainly refer to AP, since AP compared to F1-score considers Precision and Recall relations more globally \cite{boyd2012unachievable}. In this section, results are reported with a fixed $IoU=0.5$ threshold with the ground-truth among the experiment. \subsection{Study 1: Training and evaluation on one single modality} The results of the experiments discussed in Sec. \ref{subsec:study1} are given in Table \ref{table,1st}. The most effective configuration according to the AP is the one activating all the lateral lights to produce dark-field illumination from four directions. This configuration outperforms frontal light and dark-field illuminations in any of vertical and horizontal directions and it will be referred to as the baseline for the following studies. \begin{table}[h!] \centering \caption{Results of Study 1} \begin{tabular}{|c|c|c c c c|} \hline Train & Test & Precision & Recall & F1-score & AP \\ \hline \hline C & C & 63.53 & 45.84 & 53.25 & 29.97 \\ U D & U D & 61.69 & 44.95 & 52.01 & 29.11 \\ L R & L R & 58.56 & 41.07 & 48.28 & 25.52 \\ U D L R & U D L R & 61.06 & 52.73 & 56.82 & \textbf{34.69} \\ \hline \end{tabular} \label{table,1st} \end{table} \subsection{Study 2: Training on multiple modalities, evaluation on a single modality} The results of the experiments discussed in Sec. \ref{subsec:study2} are reported in Table \ref{table,2nd}. Each training set has been generated 5 different random times for each experiment and results are given in $mean \pm std$ format in the AP column. Precision, Recall, and F1-score values are given for only the first trial. The results indicate, given the same number of images in the training set, maximizing the heterogeneity in the lighting modalities is more effective than acquiring more samples of defective objects with a limited set of illumination modalities. \begin{table}[h!] \centering \caption{Results of Study 2} \begin{tabular}{|c|c|c c c c|} \hline Train ($N=5$) & Test & Precision & Recall & F1-score & AP \\ \hline \hline \begin{tabular}[c]{@{}c@{}}All samples \\ 3 rand. modalities \end{tabular} & \multirow{2}{*}{C} & 66.28 & 38.00 & 48.30 & 25.74$\pm$2.75 \\ \cline{1-1} \cline{3-6} \begin{tabular}[c]{@{}c@{}}Quarter of samples\\ All modalities\end{tabular} & & 64.86 & 49.38 & 56.07 & 33.18$\pm$1.5 \\ \hline \hline \begin{tabular}[c]{@{}c@{}}All samples \\ 3 rand. modalities \end{tabular} & \multirow{2}{*}{U D} & 66.98 & 36.94 & 47.62 & 27.17$\pm$3.9 \\ \cline{1-1} \cline{3-6} \begin{tabular}[c]{@{}c@{}}Quarter of samples\\ All modalities\end{tabular} & & 64.74 & 51.00 & 57.06 & 33.29$\pm$1.3 \\ \hline \hline \begin{tabular}[c]{@{}c@{}}All samples \\ 3 rand. modalities \end{tabular} & \multirow{2}{*}{L R} & 68.48 & 36.90 & 47.96 & 27.45$\pm$2.9 \\ \cline{1-1} \cline{3-6} \begin{tabular}[c]{@{}c@{}}Quarter of samples\\ All modalities\end{tabular} & & 65.01 & 51.37 & 57.39 & \textbf{34.49$\pm$1.57} \\ \hline \hline \begin{tabular}[c]{@{}c@{}}All samples \\ 3 rand. modalities \end{tabular} & \multirow{2}{*}{U D L R} & 66.34 & 36.61 & 47.18 & 26.87$\pm$3.79 \\ \cline{1-1} \cline{3-6} \begin{tabular}[c]{@{}c@{}}Quarter of samples\\ All modalities\end{tabular} & & 63.53 & 48.32 & 54.89 & 31.84$\pm$0.65 \\ \hline \end{tabular} \label{table,2nd} \end{table} Comparing the results of Study 2 with Study 1, it is noticeable that multi-modal training is beneficial for most of the single lighting modalities in evaluation and that the single-modal test performance is less dependent on the choice of the illumination modality if the algorithm is initially trained with multiple modalities. \subsection{Study 3: Training on all the images and modalities, test on a single modality} The results of Study 3 are listed in Table \ref{table,3rd}. Comparing these results with ones of Study 2, using a bigger training set leads to a considerable performance boost (at least $\sim18\%$). These results are a clear demonstration that acquiring more images using multiple light conditions is actually enriching the information provided to the model during training. Even in the case when 3 modalities out of 4 are not used in evaluation time, their availability during training makes the system able to better model the detection task to be solved, as it has been shown in other scenarios \cite{garcia2018modality}. \begin{table}[h!] \centering \caption{Results of Study 3} \begin{tabular}{|c|c|c c c c|} \hline Train & Test & Precision & Recall & F1-score & AP \\ \hline \hline \multirow{4}{*}{\rotatebox[origin=c]{90}{All Train}} & C & 72.61 & 70.23 & 71.39 & 52.29 \\ & U D & 70.69 & 71.22 & 70.95 & 52.27 \\ & L R & 73.76 & 68.87 & 71.23 & \textbf{52.57} \\ & U D L R & 72.11 & 70.37 & 71.23 & 52.38 \\ \hline \end{tabular} \label{table,3rd} \end{table} Eventually, it is worth noting that choosing any illumination modality to be used in production, after training the model with the multi-modal illumination system, would not bring significant variation in the detection performances. \subsection{Study 4: Training and evaluation on multiple modalities} \begin{table}[h!] \centering \caption{Results of Study 4} \begin{tabular}{|c|c|c c c c|} \hline Train & Test & Precision & Recall & F1-score & AP \\ \hline \hline All Train & All Test & 72.26 & 70.18 & 71.20 & 52.08 \\ \hline \begin{tabular}[c]{@{}c@{}}All Train\\ +\\ Late-fusion\end{tabular} & All Test & 58.23 & 90.56 & 70.89 & \textbf{60.84} \\ \hline \end{tabular} \label{table,4th} \end{table} The focus of the experiments until this point was given to the analysis of the effect of the presence of all or selected number of modalities in training while evaluation of the algorithms has been reported on single modalities. In Study 4, we aim to analyze whether it is possible to further improve the overall system performance having the availability of all the modalities also in evaluation phase. With this Study we can also assess the benefits which can be obtained with the deployment of our designed system in the operational scenario. The results of this study are reported in Table \ref{table,4th}. Comparing the results given in Table \ref{table,4th} with ones in Table \ref{table,3rd}, having the availability of all the modalities in evaluation phase, leads to performance improvements only if the detection results obtained from each single illumination modality are properly combined, using the late-fusion technique proposed in Sec. \ref{subsec:study3}. Fig. \ref{fig:roc} shows the Precision and Recall values obtained at different detection confidence thresholds in $\{0.1, 0.2, \dots, 0.9\}$, with and without employing the late-fusion technique. It can be observed that applying late-fusion leads to a higher Area Under Curve (AUC), thus higher AP. Employing late-fusion, Fig. \ref{fig:quality} shows three examples of the successful detections of defects employing late-fusion (on the right). The qualitatively better detections after applying late-fusion with regards to detections on single images can be appreciated in all the three cases. \begin{figure} \hbox{\hspace{3em}\includegraphics[width=0.40\textwidth]{fig_roc.png}} \caption{Precision and Recall values \\ per confidence thresholds.} \label{fig:roc} \end{figure} \begin{figure*} \centering {\includegraphics[width=0.9\textwidth]{fig_quality1.png}} \newline \centering {\includegraphics[width=0.9\textwidth]{fig_quality3.png}} \newline \centering {\includegraphics[width=0.9\textwidth]{fig_quality2.png}} \newline \caption{Three examples of successful qualitative results before and after applying the proposed late-fusion technique. Green bounding-boxes indicate the ground-truth while the orange indicates the final detection boundary. As it can be seen, applying the late-fusion of the results leads to a more coherent and correct final detection of defects in all the images of the defective object. Note how differently light configurations and exposures behave on different surface types and defects.} \label{fig:quality} \end{figure*} On the other side, Fig. \ref{fig:failure} shows five examples of failure cases even after the late-fusion technique in five defective images. In these cases, our observation is that the algorithm fails to detect a defect if it is not fairly visible in any of the images taken under any of the lighting conditions \cite{kokoschka1986visual}. Besides, false positive detections in some cases occur due to the presence of visually similar-to-defect artifacts on the images. This can be considered to confirm the importance of acquisition hardware setup design, and further, annotation process, for obtaining desirable results by the machine vision algorithms. In the cases where false positive detections are due to missing annotations, thus noise in the labels, the proposed method can be used to provide support for localization of defects to be fixed in the product revision departments in industries, or as an additional supervision method for further improvement of training procedure. \begin{figure*} \centering \includegraphics[width=0.8\textwidth]{fig_quality_failure.png} \caption{Five examples of missing detections or false alarms applying the proposed late-fusion. One can appreciate the visually similar-to-defect regions where false positives occur. In some of the images, the algorithm fails to detect the defect possibly due to the invisibility of the defect on the images.} \label{fig:failure} \vspace{-1em} \end{figure*} \section{Conclusion} In this paper, we introduced our custom-designed acquisition setup for inspection of a complex-object, and discussed its suitability in visualizing a wide range of surface defects thanks to the proposed illumination setup which holds four standard illumination techniques comprised of diffused, dark-field, and front illumination in one place. Further, we argued that deployment of the proposed setup might not be feasible in an inspection environment, thus we conducted four studies to exploit the role of each of the illumination sources and whether it is possible to exploit the potentials of the proposed setup when only deployed in training phase. The conclusions from the studies can be summarized as follows. In the case of deployment of the same single illumination modality in both training and evaluation phase, the most effective one is discovered to be activating all the lateral lights resembling dark-field illumination from four directions. However, given the same number of images in training set but with more modalities, the evaluation results on any of the single modalities are less dependent on the type of modality in evaluation phase. Nevertheless, exploiting more samples in all the modalities in training phase brings to a large improvement when evaluated on single modalities, justifying our proposed lighting setup to be employed at least for training purposes. The introduction of all the modalities in evaluation phase though does not lead to any substantial change with regards to a single modality illumination only, unless the proposed late-fusion technique is utilized which is when the highest performance of the proposed pipeline is achieved. We believe our proposed acquisition setup and pattern analysis of the illumination modalities can be a source of intuition for other researchers in the industrial inspection field for the automatic examination of objects with highly complex characteristics.
{'timestamp': '2020-04-21T02:29:16', 'yymm': '2004', 'arxiv_id': '2004.09374', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09374'}
arxiv
\section*{Results} We first demonstrate the shift of consumer behaviour towards more sustainable consumption, meaning products that are rated higher than $5$. The sustainable shopping behavior is measured using the weekly expenditures made for such products, normalized in $[0,1]$ using the observed maximum value. The expenditure values are deflated using the Harmonized Index of Consumer Prices~\cite{diewert2002harmonized}. The consumers that did not use the app (control group) were matched with consumers that did use the app. The following matching criteria (behavior covariates) were applied: (i) The deflated monthly total budget spent, (ii) the distribution of deflated monthly budget spent per product category and (iii) the sustainability index of the average purchased products per month. Matching reduces the control group from 3438 to 532 for Retailer A and from 1843 to 59 for Retailer B. The total consumers who participated in the field tests are filtered out to 148 (Retailer A) and 30 (Retailer B) consumers (treatment) by isolating the ones who have seen the rate of the products they have purchased. Figure~\ref{fig:behavior-change} illustrates the results of the causal impact analysis~\cite{brodersen2015inferring} using causal inference via structured Bayesian times series. \begin{figure}[!htb] \centering \includegraphics[width=0.49\textwidth]{behavior-change-COOP.pdf} \includegraphics[width=0.49\textwidth]{behavior-change-WM.pdf} \caption{\textbf{Shift to more sustainable consumption}. Predicted vs. actual normalized weekly expenditures made for highly rated products ($>5$). (a) Retailer A and (b) Retailer B. We find a high statistical significance of $p<0.001$ for a significance level of $\alpha=0.01$.}\label{fig:behavior-change} \end{figure} The results confirm a statistically significant increase of expenditures for highly rated products: (i) The absolute effect is 20\% for each retailer. (ii) The relative effect is 36.7\% and 41\% for Retailer A and Retailer B respectively. Table~\ref{table:causal-impact} in the Supplementary Information summarizes the results of the causal impact analysis. 68\% and 75\% of the total purchased products in Retailer A and Retailer B respectively are highly rated ($>5$) products that are seen in the app. Novel purchases of (i) products purchased for the first time and (ii) products whose rating is seen in the app also increase: 22\% and 16\% for Retailer A and Retailer B. The survey results of Figure~\ref{fig:feedback:pos},~\ref{fig:feedback:awareness} and~\ref{fig:feedback:final} of the Supplementary Information also confirm the following: (i) High product ratings reflect consumers' preferences. (ii) New products are discovered via the products rating. (iii) The rating of products is justified to consumers. (iv) Consumers are more aware of sustainability aspects after using the app. \subsubsection*{Relation between sustainability and price} For novel product purchases during the field test, 16\% of the field test consumers at both retailers pay at least 0.1 euros more on average for each novel product by supporting at least one of the three environmental preferences (see Table~\ref{tbl:preferences:env} in Supplementary Information). If we consider in particular the consumers of the causal impact analysis (the ones who regularly interacted with the smart phone app), the percentage of consumers increases to 39\% and 30\% for Retailer A and B respectively. We next assess whether the purchased products rated high within each product category are also the more expensive ones. First, both product deflated prices and the product ratings are normalized (see Section~\ref{subsec:prices:eval} of Supplementary Information for details). Figure~\ref{fig:price-rating} shows the frequency of the rated products that were viewed and purchased against price and rating. Retailer A clearly has a higher number of products with high price and rating as reflected by the high values on the top right of the heatmap. Similarly in Retailer B, for each normalized price value per product unit, a higher number of products are viewed and purchased that have higher rating values. We further measure the non-linear relation between product price and product ratings with the Spearman's correlation coefficient across product categories. We observe a positive correlation coefficient of $\rho=0.14$ and $\rho=0.19$ for Retailer A ($p=0.01$) and Retailer B ($p=0.02$) respectively. This suggests that highly rated products may come with slightly higher prices. \begin{figure}[!htb] \centering \includegraphics[width=0.49\textwidth]{rating-price-correlation-COOP.pdf} \begin{picture}(0,0) \put(-213,155){\colorbox{white}{\small a)}} \end{picture} \includegraphics[width=0.49\textwidth]{rating-price-correlation-WM.pdf} \begin{picture}(0,0) \put(5,168){\colorbox{white}{\small b)}} \end{picture} \caption{\textbf{Highly rated products correlate to a low extent with increased prices.} (a) Retailer A and (b) Retailer B. Normalized product unit price vs. normalized product rating for the frequency of purchased products, whose rating is seen in the app. Frequency values are derived at the level of product categories. Note the increased frequency of purchased products with higher price as the product rating increases. This is particularly visible for Retailer A with a higher number of data records and quality.}\label{fig:price-rating} \end{figure} The question that arises here is whether this positive correlation stems from the consumers' personalization, i.e. the choices on sustainability preferences, or the actual knowledge-base and the ontology design that is universal for all consumers. To answer this question we repeat these measurements, but instead of the normalized product rating we used the min-max normalized sustainability index for each preference. The Spearman's correlation coefficient between the sustainability index of products and product prices per category is calculated for each preference across product categories. Out of 50 correlation values evaluated at each retailer, only one correlation value is $>0.5$ and statistically significant. This confirms that no price biases are observed in the designed ontology in favor of more expensive products. Nevertheless, it is possible that certain preferences result in a sustainability index that is positively or negatively correlated with price due to the nature of this preference. For instance vegetarian diet products may come with lower prices only because they do not contain meat that is usually expensive. See Tables~\ref{tbl:price:corr:coop:norm} ,~\ref{tbl:price:corr:wm:norm} and~Figure~\ref{fig:price:radial} in the Supplementary Information for an evaluation of all preferences. \subsubsection*{Sustainability preference profiles} To understand how different consumers influence the product rating via personalization, we extract preference profiles by clustering consumers based on the preference choices they made during the field tests. We distinguish between \emph{initial preferences} and \emph{preference adjustments}. The initial preference choices are the very first ones made before consumers are exposed to the product rating functionality. They represent the more intrinsic intentions of consumers towards the sustainability aspects. The preference adjustments are the ones made after the initial preferences and throughout the field test participation. \textbf{Initial preferences.} The profiles of the initial preferences are extracted by clustering consumers using the Ward hierarchical clustering approach~\cite{johnson1967hierarchical}. Seven clusters are calculated for each retailer as shown in Figure~\ref{fig:consumer-profiles-coop}a. Note that most of the profiles consist of choices with a significantly high score in ``environment'' and ``quality'' as well as a high score in the category ``social''. The scores for ``health'' shows significant variation among the different profiles that reflects the diversity of dietary needs: (i) Two neutral profiles with scores around 5 are observed for both retailers. (ii) There is a profile that penalizes strict preferences such as vegan, gluten/lactose-free, etc, with low score. (iii) The majority of the profiles retain a high score for health indicators such as no preservatives/colors/emulsifiers, etc. The majority of consumers avoids radical scores in health and expresses their sustainability profile via preferences regarding environment and quality aspects. \begin{figure}[!htb] \centering \includegraphics[width=1.0\textwidth]{profiles.pdf} \begin{picture}(0,0) \put(-210,170){\colorbox{white}{\footnotesize a)}} \put(-5,170){\colorbox{white}{\footnotesize b)}} \end{picture} \caption{\textbf{Preference score profiles over the four sustainability aspects for Retailer A (top) and Retailer B (bottom)}. (a) Initial preference profiles that demonstrate the high preference scores in environment and quality aspects. (b) Minimal targeted adjustments made during the field test confirming that products rating match the expectations expressed via the sustainability preferences.} \label{fig:consumer-profiles-coop} \end{figure} \textbf{Preference adjustments.} We assume that consumers adjust their preferences if they are not satisfied with how products are rated or if they aspire to explore new products. Consumers may also try to match the rated products with the ones they use to buy. We measure the mean difference between the initial preferences and all adjusted preferences per profile to understand how different consumer groups adjust their preferences to meet their expectations. Figure~\ref{fig:consumer-profiles-coop}b shows the profile adjustments. We observe the following: (i) The majority of preference scores is on average unaffected, indicating that consumers do not need to adjust their preferences and they preserve their initial intrinsic sustainability preferences. This also validates the ontology from the consumers' perspective. (ii) Consumers with initial neutral preferences increase their preference scores, especially in Retailer B. (iii) Consumers who initially maximize the preference scores slightly roll back to more moderate preference values, especially at Retailer B. Apparently this rollback is related with a consumers' openness towards experiencing radically different highly rated products or with the ontology design and rebound effects that results in buying unexpected products. Similarly, the group of consumers that initially penalizes health preferences with low score makes adjustments to higher scores. \section*{Discussion and Outlook} The findings of this work have several implications for consumers, retailers and producers. They also have an impact on science, policy and at an institutional level. We outline here the challenges and the new pathways that this works opens up. \textbf{Consumers.} We show that value-sensitive design empowers more informed, transparent and accountable shopping choices tailored to personal sustainability values. As a result, consumers explore and finally buy new products. Compared to related work limited to health or environmental indicators for sustainability, we study a broad, yet finite set of such indicators (preferences). In the future, consumers themselves may expand or even limit this set according to their intrinsic priorities. Augmented shopping processes with smart phones may still disrupt regular shopping routines for some consumers. It is unclear to what extent and scale consumers can adopt such technologies at this moment. However, this was also the case with online shopping a few years ago and nowadays efforts such as Amazon Go~\cite{Polacco2018} showcase the feasibility of such technologies in the market. The applicability of the value-sensitive shopping assistant in the context of online shopping is promising and may simplify its use by consumers. In terms of consumers' trust on products rating, new models are required to preserve a satisfactory level of explainability in the long term. This is especially the case when such models need to capture an expanding spectrum of product characteristics as well as the dependencies and incompatibility of sustainable development goals~\cite{Spaiser2017}. The transparency and accountability of the knowledge-base can be further enhanced with the blockchain as a means to securely verify sustainable production practices as well as the traceability of supply chain~\cite{Howson2019,Gammon2018}. Recent studies also confirm how indispensable the active consumers' involvement is to evolve a viable and accurate knowledge-base on sustainability via citizen science initiatives~\cite{sachs_six_2019,Fritz2019}. \textbf{Retailers.} Retailers can pioneer as sustainability ambassadors by offering the products that are more ethically aligned to consumers' sustainability values. They can focus on selling a higher number of highly rated products that might come with slightly higher prices (or profit margins), while they serve consumers' values on sustainability. \textbf{Producers.} Value-sensitive design provides new opportunities for producers to enter retail markets with more attractive products, i.e. higher quality, by capturing (i) consumers' sustainability preferences and (ii) the sustainability gap of existing products. Moreover, producers have new opportunities to sell higher quality products at a higher price. The improvement of production practices is incentivized by capturing new consumers' values on environment, health or worker rights that can monetize innovation in sustainable production. \textbf{Science.} By demonstrating the shift of individuals to sustainable consumption, we also open up new opportunities for social coordination: moving from individual sustainability preferences to collective actions to meet sustainable development goals, bottom-up. Scientific methods from the areas of game theory, mechanism design, incentives, socio-technical optimization and learning~\cite{Becker2017,Mason2012,Mann2017,Pournaras2018} are becoming applicable to further promote and coordinate sustainability movements in society. A transdisciplinary scientific scope and methods such as the ones of this work are further required to automate the development of sustainability knowledge-bases using responsible AI and wisdom of the crowd~\cite{Bergmair2018,Kittur2019}. \textbf{Policy-making and institutions.} We foresee new opportunities for environmental non-profit organizations to interact and educate the general public by publishing their own personalization templates for consumers, for instance, adopting the WWF or Greenpeace priorities for sustainability. Such customizable personalization is supported by the built system. Legislation could protect the open and public good character of a knowledge-base for sustainability. Such a knowledge-base should not be used as an unquestionable universal ground truth for sustainability. Instead, we envision, at a global scale, the active involvement of several stakeholders such as public organizations, scientists and especially citizens to capture and develop the evolving nature of sustainability values. Promising related initiatives include the European Commission Environmental Footprint initiative or the Global Product Classification standardizing institution GS1. In other fields such as biology, initiatives for ontologies and knowledge-bases have had significant impact, for instance the Gene Ontology Consortium~\cite{Ashburner2000}. The EU project ASSET~\cite{ASSET}, in the context of which this work has been carried out, is a promising blueprint to scale up sustainable consumption bottom-up. \section*{Methods} Here we illustrate more details of the field tests and the causal impact analysis as well as the localization solution at retailer shops. We also outline the ontology design, the product rating methodology, the preference profiles and preference interactions. \subsubsection*{Field tests and causal impact analysis} \textbf{Recruitment.} Each shopping visit at retailer shops is rewarded with 10 euros. By analyzing the history of purchases, 10 visits are expected on average during the field tests and therefore the total maximum amount of 100 euros incentivizes and rewards regular shopping behavior. The study has received ethical approval by the ethical committee of ETH Zurich. To minimize biases originated by different human explanations of how to use the smart phone app (see Figure~\ref{fig:app:usage} in Supplementary Information), an integrated tutorial requires completion before consumers start using the smart phone app. A FAQ based on questions that arose during living lab experiments before the field tests was also included. \textbf{Causal impact analysis} The Dynamic Time Warping (DTW)~\cite{senin2008dynamic} algorithm is used to compare the time series data of consumers that used the smart phone app (treatment consumer) against all consumers that did not use the smart phone app (non-treatment consumers) with purchase records up to 13 months before the field tests (excluding the last month as a buffer zone). Each comparison results in the similarity ranking of consumers, who did not use the smart phone app, from which the top-$k$ nearest neighbors are selected to form the group for assessing sustainable consumption. Since different values of $k$ yield different groups for comparison, the $k$ is selected via a dynamic time warping of weekly expenditure before the treatment as shown in Table~\ref{tbl:distance:explanations} of the Supplementary Information. The temporal distance between consumers is measured over the three matching criteria (behavior covariates). More specifically, the Euclidean distance with dynamic time warping is used to determine the top-k nearest neighbors for the deflated monthly total budget spent and the sustainability index of the average purchased products per month. In contrast, the Jensen-Shannon distance (divergence)~\cite{serjantov2002towards} with dynamic time warping is used for the distribution of deflated monthly budget spent per product category as such distance metric is known for measuring the similarity of distributions. For each consumer that used the smart phone app (treatment consumer), we rank all other consumers that did not use the app (non-treatment consumers) according to the three distance metrics. Since there are three distance metrics and we cannot determine which one has higher influence, the average ranking of the consumers that did not use the app is calculated over all combinations of distance metrics. \subsubsection*{Localization of products} A privacy-preserving indoor localization system is designed for the two retailer shops~\cite{Hormann2019}. It derives the list of products that are in close proximity to consumers. It relies on Bluetooth low energy beacons installed on the shop floor of both retailers. The beacons are aligned with the shop map to provide absolute anchors to the shop coordinates. By analyzing the signal strength of the beacons using triangulation and a map logic on feasible positions and consumer movements, the position of the consumers in the shop is estimated, see Figure~\ref{fig:ASSET}a. This consumer position is related to the coordinates of product groups in close proximity. The rating of these products is calculated and presented to consumers' smart phone as shown in Figure~\ref{fig:ASSET}c. The localization system is privacy-preserving as all calculations are performed at the consumer's smart phone. Moreover, beacons do not obtain any information from consumers and therefore retailers cannot derive consumer movements from this localization system. The deployed technology uses off-the-shelf hardware which yields low hardware costs. The obtained precision has an inaccuracy of about 2 meters. The granularity of product group positions ranged from several meters down to zero accounting the intrinsic ambiguity of product groups positions on top of each other. \subsubsection*{Ontology design} \textbf{Primitive concepts, tags and rules.} The ontology is designed to quantify the association between products and preferences, e.g. to what extent a certain product is for a vegetarian diet, fair trade etc. To measure such associations, we introduce a common alphabet of characteristics for products and preferences. This alphabet is a set of \emph{keywords (tags)} that represent \emph{primitive concepts}. They form the semantic space and scope of sustainability. Subsets of these primitive concepts compose a vocabulary of product and preference tags, while a primitive concept is not further decomposed to keep the ontology practical and consistent~\cite{Alterovitz2010} within its scope, i.e. a primitive concept is regarded disjoint within a chosen scope of sustainability. For example, the preference tag "vegan" can be composed by the two primitive concepts ``production with no animals" and ``production with no animal products". Moreover, products and preference tags are assigned to products and preferences respectively based on logical rules. For instance, to assign the product tag ``low fat" to a product, a logical rule could determine the number of grams in fat, relative to the total product weight, contained in the product and/or whether the product has a low-fat label. Over 600 such rules are created for this purpose using the Drools framework~\cite{Drools}. We focused on food products. They are the ones that populate the knowledge-base and connect to product tags. In summary, the design of the ontology consists of (i) the choice of the primitive concepts, (ii) their assembly to product and preference tags and (iii) the creation of logical rules to connect the tags with products and preferences. These actions required domain knowledge from experts (WWF, Greenpeace, Ethical Consumer, VKI), reliable data sources (e.g. EU reports) as well as the wisdom of the crowd by running the Social Impact Data Hack~\cite{SIDH2017} to mine and structure information from Wikipedia, for instance, branding information (see Section~\ref{sec:crowd_sourced_product_data} in the Supplementary Information). \textbf{Association scores.} The association between a product and a preference tag is measured by their shared primitive concepts that satisfy a preference tag. We distinguish between positive and negative associations by determining for each pair of product and preference tags subsets of primitive concepts that semantically support or oppose the preference tag, i.e. the preference tag ``vegan" supports the primitive concept ``no animals involved in production" but opposes the concept "animal product". Therefore, the association score comes with positive and negative values in the range $[-1,1]$ by summing up the associations between supported and opposed primitive concepts (see Section~\ref{sec:rating} of the Supplementary Information for more details). \textbf{Reduction design principle.} The construction of product and preference tags should adhere to the \emph{reduction design principle}: (i) Between two tags with the same primitive concepts, one and only one should be assigned to a product or preference. (ii) When two tags assigned to a product or preference share primitive concepts, these primitive concepts should be removed and form a new tag. In the example of Figure~\ref{fig:sustainability-index}, the reduction design principle is violated if the product tag $AC$ is assigned to the product, or, the preference tag $BC$ is assigned to the preference. We prove in Section~\ref{sec:ontology} of the Supplementary Information how this principle minimizes the error of overlapping tags when the association scores are aggregated to calculate the rating of a product. Violations of the reduction design principle may result in excessive influence of certain preferences on the product rating. In practice, these artifacts may be captured by consumers, whose adjustments of preferences provide additional countermeasures against the error of semantically overlapping tags. \begin{figure}[!htb] \centering \includegraphics[width=1.0\textwidth]{sustainability-index.pdf} \caption{\textbf{Calculation of the sustainability index using the ontology of products and preferences}. Assume an alphabet of primitive sustainability concepts represented in this simple example by $\{A,B,C\}$. Combining the primitive concepts results is the word vocabulary $\{A,B,C,AB,AC,BC,ABC\}$ of product and preference tags. Using rules based on experts' knowledge and verified data such as ingredients of products, the product tags $A$ and $C$ are assigned to a product. Similarly, a sustainability preference is designed by a composition of the two preference tags $C$ and $AB$. We can now calculate the association scores between the product and preference tags in an automated way (without expert knowledge) by taking the intersection $\cap$ of the tags sets as follows: $|\{A\} \cap \{C\}|/|\{C\}|=0$, $|\{C\}\cap \{C\}|/|\{C\}|=1$, $|\{A\} \cap \{AB\}|/|\{AB\}|=0.5$, $|\{C\} \cap \{AB\}|/|\{AB\}|=0$. The sustainability index of a product for a given preference is calculated by the average normalized aggregate association scores of the assigned preference tags as demonstrated in this numerical example. The equations refer to the Supplementary Information.}\label{fig:sustainability-index} \end{figure} \textbf{Experts' guideline.} We propose a high-level guideline to populate the sustainability knowledge-base according to the proposed ontology. This guideline can be used by domain experts to guide the construction process and is outlined as follows: \begin{enumerate} \item Identify relevant primitive concepts based on (i) the product categories (i) the available product data and (iii) the scope of sustainability preferences (goals). \item Create product and preference tags using the primitive concepts such that these tags represent how product/preference characteristics oppose or support a product/preference. \item Create rules that connect the product tags with products, and the preference tags with preferences. \item Apply the reduction design principle between all combinations of product tags and preference tags that have overlapping concepts. \item Calculate association scores between product-preference tag pairs in the range $[-1,1]$. \item If necessary, go back to Step 1, add or remove primitive concepts and repeat the process. \end{enumerate} In Step 1, experts determine the scope of the sustainability by defining primitive concepts that capture key characteristics of products and preferences. Experts need to be aware of the products for which they design the ontology, the available information they have about these products as well as the sustainability preferences that should be captured. In Step 2 they can start combining these concepts into tags with the purpose of representing support or opposition to product characteristics and preferences. In Step 3, experts can assign these tags to product and preferences and can formalize rules under which these assignments are made. The processes of the first three steps are the most tedious ones and requires knowledge, experience and a good overview of the available information. As an example of facilitating such processes, we performed workshops with several stakeholders during the project lifetime and organized the Social Impact Data Hack~\cite{SIDH2017}. Step 4 applies the reduction design principle to improve the consistency of the ontology. Step 5 performs the calculations of the association scores based on the (automated) calculations illustrated in Figure~\ref{fig:sustainability-index}. In practice, these calculations are often calibrated by experts to reason about the association scores based on ground truth knowledge. For instance, consider a study that shows evidence about the effect of different preservatives on health. Obviously, the cause of such effects may be related to chemical or biological phenomena at a very low granularity level that is not captured within the scope of the designed sustainability ontology. In this case, association scores measuring can be calibrated to reflect the relative effect of preservatives according to the findings of such a study. Finally, the process can repeat by adding or removing primitive concepts. The motivation for this iterative process is to better capture the whole range of preferences, decompose further primitive concepts to make the ontology more granular, add/remove rules, expand product categories or enrich the knowledge-based with new datasets. During the ontology design, we performed over 10 iterations for validation purposes and the quality criterion for convergence was how well the product rating could be justified to consumers during the preliminary living lab tests. \subsubsection*{Product rating: Sustainability index and preferences} \textbf{Sustainability index.} It quantifies the support or opposition of a preference by a set of product characteristics found in a product. This support or opposition is compared to a product, existing or hypothetical (`reference product' in Figure~\ref{fig:sustainability-index}), that has all possible characteristics that can support or oppose respectively a preference. Figure~\ref{fig:sustainability-index} illustrates the involved calculations. The sustainability index between a product and a preference is measured using the normalized association scores aggregated over the connected product and preference tags. The normalized aggregated association score of a product-preference pair is the normalized aggregated association score of a product averaged over all preference tags assigned to the preference (Calculation 4 in Figure~\ref{fig:sustainability-index}). Each normalized aggregated association score between a product and a preference tag (Calculation 3 in Figure~\ref{fig:sustainability-index}) is calculated by the aggregated association scores of the product tags assigned to this product (Calculation 2 in Figure~\ref{fig:sustainability-index}) divided by the maximum association score between the reference product and the preference tags of the preference (Calculation 1 in Figure~\ref{fig:sustainability-index}). \textbf{Insights on sustainability of production.} Note that by calculating for each preference the density of the sustainability index over all products, new opportunities arise to reason about the following: (i) The sustainability profile of different retailers. (ii) New ways (preferences) with which producers can improve products with a more sustainable profile. (iii) Market gaps where new business ecosystems can evolve with stronger involvement of producers and consumers to accelerate sustainable consumption. For instance, the densities in Figure~\ref{fig:si:distro} of the Supplementary Information confirms the more sustainable profile of Retailer B products across the preferences, e.g. higher sustainability index for animal rights, fair trade, recyclability and green farming. Improvements can be made by either introducing new products with better sustainability footprint over these preferences or by improving the existing production practices of the available products. \textbf{Product rating.} Note that the sustainability index does not require any personal information for its calculation. It only relies on the information of the sustainability ontology, i.e. primitive concepts and tags, that we make available as public-good knowledge. As such, it can be calculated in public computational infrastructure, i.e. servers, public clouds, etc. In contrast, the calculation of the product rating requires personalization with consumers' preference choices that remain by design locally on their smart phones to protect privacy and limit manipulative nudging. As a result, the product rating is calculated on consumers' smart phones using the sustainability index values retrieved remotely using a distributed protocol of message passing between smart phones and a project server. The calculation is performed on-demand by consumers when they navigate in the retailer shop and request the rating of the products that are in their close proximity. For each product, the rating algorithm multiplies the sustainability index with the degree of opposition or support of each preference, measured by the distance (offset) from the median preference score ($5$, remaining neutral). These calculations are summed up and divided by the sum of all distances from the median preference scores. Section~\ref{sec:rating} in the Supplementary Information outlines in more detail the product rating calculation and its computational complexity. The (unscaled) product rating calculation is summarized as follows: \begin{equation} \text{product rating}=\frac{\text{sum of all (sustainability indices $*$ preference offsets)}}{\text{sum of absolute preference offsets}}, \end{equation}\label{eq:product-rating} \noindent where the product rating values can be scaled to match different grading systems of different countries ($[0,10]$ in the field tests as supported in the Section~\ref{sec:rating} of the Supplementary Information). \textbf{Explainability} Two levels of rating explainability are provided to consumers: (i) \emph{product tags} and (ii) \emph{preferences}. Consumers can learn about how each product characteristic influences the rating value by solving Equation~\ref{eq:contr:prftag} of Supplementary Information for a certain product tag, given that all other variables are known. Similarly, consumers can know how each offset of their preferences contributes to the product rating by solving Equation~\ref{eq:contr:preference} of the Supplementary Information for a certain preference offset. \textbf{Preferences selection.} The selection of preferences was made on the basis of providing a broad spectrum of different sustainability indicators with which consumers can express their preferences. However, this spectrum is not too broad to the extent of creating a cognitive overload for consumers and lack of comprehension about which preferences influence the rating of products and why. This is critical for the effectiveness of the rating explainability. Moreover, a lower number of preferences decreases the computational cost of the rating algorithm and improves the usability of the smart phone app (see Section~\ref{subsec:algorithm-complexity} of the Supplementary Information). This balance is a result of the following process: (i) Participation of several stakeholders in the ASSET project meetings and workshops providing insights about how grocery product choices influence different sustainability criteria. (ii) Preliminary living lab experiments and smaller-scale field tests for feedback acquisition on the preferences. (iii) Choice based on available data, i.e. product and preference tags. Preferences with very similar preference tags or very few preference tags are removed or merged. The set of the final preferences shows a balance between several individual criteria on health (13) versus collective criteria in environment, social and quality aspects (12). The consumers' feedback during the preliminary tests also determined the \emph{strict preferences} of gluten-free, lactose-free, vegan and vegetarian products. Fully supporting such preferences results in excluding products that do not fully satisfy them even though they may satisfy other (non-strict) consumer preferences. In other words, strict preferences cancel association scores with other preferences. \subsubsection*{Preference profiles and interactions} \textbf{Preference profiles.} The Ward hierarchical clustering approach~\cite{johnson1967hierarchical}, with which the preference profiles are extracted, is selected based on its interpretable clusters and high scoring in the following evaluation metrics~\cite{Rendon2011}: silhouette, Dunn index, Davies-Bouldin and Calinski-Harabaz. It uses Euclidean distance given that preference scores are continuous, not sparse and different preference scores are comparable, with the exception of strict preferences that may introduce biases. No normalization or standardization is performed given the same scale among preferences. \textbf{Interactions of preferences} The sustainability preferences show correlations that originate from the (i) anticipated association between different product/preference tags (ontology-level) and (ii) the actual linking of products to product tags (product-level). This information at the ontology and product-level respectively can be used to reason about potential rebound effects~\cite{Spaiser2017}: undermining a sustainability preference by satisfying another one. \begin{figure}[!htb] \centering \includegraphics[width=1.0\textwidth]{rebound-effects.pdf} \caption{\textbf{Interaction effects between different sustainability preferences}. Ontology-level: Correlation of association scores for (a) Retailer A and (b) Retailer B. Product-level: (c) Correlation of sustainability indices for a common set of products between Retailer A and Retailer B . Positively correlated preference pairs across the x and y axes indicate dependence whereas negatively correlated preference pairs indicate potential rebound effects.}\label{fig:rebound-effects} \end{figure} \begin{enumerate} \item \textbf{Ontology-level}: The interaction of two preferences is measured as follows: (i) Find the shared product tags between the two preferences. (ii) For each of the two preferences and shared product tag, calculate the average association score among the preference tags of the preference and the shared product tag. (iii) Calculate the Spearman correlation coefficient of the average association scores among the two preferences. \item \textbf{Product-level}: The interaction of two preference at the product-level is measured as follows: (i) Calculate the sustainability index for each product-preference pair. (ii) Calculate the Spearman correlation coefficient of the sustainability indices among the two preferences. \end{enumerate} These Spearman correlations are shown in Figure~\ref{fig:rebound-effects}. Potential rebound effects are observed between health/quality preferences vs. environmental ones, while a highly rated product may be caused by multiple environmental preferences that share several common product tags. \subsection*{Acknowledgments} This work was supported by the European Commission H2020 Program under the scheme "ICT-10-2015 RIA" grant agreement \#688364 ASSET - ``Instant Gratification for Collective Awareness and Sustainable Consumerism'' (\url{https://www.asset-consumerism.eu}) and by the LCM – K2 Center within the framework of the Austrian COMET-K2 program. We would like to thank the two retailers Coop and Winkler Markt for supporting the project and field tests as well as all consortium partners for their contributions (alphabetically): AINIA, BIA, Fastline and VKI. The authors are grateful to the participants of the Social Impact Data Hack~\cite{SIDH2017} and in particular Maryna Pashchynska for her contribution to developing the sustainability ontology further. Several organizations supported this project in various ways such as WWF, Ethical Consumer, Greenpeace and Global2000. Finally the authors would like to heartily thank in alphabetical order George Lekakos, Marloes Maathuis, Heinrich Nax, Michael Siegrist and Stefan Wehrli for their invaluable suggestions and feedback. \subsection*{Open Data and Code} The ontology data is available here: https://doi.org/10.6084/m9.figshare.8313257 \noindent The product rating algorithm is available here: https://github.com/asikist/value-sensitive-design-code \section*{\textbf{Supplementary Figures}} \counterwithin{figure}{section} \renewcommand{\thefigure}{S.\arabic{figure}} \setcounter{figure}{0} \begin{figure}[h!] \centering{ \clearpage \scalebox{0.7}{ \begin{tikzpicture}[->,>=stealth',shorten >=1pt,auto ] \path (0,14.5) node[literal node] (qw) {} +(1.3,0) node[align=left] (oolooo) {Primitive\\String} ++(2.6,0) node[entity node] (qwq) {} ++(1.3,0) node[align=left] (ooloo) {Complex\\Entity} ++(1.4,0) node[calculated node] (qwwq) {} ++(1.3,0) node[align=left] (olo) {Calculated\\Number} ++(1.3,0) node[scalar node] (wqqw) {} +(1.7,0) node[align=left] (ollo) {User Provided\\Number} ; \path (0,14.5) node[literal node] (qw) {} ++(-0.4,1) node[] (o) {} +(5.5,0) node[] (oo) {} ++(5.5,0) node[] (ooo) {} +(5.7,0) node[] (oooo) {} ; \path[every node/.style={font=\sffamily\small}] (o) edge node [edgestyle] {relates to} (oo); \path[every node/.style={font=\sffamily\footnotesize}] (ooo) edge[isa] node[isalabel] {isA} (oooo); \path (0,0) node[literal node] (PdT) {Product \\ Tag} +(5,0) node[calculated node] (AcSc) {Tag \\ Association} ++(0,5) node[entity node] (PdD) {Product \\ Data} ++(0,4.7) node[entity node] (Pd) {Product} +(5,0) node[calculated node] (PdR) {Product \\ Rating} +(5,-3) node[calculated node] (PdPfAc) {Product \\ Preference \\ Association} ++(0,3) node[entity node] (U) {User} ++(5,0) node[scalar node] (Sc) {Score}; \path (9.7,0) node[literal node] (PfT) {Preference \\ Tag} ++(0,5) node[entity node] (PfAs) {Preference \\ Aspect} +(-4.7,-2) node[calculated node] (NAgAc) {Normalized \\ Aggregated \\ Association} ++(0,4.7) node[entity node] (Pf) {Preference} ++(0,3) node[literal node] (PfSt) {Preference \\ Statement}; \path[every node/.style={font=\sffamily\small}] (PfT) edge node [edgestyle] {represents} (PfAs) edge node[edgestyle] {has} (AcSc) (PfAs) edge node [edgestyle] {composes} (Pf) (PfSt) edge node [edgestyle] {represents} (Pf) (PdT) edge node[edgestyle] {summarizes} (PdD) edge node[edgestyle] {has} (AcSc) (PdD) edge node[edgestyle] {describe} (Pd) (U) edge node[edgestyle] {assigns} (Sc) edge node [edgestyle] {receives} (PdR) (PdR) edge node[edgestyle] {ranks} (Pd) edge node[edgestyle] {aggregates (\ref{eq:rating:raw})} (PdPfAc) (Sc) edge node[edgestyle] {prioritizes} (PfSt) (PdPfAc) edge node[edgestyle] {evaluates} (Pd) edge node[edgestyle] {considers} (Pf) edge node[edgestyle] {aggegates (\ref{eq:connection})} (NAgAc) (NAgAc) edge node[edgestyle] {evaluates} (Pd) edge node[edgestyle] {considers} (PfAs) edge node[edgestyle] {aggregates (\ref{eq:additive}, \ref{eq:relevance:max}, \ref{eq:relevance:min}, \ref{eq:relevance:norm})} (AcSc) (Sc) edge node[edgestyle] {influences (\ref{eq:offset}, \ref{eq:rating:raw})} (PdR); \end{tikzpicture} } \caption{Product rating is calculated by utilizing the ontology. There are ontology relations that contain the relevant equation from the current article in parenthesis. } \label{fig:prod:rating:ontology} } \end{figure} \begin{figure}[h!] \begin{center}\subfloat[Overlapping product tag and preference tag concepts.]{ \includegraphics[width=0.21\textwidth]{001_img_paper-diagrams_association.pdf} \label{fig:association} }\subfloat[The semantic space that defines a preference tag is the union of the concepts, which support or oppose its existence.]{ \includegraphics[width=0.21\textwidth]{002_img_paper-diagrams_preference_concepts.pdf} \label{fig:preference:concepts} } \\ \subfloat[A product concept as a union of its product tag concepts.]{\includegraphics[width=0.155\textwidth]{003_img_paper-diagrams_product_concepts.pdf} \label{fig:product:concept}}\subfloat[Semantic overlap between a product and a preference tag.]{\includegraphics[width=0.155\textwidth]{004_img_paper-diagrams_agg_association.pdf} \label{fig:overlap}}\subfloat[Introduction of new product tag according to the reduction design principle.]{\includegraphics[width=0.155\textwidth]{005_img_paper-diagrams_reduction_principle.pdf} \label{fig:reduction:design}}\caption{Venn diagrams that illustrate the operations between sets of preference and product tags primitive concepts.} \end{center} \end{figure} \begin{figure}[h!] \centering \includegraphics[width=\textwidth]{006_img_paper-diagrams_theoretical_norm.pdf} \caption{An alternative calculation of sustainability index illustrated in Figure~5. This calculation uses a theoretical normalized aggregate association score that does not respect the reduction design principle of \refsec{subsec:comparable-aggregated-associations}. To avoid violation of the bounding properties of \refeq{eq:relevance:norm}, the clipping methodology introduced in \refsec{subsec:overlaps-and-possible-error-overflows} is used. } \label{fig:clip:aggregate} \end{figure} \begin{figure*}[ht!] \subfloat[Preference tags.]{\includegraphics[width=\linewidth]{042_img_paper-plots_wordclouds_preference_tags.pdf} \label{fig:cloud:preferences}}\hfill\\ \subfloat[Product tags.]{\includegraphics[width=\linewidth]{043_img_paper-plots_wordclouds_product_tags.pdf} \label{fig:cloud:products}}\hfill\\ \caption{Wordclouds of preference and product tags. The size is proportional to the number of products assigned to each tag.\label{fig:cloud}} \end{figure*} \begin{figure}[!htb] \subfloat[B.I.7: Finding additional product information in the app was easy.]{ \includegraphics[width=0.28\linewidth]{007_img_qplots_likerts_83.pdf} \label{fig:feedback:pos:extrainfo} \begin{picture}(0,0) \put(-115,140){\colorbox{white}{\footnotesize Retailer}} \put(-115,131){\colorbox{white}{\makebox(5,2){ }}} \put(-110,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-102,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-102,125){\colorbox{white}{\makebox(5,4){\hfill }}} \put(-115,129){\colorbox{white}{\footnotesize A}} \put(-82,140){\colorbox{white}{\footnotesize Retailer }} \put(-82,129){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-85,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-65,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-55,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-45,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-35,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-75,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-82,129){\colorbox{white}{\footnotesize B}} \end{picture} }\hfill \subfloat[B.I.8: The product info justify the rating of the products.]{ \includegraphics[width=0.28\linewidth]{008_img_qplots_likerts_84.pdf} \label{fig:feedback:pos:justify} }\hfill \subfloat[B.II.6: The products with high rating match my preferences.]{ \includegraphics[width=0.28\linewidth]{009_img_qplots_likerts_91.pdf} \label{fig:feedback:pos:prefmatch} }\hfill \subfloat[B.II.13: I discovered new products while using the rating functionality.]{ \includegraphics[width=0.28\linewidth]{010_img_qplots_likerts_98.pdf} \label{fig:feedback:pos:novelty} }\hfill \subfloat[B.II.14: The app does not take into account my preferences when calculating the ratings.]{ \includegraphics[width=0.28\linewidth]{011_img_qplots_likerts_99.pdf} \label{fig:feedback:pos:preferences:account} }\hfill \subfloat[B.III.1: The app could capture my actual preferences.]{ \includegraphics[width=0.28\linewidth]{012_img_qplots_likerts_117.pdf} \label{fig:feedback:pos:capture:preferences} }\hfill \caption{Questions regarding the application that indicate acceptance from users.} \label{fig:feedback:pos} \end{figure} \begin{figure}[!htb] \subfloat[B.IV.3: The products I used to buy before using the app achieve high rating in the app.]{ \includegraphics[width=0.28\linewidth]{013_img_qplots_likerts_122.pdf} \label{fig:feedback:awareness:high:before} \begin{picture}(0,0) \put(-115,140){\colorbox{white}{\footnotesize Retailer}} \put(-115,131){\colorbox{white}{\makebox(5,2){ }}} \put(-110,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-102,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-102,125){\colorbox{white}{\makebox(5,4){\hfill }}} \put(-115,129){\colorbox{white}{\footnotesize A}} \put(-82,140){\colorbox{white}{\footnotesize Retailer }} \put(-82,129){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-85,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-65,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-55,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-45,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-35,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-75,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-82,129){\colorbox{white}{\footnotesize B}} \end{picture} }\hfill \subfloat[B.IV.4: The products I used to buy before using the app achieve low rating.]{ \includegraphics[width=0.28\linewidth]{014_img_qplots_likerts_123.pdf} \label{fig:feedback:awareness:lowe:before} }\hfill \subfloat[B.IV.5: The products I will buy in the future are the ones with high rating in the app.]{ \includegraphics[width=0.28\linewidth]{015_img_qplots_likerts_124.pdf} \label{fig:feedback:awareness:high:rating} }\hfill \\ \centering{ \null\hfill \subfloat[B.IV.6: The products I will buy in the future are the ones with low rating in the app.]{ \includegraphics[width=0.28\linewidth]{016_img_qplots_likerts_125.pdf} \label{fig:feedback:awareness:low:rating} }\hfill \subfloat[B.IV.9: I am more aware about sustainability aspects after using the app.]{ \includegraphics[width=0.28\linewidth]{017_img_qplots_likerts_128.pdf} \label{fig:feedback:awareness:awareness} }\hfill\null } \caption{Questions regarding sustainability awareness and future purchases.} \label{fig:feedback:awareness} \end{figure} \begin{figure}[!htb]\subfloat[The rating of the app.]{ \includegraphics[width=0.28\linewidth]{018_img_qplots_likerts_102.pdf} \label{fig:feedback:final:rating} \begin{picture}(0,0) \put(-115,140){\colorbox{white}{\footnotesize Retailer}} \put(-115,131){\colorbox{white}{\makebox(5,2){ }}} \put(-110,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-102,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-102,125){\colorbox{white}{\makebox(5,4){\hfill }}} \put(-115,129){\colorbox{white}{\footnotesize A}} \put(-82,140){\colorbox{white}{\footnotesize Retailer }} \put(-82,129){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-85,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-65,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-55,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-45,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-35,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-75,131){\colorbox{white}{\makebox(5,2){\hfill }}} \put(-82,129){\colorbox{white}{\footnotesize B}} \end{picture} }\hfill \subfloat[The product information I read in the app.]{ \includegraphics[width=0.28\linewidth]{019_img_qplots_likerts_104.pdf} \label{fig:feedback:final:product:info} }\hfill \subfloat[Their price. ]{ \includegraphics[width=0.28\linewidth]{020_img_qplots_likerts_106.pdf} \label{fig:feedback:final:price} } \caption{The products I finally chose during this study are because of:} \label{fig:feedback:final} \end{figure} \begin{figure}[!htb] \centering \includegraphics[width=0.35\linewidth]{021_img_qplots_purchases.pdf} \caption{Estimate the \% of highly rated products you finally bought:} \label{fig:feedback:percentage:bought} \begin{picture}(0,0) \put(30,163){\colorbox{white}{\footnotesize Retailer A}} \put(60,175){\colorbox{white}{\makebox(5,2){\hfill }}} \put(70,175){\colorbox{white}{\makebox(5,2){\hfill }}} \put(80,175){\colorbox{white}{\makebox(5,2){\hfill }}} \put(30,175){\colorbox{white}{\footnotesize Retailer B }} \end{picture} \end{figure} \begin{figure}[!htb] \centering \subfloat[Retailer A.]{ \includegraphics[width=0.429\columnwidth,valign=m]{022_img_paper-plots_price_radial_norm_radial_map_coop.pdf} \label{fig:price:radial:norm:coop} } \hspace{-1.35em} \subfloat[Retailer B.]{ \includegraphics[width=0.429\columnwidth,valign=m]{023_img_paper-plots_price_radial_norm_radial_map_wm.pdf} \label{fig:price:radial:norm:wm} } \hspace{-1.4em} \subfloat{ \includegraphics[width=0.10\columnwidth,valign=m]{024_img_paper-plots_price_radial_colorbar_zero.pdf} }\hfill \caption{Evaluation of mean normalized sustainability index (colorscale) per category across the different price bins per category as denoted in \reftab{tbl:price:bins} for all products of each retailer. } \label{fig:price:radial} \end{figure} \begin{figure} \centering \includegraphics[width=0.8\linewidth]{025_img_paper-plots_rebounds_graph1.pdf} \caption{The distribution of sustainability index per preference for all products in both retailers.\label{fig:si:distro}} \label{fig:si:distro} \end{figure} \begin{figure*}[ht!] \centering \subfloat[Answering the demographics questions in the entry survey.]{\includegraphics[width=0.31\columnwidth]{044_img_app_demographics.png} \label{fig:app:demographics}}\hfill \subfloat[Assigning preference scores.]{\includegraphics[width=0.31\columnwidth]{045_img_app_preferences.png} \label{fig:app:preferences}}\subfloat[Notification for extreme preference scores, which are also explained to the user in the app tutorial.]{\includegraphics[width=0.31\columnwidth]{046_img_app_preferences-extereme.png} \label{fig:app:preferences:extreme} } \caption{Survey and the preference user interfaces of ASSET.} \label{fig:app:usage} \end{figure*} \begin{figure*}[ht!] \subfloat[The main screen of the application.]{\includegraphics[width=0.31\columnwidth]{047_img_app_main.png} \label{fig:facebook:text:clipboard}}\hfill \subfloat[Presenting nearby product categories.]{\includegraphics[width=0.31\columnwidth]{048_img_app_near_cats.png} \label{fig:facebook:text:group}}\hfill \hfill\subfloat[Receiving product ratings.]{\includegraphics[width=0.31\columnwidth]{049_img_app_ratings.png} \label{fig:facebook:text:post}}\hfill \\ \caption{Using the application.} \label{fig:facebook*} \label{fig:app:main} \end{figure*} \begin{figure*}[ht!] \subfloat[The amount a preference contributes to the product rating.]{\includegraphics[width=0.31\columnwidth]{050_img_app_pref_contr.png} \label{fig:contr:pref}}\hfill \subfloat[Product tags that contribute a positive amount to the rating.]{\includegraphics[width=0.31\columnwidth]{051_img_app_pos.png} \label{fig:contr:pos}}\hfill \hfill\subfloat[Product tags that contribute a negative amount to the rating.]{\includegraphics[width=0.31\columnwidth]{052_img_app_neg.png} \label{fig:contr:neg}}\hfill \\ \caption{Preference and product tag contribution to the rating. This feature improves the explainability of the product rating.} \label{fig:contr} \end{figure*} \clearpage \vspace*{1.5cm} \section*{\textbf{Supplementary Tables}} \counterwithin{table}{subsection} \renewcommand{\thetable}{S.\arabic{table}} \setcounter{table}{0} \begin{table}[hb!] \caption{{\bf Environmental Preferences}. The preferences setting options provided in value-sensitive smartphone application. }\label{tbl:preferences:env} \begin{tabularx}{\linewidth}{eXz} \toprule \textbf{Preference} & Description & \textbf{ID} \\ \midrule 1. Products disposed in an environmentally friendly way (e.g. bio-degradable or recyclable packaging) & Products and product packages that can be recycled efficiently or are biodegradable and do not cause environmental hazard when disposed of. & E.1 \\ 2. Products produced and distributed in an environmentally friendly way & A product has a sustainable lifecycle if during manufacturing, distribution, consumption and disposal: it has low CO2 and water footprint, low transportation costs, it can be efficiently recycled and/or biodegradable and produces no waste that is harmful to the environment. Some examples include toxic waste, high CO2 emissions during production, usage of palm oil during production that leads to deforestation etc. & E.2 \\ 3. Sustainably farmed products & Sustainable farming is achieved by a company by applying farming methods such as Integrated Pest Management, No-till agriculture, biodynamic and permaculture. For sea products, aquaculture is preferred instead of free fishing. The countries where the company produces its products should have clear and fair regulations regarding farming and land-management. & E.3 \\ \bottomrule \end{tabularx} \end{table} \begin{table}[hb!] \caption{{\bf Quality Preferences}. The preferences setting options provided in value-sensitive smartphone application.\label{tbl:preferences:qual}} \begin{tabularx}{\linewidth}{eXz} \toprule \textbf{Preference} & Description & \textbf{ID} \\ \midrule 1. Award winning or high quality certified products. & There are several officially recognized organizations that offer awards and/or certifications to companies that produce high-quality products. & Q.1 \\ 2. Fresh products & Fresh products are directly brought from production to the shelves of the supermarket. Fresh products usually tend to be richer in nutrients. Also it is less likely for fresh products to cause health problems to the digestive system. & Q.2 \\ 3. Locally originated and domestic products. & I prefer products that the country of origin is the same as the one I am living in. & Q.3 \\ \bottomrule \end{tabularx} \end{table} \begin{table}[hb!] \caption{{\bf Social Preferences}. The preferences setting options provided in value-sensitive smartphone application.\label{tbl:preferences:social}} \begin{tabularx}{\linewidth}{eXz} \toprule \textbf{Preference} & Description & \textbf{ID} \\ \midrule 1. Products evaluated with auditing processes that rely on sustainability criteria. & All the processes that enhance and enable sustainability should be checked and validated from 3rd parties. Auditing processes based on sustainability criteria support companies in adopting more sustainable processes and also increase their transparency. & S.1 \\ 2. Products from companies that actively contribute to public and social good & I prefer supporting companies, that sponsor charities, scholarships, R\&D, social activities & S.2 \\ 3. Products from companies that support animal rights protection & Brands that respect and support animal rights should avoid factory farming, animal testing and any kind of animal abuse/mistreatment during the production of their products. & S.3 \\ 4. Products from companies that support fairness and equality in the workplace & Brands that treat their workers equally and respect their rights. Such brands should take action against any discrimination between their employees and promote gender and race equality. & S.4 \\ 5. Products from companies with transparent activities & I prefer buying products from companies that are open to sharing the impact and nature of their operation. & S.5 \\ 6. Products from fair trade label companies & Fair trade focuses on human rights in general. Companies should respect human rights and trade with producers in developing and developed countries in a fair manner, offering fair prices for raw materials and not abusing local laws for fair resource sharing, like public water sources, fair land management etc. & S.6 \\ \bottomrule \end{tabularx} \end{table} \begin{table}[hb!] \caption{{\bf Health Preferences}. The preferences setting options provided in value-sensitive smartphone application.\label{tbl:preferences:health}} \begin{tabularx}{\linewidth}{eXz} \toprule \textbf{Preference} & Description & \textbf{ID} \\ \midrule 1. Allergen-free products & Food allergens are typically naturally-occurring proteins in foods or derivatives of them that cause abnormal immune responses. Eight ingredients cause about 90\% of food allergy reactions: Milk (mostly regarding children), Eggs, Peanuts, Tree nuts, like walnuts, almonds, pine nuts, brazil nuts, and pecans, Soy, Wheat and other grains with gluten, including barley, rye, and oats, Fish (mostly in adults), Shellfish (mostly in adults) & H.1 \\ 2. Gluten-free products & A gluten-free diet is a diet that strictly excludes gluten, a mixture of proteins found in wheat and related grains, including barley, rye, oat, and all their species and hybrids (such as spelt, kamut, and triticale). The inclusion of oats in a gluten-free diet remains controversial, and may depend on the oat cultivation and the frequent cross-contamination with other gluten-containing cereals. & H.2 \\ 3. High-protein products & Protein is one of the three macronutrients, along with carbs and fat. It is beneficial for building muscle. Protein serves a number of important functions in your body. It is made up of individual amino-acids, including many that your body cannot create on its own. Protein is the main component of your muscles, bones, skin and hair. These tissues are continuously repaired and replaced with new protein. & H.3 \\ 4. Lactose-free products & A lactose free diet means eating foods that have no lactose. Lactose is a sugar that is a normal part of dairy products. Some people do not break down lactose well. They may not have enough lactase, the enzyme that breaks lactose down in the body. Or, their body may create lactase variants that do not work properly. & H.4 \\ 5. Low fat products & Fats are a type of nutrient that you get from your diet. It's a major source of energy. It helps you absorb some vitamins and minerals. Fat is needed to build cell membranes, the vital exterior of each cell, and the sheaths surrounding nerves. It is essential for blood clotting, muscle movement, and inflammation. It is essential to eat some fats, though it is also harmful to eat too many. For long-term health, some fats are better than others. Good fats include monounsaturated and polyunsaturated fats. Bad ones include industrial-made trans fats. Saturated fats fall somewhere in the middle. Saturated fats raise your LDL (bad) cholesterol level. High LDL cholesterol puts you at risk for heart attack, stroke, and other major health problems. Trans fats can raise LDL cholesterol levels in your blood. They can also lower a person’s HDL (good) cholesterol levels. & H.5 \\ 6. Low salt products & There is also some evidence that too much salt can damage the heart, aorta, and kidneys without increasing blood pressure, and that it may be harmful for bones, too. & H.6 \\ 7. Low sugar products & Added sugar is known to cause heart diseases. Sugar delivers “empty calories” — calories unaccompanied by fiber, vitamins, minerals, and other nutrients. Too much added sugar can replace healthier foods from a person’s diet. & H.7 \\ 8. Products rich in antioxidants & Antioxidants come up frequently in discussions about good health and preventing diseases. Their nature is to prohibit (and in some cases even prevent), the oxidation of other molecules in the body. Oxidation is a chemical reaction that can produce free radicals, leading to chain reactions that may damage cells. The term "antioxidant" is mainly used for two different groups of substances: industrial chemicals which are added to products to prevent oxidation, and natural chemicals found in foods and body tissue which are said to have beneficial health effects. It is often debated whether they actually prevent diseases, which antioxidant(s) are needed from the diet and in what amounts beyond typical dietary intake. & H.8 \\ 9. Products without artificial colours or flavor enhancers. & Artificial colors and flavoring enhancers are used to produce coloring effects and improve food taste. In general these substances are exhaustively tested in labs before they are used in food production. Still, it is not fully determined whether they cause health problems in the long term. & H.9 \\ 10. Products without preservatives & A preservative is a substance or a chemical that is added to products such as food, beverages, pharmaceutical drugs, paints, biological samples, cosmetics, wood, and many other products to prevent decomposition by microbial growth or by undesirable chemical changes. Preservatives are used to prolong the shelf-life of the product but may cause health problems in the long term. & H.10 \\ 11. Products without thickeners, stabilizers or emulsifiers & Emulsifiers allow water and oils to remain mixed together in an emulsion, as in mayonnaise, ice cream, and homogenised milk. Stabilizers, thickeners and gelling agents, like agar or pectin (used in jam for example) give foods a firmer texture. While they are not true emulsifiers, they help to stabilize emulsions. These additives may cause health problems in the long term. & H.11 \\ 12. Vegan products & Vegans choose not to consume dairy, eggs or any other products of animal origin, in addition to not eating meat like the vegetarians. Veganism was originally defined as "the principle of emancipation of animals from exploitation by man." & H.12 \\ 13. Vegetarian products & The Vegetarian Society defines a vegetarian as follows: "A vegetarian is someone who lives on a diet of grains, pulses, legumes, nuts, seeds, vegetables, fruits, fungi, algae, yeast and/or some other non-animal-based foods (e.g. salt) with, or without, dairy products, honey and/or eggs. A vegetarian does not eat foods that consist of, or have been produced with the aid of products consisting of or created from, any part of the body of a living or dead animal. This includes meat, poultry, fish, shellfish*, insects, by-products of slaughter** or any food made with processing aids created from these." & H.13 \\ \bottomrule \end{tabularx} \end{table} \begin{savenotes} \begin{table}[htb!] \centering \caption{An example of association score values and their corresponding meaning. RDA refering to ``Recommended Daily Allowance''~\cite{RDA}. LDL refering to ``Low-density lipoprotein''.} \label{tbl:correlation} \bgroup \def1.15{1.15} \begin{tabular}{C{0.22\linewidth}R{0.18\linewidth}R{0.18\linewidth}R{0.27\linewidth}} \hline association score & product tag \vmath{\pmb\vproducttag} & preference tag \vmath{\pmb\vpreferencetag} & \textbf{Meaning} \\ \hline \vmath{\vcorrelation= 1} & vegetable & vegetarian diet & \vproduct fully supports \vpreference via \vmath{\vproducttag}\\ \vmath{\vcorrelation \in (0, 1)} & 10\% RDA Vitamin C & healthy diet & \vproduct partially supports \vmath{\vpreference} via \vmath{\vproducttag}\\ \vmath{\vcorrelation = 0} & contains sugar & animal rights & \vproducttag is irrelevant to \vmath{\vpreferencetag}\\ \vmath{\vcorrelation \in (-1,0)} & contains LDL & healthy diet &\vpreferencetag partially opposes \vmath{\vproducttag}\\ \vmath{\vcorrelation = -1} & contains eggs & vegan diet &\vpreferencetag fully opposes \vmath{\vproducttag}\\ \hline \end{tabular} \egroup \end{table} \end{savenotes} \clearpage \begin{comment} \section{Literature Overview}\label{sec:related} Several platforms and services provide sustainability ratings for products or companies\cite{chatterji2009well}. A sample of these sources is listed in \reftab{tbl:online:ratings}. The sector scope is usually general and includes different types of product categories, from household cleaners to electronics. Sustainability ratings often target brands and companies, but product ratings are also common. Still, a lack of generalized methodologies that apply to any sector scope and/or target is observed. In terms of rating computation, the majority of proposed solutions rely on expert ratings, that often cannot guarantee transparency by design. The main focus of several sustainability ratings lies on environmental and social criteria, while health and ethical criteria are also often used. There seems to be no generalized methodology that allows the extension of sustainability ratings with new sustainability criteria. Finally, most ratings are represented in ordinal scale, with limited information on how these ratings can be aggregated for a robust statistical analysis. Most rating websites rely on Environmental Social Governance (ESG) analyses, Corporate Social Reports (CSR), expert knowledge, or crowdsourcing. Often enough, the main focus of sustainability rating apps are environmental and social factors~\cite{nghiem2016mobile}. Other studies may also focus on the predictive capability of using sustainability ratings as the basis of recommender systems~\cite{tomkins2018sustainability}. The majority of rating methodologies focuses on the brand level and relies on expert input. Only, a small fraction of these rating algorithms enables personalization, which allow the users to decide which sustainability factors should affect the ratings the most and how much. In particular until 2017, Ethical Consumer\cite{ethicalconsumer} allowed registered users to score factors, on a continuous sustainability scale. The Green Stars Project\cite{greenstars} allows users to conduct reviews and assign a score to products according to their own preferences and opinions. A Green Stars report can be posted to a website or service, such as Yelp or Google reviews, allowing the users to provide sustainability reports without restrictions. The project owner provides a list of guidelines on how to write such reviews. WikiRate focuses on the collection of sustainability data based on reports or claims made by a community or by experts. Such reports may suggest possible evaluation metrics for different sustainability aspects. The users of WikiRate\cite{wikirate} can either use existing metrics or create a custom implementation over those metrics. Therefore users with different interests follow different metrics and are exposed to information relevant to their interests\cite{mills2018situativity}. In WikiRate, distributed and even decentralized rating implementations are also possible, as WikiRate data for rating calculations or sustainability reporting can be accessed and stored locally via its API. \end{comment} \begin{table*}[!htb] \caption{\textbf{Alternative approaches.} Overview of online sources that provide sustainability ratings. Most of these approaches limit their scope to evaluation of brands rather than a broad spectrum of products. They are online web approaches with limited integration to shopping processes in retailer shops. Explainability is not explicitly provided and data may only be collected in a centralized fashion. They do not always capture a broad spectrum of sustainability goals. No rigorous evaluation with field studies has been shown how they impact sustainable consumption. } \label{tbl:online:ratings} \begin{tabularx}{\linewidth}{qqeqqe} \toprule Organization & Sector Scope & Target & Computation & Main Focus & Rating Type \\ \midrule rankabrand\cite{rankabrand} & General & Brand & Crowdsourced & Environment, Social and Health & Ordinal \\ GoodGuide\textregistered\cite{goodguide} & Personal Care, Household Supplies, Babies and Kids products & Product & Ingredient analysis based on official regulations & Environment and Health & Continuous \\ Shop Ethical!\cite{shopethical} & General & Brand & Screening and reports for praises and/or criticism towards companies based on expert weighting & Social and Environmental & Ordinal \\ THE GOOD SHOPPING GUIDE\cite{goodshopping} & General & Companies, Brands & Qualitative and quantitative evaluation based on expert criteria. & Environment, Animals, People, Ethical and Other Factors & Ordinal \\ The Green Stars Project\cite{greenstars} & General & Companies, Brands, Services, Products etc. & User based reviews and rating assignment & Social and Environmental & Ordinal \\ WikiRate\cite{wikirate} & General & Company & Allows for implementation of any rating based on the data the website offers & Environmental, Social and Governmental Concerns & Any \\ Behind the Brands\cite{behindthebrands} & Food & Brand & Expert based & Social, Environmental and Ethical & Continuous, ordinal \\ \bottomrule \end{tabularx} \end{table*} \begin{comment} Each methodology of \reftab{tbl:online:ratings} has different capabilities and drawbacks. The majority of those methodologies lacks a transparent and formalized description of the rating methodology\cite{nghiem2016mobile}. However, transparency is needed to validate and evaluate the rating methodology, the required sustainability standards and proposed evaluation metrics\cite{mills2018situativity, chatterji2009well, delmas2010measuring}. Intransparent rating calculations obfuscate for designer bias, which can imply inaccurate ratings. Such ratings often create misconceptions regarding sustainable activities of brands and companies~\cite{kwon2016third} and also enable nudging effects\cite{lehner2016nudging}. Furthermore, rating control via design choices or personalization is also a consideration in most rating methodologies, especially when users can have different interpretations for different values of a rating scale\cite{parguel2011sustainability, kwon2016third}. Any bias introduced during the rating design can be reduced by allowing users to personalize the ratings they get, as the personalization mechanism can shift rating values to match user perception. The evaluation of sustainability ratings is usually done by experts or relies on recommender system criteria\cite{tomkins2018sustainability}. Shopping behavior and sustainability preferences of consumers can be evaluated by developing mobile application that use sustainability ratings creates the opportunity to conduct field tests~\cite{bhattacharya2012ma}. \end{comment} \begin{table}[hb!] \caption{\textbf{Data Sources}. The data sources used for the construction of the used ontology. Websites accessed on January 2020.} \label{tbl:impl:data-sources} \begin{tabularx}{\columnwidth}{fXa} \toprule \textbf{Source Type} & \textbf{Institute} & \textbf{Website} \\ \midrule \multirow{2}{*}{\shortstack[l]{Retailer\\Database}} & Coop Estonia & \url{coop.ee} \\ & Winkler Markt & \url{www.winklermarkt.at} \\ \cline{2-3} \multirow{2}{*}{\shortstack[l]{Online\\Datastores}} & GS1 & \url{gs1.org} \\ & ecoinvent & \url{ecoinvent.org} \\ \cline{2-3} \multirow{6}{*}{Experts} & AINIA & \url{ainia.es} \\ & BIA & \url{bia.ee} \\ & ETH & \url{ethz.ch} \\ & Ethical Consumer Workshop 2017 & \url{ethicalconsumer.org}\\ & LCM & \url{lcm.at} \\ & VKI & \url{vki.at} \\ \cline{2-3} \multirow{2}{*}{Crowdsourcing} & Wikipedia & \url{wikipedia.org} \\ & Social Impact Data Hack & \url{sidh2017.ut.ee} \\ \bottomrule \end{tabularx} \end{table} \begin{table}[ht!] \centering \caption{Approximate confidence intervals and error margins calculated based on available sample size. The population size for the calculations is estimated as the average number of loyalty card visitors per month .} \label{tbl:surveys:part} \footnotesize \begin{tabularx}{0.5\columnwidth}{Xrr} \toprule \textbf{Retailer} & \textbf{Survey} & \textbf{\# Users} \\ \midrule \multirow{3}{=}{Retailer A} & Entry & 323 \\ & Exit & 44 \\ & Preferences & 315\\ \cline{1-3} \multirow{3}{=}{Winkler Markt} & Entry & 69 \\ & Exit & 12 \\ & Preferences & 66 \\ \bottomrule \end{tabularx} \end{table} \begin{table}[!htb] \caption{\textbf{Causal Impact Analysis}. Best \vmath{k\text{NN}} matches for treatment group selected on the DTW euclidean distance on high mean rating products weekly expenditure. The control group is selected by using covariates for matching between users. Since different values of \vmath{k} result in different control group per combination of criteria the best value of \vmath{k} is selected via a dynamic time warping of weekly expenditure before treatment. The warping window size is \vmath{1}, meaning that the algorithm searches 1 week before or after to match the expenditure of the current weekly expenditure between control and treatment. } \label{tbl:distance:explanations} \begin{tabularx}{\columnwidth}{XYYYee} \toprule Retailer & Monthly Total Expenditure & \raggedright{Distribution of Monthly Expenditure per Category} & Monthly Representations & Distance & \vmath{k} \\ \midrule \multirow{7}{=}{retailer A} & - & - & \checkmark & 0.030852 & 5 \\ & - & \checkmark & - & 0.037871 & 5 \\ & - & \checkmark & \checkmark & 0.032995 & 2 \\ & \checkmark & - & - & 0.032736 & 4 \\ & \checkmark & - & \checkmark & 0.033386 & 5 \\ & \checkmark & \checkmark & - & 0.033722 & 2 \\ & \checkmark & \checkmark & \checkmark & 0.035229 & 4 \\ \cline{1-6} \multirow{6}{=}{retailer B} & - & \checkmark & - & 0.056523 & 1 \\ & - & \checkmark & \checkmark & 0.061028 & 2 \\ & \checkmark & - & - & 0.066083 & 2 \\ & \checkmark & - & \checkmark & 0.055792 & 2 \\ & \checkmark & \checkmark & - & 0.061923 & 1 \\ & \checkmark & \checkmark & \checkmark & 0.059597 & 2 \\ \bottomrule \end{tabularx} \end{table} \begin{table}[htb!] \caption{The summary of the causal impact analysis for Retailer A and Retailer A users. The reported decimal values in the table are rounded.} \label{table:causal-impact} \footnotesize{ {\setlength{\extrarowheight}{1pt}\begin{tabularx}{\linewidth}{X>{\hsize=1.03\hsize}X>{\hsize=0.5\hsize}y>{\hsize=0.5\hsize}yy>{\hsize=0.5\hsize}y>{\hsize=0.5\hsize}yya} \toprule \multirow{2}{=}{\textbf{Retailer}} & & \multicolumn{3}{>{\hsize=3\hsize}X}{\centering{\textbf{Average}}} & \multicolumn{3}{>{\hsize=3\hsize}X}{\centering{\textbf{Cumulative}}} & \multirow{2}{=}{\vmath{p}} \\ & & value & s.d. & \vmath{95\%} c.i. & value & s.d. & \vmath{95\%} c.i. & \\ \midrule \multirow{3}{=}{A} & Actual & \vmath{0.8} & - & - & \vmath{14.7} & - & - & \multirow{3}{=}{\vmath{\leq 0.001}} \\ & Prediction & \vmath{0.6} & \vmath{0.0} & \vmath{[0.5,\ 0.6]} & \vmath{10.8} & \vmath{0.3} & \vmath{[10.1,\ 11.4]} & \\ & Absolute Effect & \vmath{0.2} & \vmath{0.0} & \vmath{[0.2,\ 0.2]} & \vmath{4.0} & \vmath{0.3} & \vmath{[3.3,\ 4.6]} & \\ & Relative Effect & \vmath{36.7\%} & \vmath{3.1\%} & \vmath{[30.7\%,\ 42.8\%]} & - & - & - & \\ \cline{1-9} \multirow{3}{=}{B} & Actual & \vmath{0.6} & - & - & \vmath{10.1} & - & - & \multirow{3}{=}{\vmath{\leq 0.001}} \\ & Prediction & \vmath{0.4} & \vmath{0.0} & \vmath{[0.3,\ 0.5]} & \vmath{7.1} & \vmath{0.8} & \vmath{[5.4,\ 8.7]} & \\ & Absolute Effect & \vmath{0.2} & 0.0 & \vmath{[0.1,\ 0.3]} & 2.9 & 0.8 & \vmath{[1.4,\ 4.7]} & \\ & Relative Effect & \vmath{41.0\%} & \vmath{11.8\%} & \vmath{[19.2\%,\ 65.4\%]} & - & - & - & \\ \bottomrule \end{tabularx} }} \end{table} \clearpage \begin{table}[htbp] \centering \caption{The price bins used for classifying a product according to its price per unit in \reffig{fig:price:radial}. Each product price is compared against prices of other products in the same category. Package specific quantities are not taken into account.} \label{tbl:price:bins} \begin{tabularx}{\columnwidth}{eXX} \toprule Label & Normalized Price Range & Description \\ \midrule B1 & \vmath{(0, 0.33)} & The \vmath{33\%} of lowest product prices in category \\ B2 & \vmath{(0.33, 0.66)} & Between \vmath{33\%} and \vmath{66\%} product prices\\ B3 & \vmath{(0.66, 1)} & The \vmath{66\%} and \vmath{100\%} of highest product prices in category \\ \bottomrule \end{tabularx} \end{table} \begin{table}[!htb] \caption{(Max-Min) Normalized price per category and normalized sustainability index for retailer A. Relevant to \reffig{fig:price:radial:norm:coop}.} \label{tbl:price:corr:coop:norm} \footnotesize \begin{tabularx}{\linewidth}{yyy} \toprule Preference & Correlation & p-value \\ \midrule E.1 & 0.03 & 0.21 \\ E.2 & -0.08 & 0.00 \\ \textsuperscript{+}E.3 & 0.10 & 0.00 \\ H.1 & 0.09 & 0.70 \\ H.2 & 1.00 & - \\ H.3 & -0.05 & 0.47 \\ H.4 & - & - \\ H.5 & -0.02 & 0.21 \\ H.6 & -0.03 & 0.17 \\ H.7 & -0.04 & 0.12 \\ H.8 & - & - \\ \textsuperscript{-}H.9 & -0.10 & 0.01 \\ H.10 & 0.14 & 0.23 \\ H.11 & 0.03 & 0.74 \\ \textsuperscript{-}H.12 & -0.88 & 0.02 \\ H.13 & 0.13 & 0.11 \\ Q.1 & - & - \\ Q.2 & - & - \\ \textsuperscript{+}Q.3 & 0.12 & 0.01 \\ S.1 & - & - \\ S.2 & - & - \\ S.3 & 0.00 & 0.81 \\ S.4 & -0.05 & 0.00 \\ S.5 & 0.02 & 0.21 \\ S.6 & 0.07 & 0.00 \\ \bottomrule \end{tabularx} \end{table} \begin{table}[t] \caption{(Max-Min) Normalized price per category and normalized sustainability index for retailer B. Relevant to \reffig{fig:price:radial:norm:wm}.} \label{tbl:price:corr:wm:norm} \footnotesize \begin{tabularx}{\linewidth}{yyy} \toprule Preference & Correlation & p-value \\ \midrule E.1 & -0.03 & 0.03 \\ \textsuperscript{-}E.2 & -0.17 & 0.00 \\ \textsuperscript{-}E.3 & -0.34 & 0.00 \\ \textsuperscript{+}H.1 & 0.23 & 0.00 \\ \textsuperscript{+}H.2 & 0.22 & 0.00 \\ H.3 & 0.02 & 0.92 \\ H.4 & 0.09 & 0.00 \\ H.5 & -0.09 & 0.00 \\ \textsuperscript{+}H.6 & 0.12 & 0.00 \\ H.7 & -0.01 & 0.59 \\ H.8 & - & - \\ H.9 & -0.03 & 0.15 \\ \textsuperscript{+}H.10 & 0.40 & 0.02 \\ H.11 & 0.01 & 0.78 \\ \textsuperscript{+}H.12 & 0.17 & 0.00 \\ \textsuperscript{+}H.13 & 0.20 & 0.00 \\ Q.1 & - & - \\ Q.2 & - & - \\ Q.3 & - & - \\ \textsuperscript{-}S.1 & -0.30 & 0.00 \\ S.2 & - & - \\ \textsuperscript{+}S.3 & 0.29 & 0.00 \\ \textsuperscript{+}S.4 & 0.22 & 0.00 \\ \textsuperscript{+}S.5 & 0.35 & 0.00 \\ S.6 & -0.08 & 0.05 \\ \bottomrule \end{tabularx} \end{table} \clearpage \vspace*{1cm} \section*{\textbf{Supplementary Methods}} \renewcommand\thesubsection{SM.\arabic{subsection}} \renewcommand\thesubsubsection{SM.\arabic{subsection}.\arabic{subsubsection}} \subsection{\textbf{Ontology}}\label{sec:ontology} In the used product ontology, product characteristics are summarized in the form of words or phrases, the \textbf{product tags}. Each product tag \vmath{\vproducttag} can be assigned to one or more products and it summarizes concepts and characteristics of a product \vmath{\vproduct}. Every product \vmath{\vproduct} can be assigned to multiple product tags. The set of all product tags denotes the semantic space of product characteristics. Product tags are generated based on the data available from the data sources. For example \vmath{\vproduct=\text{"cabbage"}} is associated with the product tag \vmath{\vproducttag=\text{"vegetable"}}. The consumer preferences (see Table~\ref{tbl:preferences:env}-\ref{tbl:preferences:health}) are also represented in the consumer preference ontology. Several challenges arise when defining an universal golden standard regarding a sustainable consumption behavior. Therefore, a personalized view on sustainable consumption is evaluated per consumer. Each preference is presented to the consumer in form of a statement \vmath{\vpreference}. Each statement is accompanied by a description that explains the sustainability concepts composing this preference, e.g. \vmath{\vpreference=\text{"I prefer vegan products.".}} A consumer \vmath{\vuser} then assigns numerical values to each preference statement \vmath{\vpreference}, to express support, opposition or neutrality towards the preference statement. This numerical value is referred to as preference score \vmath{\vpreferencescore}. The preference score is bound in the range of \vmath{\left[0, 2\cdot\vmean{\vprefscore}\right]}, where \vmean{\vprefscore} is the mean value of the range. The minimum value of the score implies that a consumer fully opposes a sustainability preference. The maximum value implies fully supports a sustainability preferences. The mean value of the scale implies no consumer preference regarding a sustainability criterion. An assigned preference score is stored in the device of a consumer \vmath{\vuser}, and represents personalization. The rating system calculates the product rating \vmath{\vrating{\vproduct}{\vuser}} for a given product \vmath{\vproduct} and a consumer \vmath{\vuser} based on the preference scores. The introduced method extends the semantic differential methodology for evaluating associations of product characteristics and sustainability preferences\cite{helbing2010quantitative, osgood1957measurement}. Preference statements usually express \vchal{abstract} complex sustainability aspects. These aspects are decomposed into simpler ones creating a hierarchical ontology. A word or phrase, referred to as preference tag \vmath{\vpreferencetag}, represents an aspect of a preference statement. For example, \vmath{\vpreference =} "I prefer products that can be disposed in a sustainable manner." is composed by two sustainability preference tags: \vmath{\vpreferencetag_1=\text{"biodegradability"}}, which is the ability of the product to dissolve within an acceptable time and without harming the environment \cite{goswami2016developments}, and \vmath{\vpreferencetag_2=\text{"recycling capability"}}, which denotes whether a product can be recycled in an efficient and environmentally friendly way \cite{villalba2002proposal}. In other words, a preference tag \vmath{\vpreferencetag \in \toSet{\Omega}_{\vpreference}}, which belongs to a preference tag set \vmath{\toSet{\Omega}_{\vpreference}} of a preference \vmath{\vpreference}, compresses and represents information regarding the concepts that compose the preference statement \vmath{\vpreference}. The main challenge of designing an ontology for a sustainable consumption ontology is to define quantifiable associations between the semantic spaces of product tags and preference tags. To enable numerical calculation for product ratings we use the ontological design as sketched in \reffig{fig:prod:rating:ontology}. Several ontological connections are introduced to calculate the aggregate support or opposition of a product to a consumer's preferences. The ontology of sustainability concepts has hierarchical structures of concepts~\cite{Rodriguez2003}, where one concept is composed of several other concepts \vmath{q \in \toSet{Q}}. If it is not feasible to further decompose a concept, then such a concept is referred to as a \textit{primitive concept}\footnote{The definition of primitive concepts serves more as a theoretical tool, with which the scope of the sustainability can be determined.}. A \textbf{semantic association framework} introduces a logic for quantifiable semantic associations between a product tag \vmath{\vproducttag} and a preference tag \vmath{\vpreferencetag}. Examples of such associations can be found on \reftab{tbl:correlation}. The associations between tags are quantified in a shared semantic space \toSet{Q}, which contains all concepts relevant to products and sustainability preferences. The space is defined with the following two assumptions: \begin{enumerate} \item The individual elements of this space are \textit{primitive concepts} that cannot be decomposed into other concepts within the defined sustainability scope. \item Complex concepts are represented as sets that contain all the \textit{primitive concepts} that compose them. For instance, the preference tag \vmath{\vpreferencetag=\text{"vegan"}} may be decomposed to the set \vmath{\toSet{Q}_{\vpreferencetag} = \{}"no animals involved in production", "no animal products involved in production", \vmath{\ldots\}} where \vmath{\toSet{Q}_{\vpreferencetag} \subseteq \toSet{Q}}. \end{enumerate} Suppose a product tag expresses one or more \textit{primitive concepts}. The set of those concepts is defined as \vmath{\toSet{Q}_{\vproducttag} \subseteq \toSet{Q}}. Following the same logic, let a preference that its existence is denoted by the union of \textit{primitive concepts} such as \vmath{\toSet{Q}_{\vpreferencetag}^{+}}. An association between the product and the preference tag is defined as the overlap between the \textit{primitive concepts} that each tag represents \vmath{\toSet{Q}_\vproducttag \cap \toSet{Q}_{\vpreferencetag}^{+}} as shown in \reffig{fig:association}. This overlap is maximized when all \textit{primitive concepts} that compose the preference tag also compose the product tag. The following positive association score is defined: \begin{equation} \label{eq:pos_association} r^{+}(\vproducttag, \vpreferencetag) = \dfrac{\absol{\toSet{Q}_\vproducttag \cap \toSet{Q}_{\vpreferencetag}^{+}}}{\absol{\toSet{Q}_{\vpreferencetag}^{+}}} \end{equation} The score is bounded, since: \begin{equation} \label{eq:pos:bound} \toSet{Q}_\vproducttag \cap \toSet{Q}_{\vpreferencetag}^{+} \subseteq \toSet{Q}_{\vpreferencetag}^{+} \Leftrightarrow r^{+}\left (\vproducttag, \vpreferencetag\right) \in \left[0,1\right] \end{equation} For example, let a product tag and the relevant \textit{primitive concepts}: \vmath{\vproducttag=}"vegetable" with \vmath{\toSet{Q}_\vproducttag=\{}"minimal CO\textsubscript{2} footprint", "plant part", "not animal product"\vmath{\}}. Suppose the following two preference tags, which are decomposed to \textit{primitive concepts}, \vmath{\vpreferencetag_1=}"vegetarian diet" with \vmath{\toSet{Q}_{\vpreferencetag1}=\{}"plant part", "not animal product"\vmath{\}} and \vmath{\vpreferencetag_2=}"sustainable production" \vmath{\toSet{Q}_{\vpreferencetag2}=\{}"minimal CO\textsubscript{2} footprint", "minimal water footprint", "no toxic waste"\vmath{\}}. The "vegetable" product tag is composed of concepts which are enough to guarantee a "vegetarian diet". Yet, the "vegetable" product tag is composed of some but not all of the concepts that guarantee a sustainable production. A product tag may oppose the existence of a preference tag concept. For example the concept of "animal product" in food, fully opposes a "vegan diet" preference. When a product contains animal products, then it is definitely not vegan. Partial opposition is also possible, as for example the concept "contains lactose" indicates that a product probably contains animal products, as lactose is a protein mainly found in milk\cite{Kretchmer1972}. Therefore, the need to define opposite associations arises. The negative \textit{primitive concepts} of a preference tag are defined as a set \vmath{\toSet{Q}_\vpreferencetag^{\scriptstyle{-}}}. For that, an association is defined when the concept in a product tag is mutually exclusive with concepts defining a preference tag. In this case a negative association score evaluates the overlap of concepts belonging to the set of simple concepts of the product tag \vmath{\toSet{Q}_{\vproducttag} \cap \toSet{Q}_\vpreferencetag^{\scriptstyle{-}}}. The negative association score is defined as: \begin{equation} \label{eq:neg_association} r^{-}(\vproducttag, \vpreferencetag) = \dfrac{\absol{\toSet{Q}_{\vproducttag} \cap \toSet{Q}_\vpreferencetag^{\scriptstyle{-}}}}{\absol{\toSet{Q}_\vpreferencetag^{\scriptstyle{-}}}} \end{equation} The negative score is also bounded, since: \begin{equation} \label{eq:neg:bound} \toSet{Q}_\vproducttag \cap \toSet{Q}_{\vpreferencetag}^{-} \subseteq \toSet{Q}_{\vpreferencetag}^{-} \Leftrightarrow r^{-}\left (\vproducttag, \vpreferencetag\right) \in \left[0,1\right] \end{equation} The preference tag is defined by the union of its negative and positive concepts \vmath{\toSet{Q}_{\vpreferencetag} = \toSet{Q}_\vpreferencetag^+ \cup \toSet{Q}_\vpreferencetag^-} as shown in \reffig{fig:preference:concepts}. E.g. the preference tag \vmath{\vpreferencetag=}"vegan" can be decomposed to the supporting \textit{primitive concepts} \vmath{\toSet{Q}_\vpreferencetag^{+}=}"plant part". Product tags that contain \textit{primitive concepts} that both oppose and support a preference tag are also possible. In such case, the sum of positive and negative scores is calculated. For this calculation, it is assumed that positive simple concepts cancel out negative concepts and vice versa. The association score between a product tag and a preference tag is defined as: \begin{equation} \label{eq:total_association} \vcorrelation = r^{+}(\vproducttag, \vpreferencetag) - r^{-}(\vproducttag, \vpreferencetag) \stackrel{\ref{eq:pos:bound}, \ref{eq:neg:bound}, \ref{eq:total_association}}{\Leftrightarrow} \vcorrelation \in \left[-1, 1\right] \end{equation} This is denoted as the \textbf{individual bounding property} of the score and applies to all association scores between any product and preference tags. A product is often related to a set of product tags \vmath{\toSet{\vproducttag}_{\vproduct}}, therefore it can be represented by the union of all \textit{primitive concepts} of these tags: \begin{equation} \label{eq:sets:union} \toSet{Q}_{\vproduct} = \bigcup_{z \in \toSet{\vproducttag}_{\vproduct}}\toSet{Q}_{\vproducttag} \end{equation} An example of how a product \vmath{\vproduct} is decomposed to the \textit{primitive concepts} of the product tags it consists of is found in \reffig{fig:product:concept}. In practice, the calculation of the association score is performed by knowledge systems that rely on (i) expert knowledge, (ii) crowdsourcing and (iii) machine learning. As illustrated on line 4 in \reftab{tbl:correlation}, the products that contain high quantities of LDL, oppose the preference tag "healthy diet", e.g.\ the health of the cardiovascular system\cite{Miller1975}. This is quantified via a negative association score value in the range \vmath{\left(-1, 0\right)}. The negative threshold value is assigned to the "contains eggs" product tag, which fully opposes the "vegan" preference tag, as shown on row 5 of \reftab{tbl:correlation}. Associations between products \vmath{\vproduct} and preference tags are calculated by an aggregated association score \vmath{\vrelevance}. According to \refeq{eq:sets:union}, the intersection between all \textit{primitive concepts} related to a product and a preference tag is used for such calculation: \begin{equation}\label{eq:relevance:agg} \vrelevance = \dfrac{\absol{{\toSet{Q}_{\vproduct}}\cap\toSet{Q}_{\vpreferencetag}^{+}}} {\absol{\toSet{Q}_{\vpreferencetag}^{+}}} - \dfrac{\absol{{\toSet{Q}_{\vproduct}}\cap\toSet{Q}_{\vpreferencetag}^{-}}} {\absol{\toSet{Q}_{\vpreferencetag}^{-}}} \stackrel{\refeq{eq:sets:union}}{\Leftrightarrow{}} \end{equation} Note that, it is challenging to assign \textit{primitive concepts} directly to products. A fixed sustainability scope supports the identification of overlaps and the existence of primitive concepts. The definition of primitive concepts is challenging when the ontology is under construction and the sustainability scope is not fixed. Conceptual overlaps are common in real world scenarios where product tags are usually derived from labels or certifications, which are related to several \textit{primitive concepts}, e.g.the fair trade label. Intersection between a product tag and a preference tag \vmath{\vcorrelation} quantifies their shared semantic space, consisting of at least one primitive concept. The individual intersections between product tags and preference tags \vmath{\vcorrelation} can be used for the approximation of the aggregated association \vmath{\vrelevance}. The number of available product tags is considerably lower than the number of products worldwide. When the product tags share \textit{primitive concepts}, it may prove challenging to calculate this intersection, especially when the \textit{primitive concepts} are not identified. Shared product tag \textit{primitive concepts} introduce overlaps between intersections of different product tags and a preference tag. Such overlaps introduce an error \vmath{\epsilon} in the approximation of the aggregate associations \vmath{\vrelevance}. Reducing the overlaps between product tags of the same product, minimizes this error, as shown in \textit{Lemma} \ref{lemm:errors}. \begin{lemma}\label{lemm:errors} The aggregated association \vmath{\vrelevance} between a product \vmath{\vproduct} and a preference tag \vmath{\vpreferencetag} is approximated with error \vmath{\epsilon} by the sum of tag associations \vmath{\vcorrelation} of each related product tag \vmath{\vproducttag \in \toSet{\vproducttag}_{\vproduct}} with the preference tag \vmath{\vpreferencetag}, assuming that the \textit{primitive concept} overlaps between product tags are minimized \vmath{\bigcap_{z\in\toSet{\vproducttag}_\vproduct}\toSet{Q}_{\vproducttag } \to 0}, such that \vmath{\epsilon \to 0}. \end{lemma} \begin{proof} A product is defined as the union of associated \textit{primitive concepts} that product tags represent. Therefore the aggregated association for \vmath{\vproducttag \in \toSet{\vproducttag}_{\vproduct}} is: \begin{equation} \label{eq:association:1} \begin{gathered} \vrelevance = \dfrac{\absol{{\toSet{Q}_{\vproduct}}\cap\toSet{Q}_{\vpreferencetag}^{+}}} {\absol{\toSet{Q}_{\vpreferencetag}^{+}}} - \dfrac{\absol{{\toSet{Q}_{\vproduct}}\cap\toSet{Q}_{\vpreferencetag}^{-}}} {\absol{\toSet{Q}_{\vpreferencetag}^{-}}} \stackrel{\refeq{eq:sets:union}}{\Leftrightarrow{}} \\ \vrelevance = \dfrac{\absol{\left(\bigcup_{z} \toSet{Q}_{\vproducttag}\right)\cap\toSet{Q}_{\vpreferencetag}^{+}}} {\absol{\toSet{Q}_{\vpreferencetag}^{+}}} - \dfrac{\absol{\left(\bigcup_{z}\toSet{Q}_{\vproducttag}\right)\cap\toSet{Q}_{\vpreferencetag}^{-}}} {\absol{\toSet{Q}_{\vpreferencetag}^{-}}} \Leftrightarrow{} \\ \vrelevance = \dfrac{\absol{\bigcup_{\vproducttag}\left (\toSet{Q}_{\vproducttag}\cap\toSet{Q}_{\vpreferencetag}^{+}\right)}} {\absol{\toSet{Q}_{\vpreferencetag}^{+}}} - \dfrac{\absol{\bigcup_{\vproducttag}\left(\toSet{Q}_{\vproducttag}\cap\toSet{Q}_{\vpreferencetag}^{-}\right)}} {\absol{\toSet{Q}_{\vpreferencetag}^{-}}} \\ \end{gathered} \end{equation} Each nominator can be further analyzed using the general form of the Inclusion-Exclusion principle\cite{rota1964foundations}. The first fraction nominator is expanded as, for any subset of product tags \vmath{\emptyset\neq\toSet{\vproducttag}_{\vproduct}'\subseteq\toSet{\vproducttag}_{\vproduct}}, and then all intersection between a preference tag and more than one product are isolated to determine overlaps: \begin{equation} \label{eq:association:2} \begin{aligned} \absol{\bigcup_{\vproducttag}\left(\toSet{Q}_{\vproducttag}\cap\toSet{Q}_{\vpreferencetag}^{+}\right)} &= \sum_{\emptyset\neq\toSet{\vproducttag}_{\vproduct}'\subseteq\toSet{\vproducttag}_{\vproduct }} \left[(-1)^{\absol{\toSet{\vproducttag}_{\vproduct}'}-1} \biggl|\bigcap_{\vproducttag\in\toSet{\vproducttag}_\vproduct'} \toSet{Q}_{\vproducttag}\cap\toSet{Q}_\vpreferencetag^{+} \biggr| \right] \\ &= \sum_{\vproducttag\in\toSet{\vproducttag}_{\vproduct}}\absol{\toSet{Q}_{\vproducttag} \cap \toSet{Q}_\vpreferencetag^{+} } \\ &+ \underbrace{\sum_{\substack{\absol{\toSet{\vproducttag}_{\vproduct}'}>1\\ \toSet{\vproducttag}_{\vproduct }'\subseteq \toSet{\vproducttag}_{\vproduct}}} \left[ (-1)^{\absol{\toSet{\vproducttag}_{\vproduct}'}-1} \biggl|\bigcap_{\vproducttag\in\toSet{\vproducttag}_\vproduct'} \toSet{Q}_{\vproducttag}\cap\toSet{Q}_\vpreferencetag^{+} \biggr| \right]}_{\epsilon^{+}} \\ \end{aligned} \end{equation} Thus: \begin{equation} \label{eq:overlap:error:pos} \absol{\bigcup_{\vproducttag}\left(\toSet{Q}_{\vproducttag}\cap\toSet{Q}_{\vpreferencetag}^{+}\right)} = \sum_{\vproducttag\in\toSet{\vproducttag}_{\vproduct}}\absol{\toSet{Q}_{\vproducttag} \cap \toSet{Q}_\vpreferencetag^{+} } + \epsilon^{+} \end{equation} Respectively it is shown that: \begin{equation} \label{eq:overlap:error:neg} \absol{\bigcup_{\vproducttag}\left(\toSet{Q}_{\vproducttag}\cap\toSet{Q}_{\vpreferencetag}^{-}\right)} = \sum_{\vproducttag\in\toSet{\vproducttag}_{\vproduct}}\absol{\toSet{Q}_{\vproducttag} \cap \toSet{Q}_\vpreferencetag^{-} } + \epsilon^{-} \end{equation} The terms \vmath{\epsilon^+} and \vmath{\epsilon^-} are the overlap correction terms introduced by the Inclusion-Exclusion principle. These terms express the semantic overlap between different product tags of a product and a single preference tag. Therefore, it is possible now to expand \textit{Relation} \ref{eq:association:1}: \begin{equation} \label{eq:association} \begin{gathered} \vrelevance = \dfrac{\sum_{z}{\absol{\toSet{Q}_z\cap\toSet{Q}_{\vpreferencetag}^{+}}} + \epsilon^{+} } {\absol{\toSet{Q}_{\vpreferencetag}^{+}}} - \dfrac{\sum_{z}{\absol{\toSet{Q}_z\cap\toSet{Q}_{\vpreferencetag}^{-}}} + \epsilon^{-}} {\absol{\toSet{Q}_{\vpreferencetag}^{-}}} \stackrel{\textit{Eq.}~\ref{eq:pos_association}~\&~\ref{eq:neg_association}}{\Leftrightarrow{}} \\ \vrelevance = \sum_{z}{r^{+}(\vproducttag, \vpreferencetag)} - \sum_{z}{r^{-}(\vproducttag, \vpreferencetag)} + \epsilon \stackrel{\textit{Eq.}~\ref{eq:total_association}}{\Leftrightarrow{}} \\ \vrelevance = \sum_{z}{\vcorrelation} + \epsilon \end{gathered} \end{equation} where: \begin{equation} \label{eq:overlap:error} \begin{gathered} \epsilon = \dfrac{\epsilon^{+}}{\absol{\toSet{Q}_{\vpreferencetag}^{+}}} + \dfrac{\epsilon^{-}}{\absol{\toSet{Q}_{\vpreferencetag}^{-}}} \end{gathered} \end{equation} Since the intersection between sets is a commutative operation, it can be derived from \refeq{eq:association:2} that: \begin{equation} \biggl|\bigcap_{\vproducttag\in\toSet{\vproducttag}_\vproduct'} \toSet{Q}_{\vproducttag}\cap\toSet{Q}_\vpreferencetag^{+} \biggr| = \biggl|\toSet{Q}_\vpreferencetag^{+} \cap \left(\bigcap_{\vproducttag\in\toSet{\vproducttag}_\vproduct'} \toSet{Q}_{\vproducttag} \right) \biggr| \end{equation} \textit{Equations} \ref{eq:association:2}, \ref{eq:overlap:error:pos} and \ref{eq:overlap:error:neg} show that if the overlaps \vmath{\bigcap_{z\in\toSet{\vproducttag}_\vproduct}\toSet{Q}_{\vproducttag} \to 0} between product tags are minimized then \vmath{\epsilon^{+}, \epsilon^{-} \to 0 \Rightarrow \epsilon \to 0}. Thus the lemma is proved. \end{proof} For example assume the product \vmath{\vproduct=}"orange-lettuce-rice salad" in \reffig{fig:product:concept}, which is associated with the product tags \vmath{\toSet{\vproducttag}_{\vproduct} = \{}"vegetable", "fruit", "cereal"\vmath{\}}. The product tags \vmath{\vproducttag_{1}} = "cereal", \vmath{\vproducttag_{2}} = "fruit" and \vmath{\vproducttag_{3}}="vegetable" share several \textit{primitive concepts}, such as "plant part". Each product tag has a positive association score with the preference tag \vmath{\vpreferencetag=} "vegetarian". As it is showcased in \reffig{fig:overlap} there are several overlaps between associations, due to the shared primitive concepts of the product tags. Summing all association scores with the preference tag "vegetarian" introduces errors because of the shared "primitive concepts". The calculation of error correction terms \vmath{\epsilon^+ , \epsilon^- } requires all possible combinations of intersections of product tags with shared \textit{primitive concepts}. Such calculation in the worst case requires an exponential time complexity of \vmath{O(2^{n})} for every aggregate association score. Therefore, the aggregation of association scores may become infeasible for an ontology with a high number of shared \textit{primitive tags} amongst associations per product. This challenge can be addressed in the construction of the ontology, by indentifying and isolating overlapping \textit{primitive concepts}. In the previous example, this can be achieved by creating a new product tag \vmath{\vproducttag_{4}} = "plant part" and assigning it to all products that have the "vegetable" or "fruit" tag. All the association scores between the "vegetable" and "fruit" product tags are now reduced by an amount \vmath{\delta}, such that \vmath{\vcorrelation = \vcorrelation - \delta} with \vmath{\vproducttag \in \{\vproducttag_1, \vproducttag_2\}}. All associated preference tags with the product tags "fruit" and "vegetable" can now be associated to the product tag "plant part" with association score \vmath{\vcorrelationindexed{\vproducttag_{4}}{\vpreferencetag} = \delta}, as illustrated in \reffig{fig:reduction:design}. In such case, all terms of \refeq{eq:overlap:error} are equal to \vmath{0}, since all possible intersection are equal to the empty set. Based on the above example to avoid overlaps, a generic \textbf{reduction design principle} is proposed during the ontology design: \begin{enumerate} \item If a product tag contains all the \textit{primitive concepts} of another product tag, then only one is chosen and assigned to a product. \item If there are overlaps of \textit{primitive concepts} between two product tags of the same product, but neither can be omitted because their non-shared \textit{primitive concepts} are important, then the intersection of their \textit{primitive concepts} should be treated as a separate product tag and assigned to all products these tags are associated with. The shared \textit{primitive concepts} are omitted from the original product tags. \end{enumerate} The introduction of the reduction design principle minimizes overlap error \vmath{\epsilon\to0} and therefore the aggregate association can now be calculated as: \begin{equation} \label{eq:additive} \vrelevance = \sum_{z}{\vcorrelation} \end{equation} This calculation has linear complexity \vmath{O(n)} to the number of product tag concepts in each aggregate association calculation. Yet, the reduction design principle methodology introduces a quadratic \vmath{O(n^{2})} complexity in regards to product tags, once during the creation of the ontology, as each tag needs to be compared against each other to determine overlaps. The reduction design principle is illustrated in \reffig{fig:reduction:design}. If the aggregated association is \vmath{0}, then it is not possible to determine whether a product supports or opposes a preference tag, since it contains equally enough positive and negative concepts. The uncertainty is treated as a product having no information. Analyzing and comparing the aggregate associations between different preferences can be used for the identification of possible \textit{trade-offs} and \textit{rebound effects}. If no overlapping occurs (\vmath{\epsilon=0}) between the associations, then the individual bounding property is also extended to the aggregated association. The \textbf{aggregated association bounding property} is the following: \begin{equation} \begin{gathered} \dfrac{\absol{{\toSet{Q}_{\vproduct}}\cap\toSet{Q}_{\vpreferencetag}^{+}}} {\absol{\toSet{Q}_{\vpreferencetag}^{+}}} - \dfrac{\absol{{\toSet{Q}_{\vproduct}}\cap\toSet{Q}_{\vpreferencetag}^{-}}} {\absol{\toSet{Q}_{\vpreferencetag}^{-}}} \in [-1,1] \stackrel{\refeq{eq:association}, \epsilon = 0}{\Leftrightarrow}\\ \vrelevance \in [-1,1] \end{gathered} \end{equation} Application of the reduction design principle reduces overlaps, yet it may increase the amount of tags and associations in the ontology, when tags are decomposed to disjoint tags with less primitive concepts. Furthermore, successful application relies on the ability of the expert or system to identify and break down associations between preference and product tags. Therefore a trade-off is introduced between efficiency, performance and maintenance of the ontology. \vspace*{1cm} \subsection{\textbf{Product Rating Mechanism}}\label{sec:rating} The ontology is used to calculate a distributed and privacy-preserving product rating value \vmath{\varrho(\vproduct, \vuser)\in\mathbb{R}} between a product \vmath{\vproduct} and a user \vmath{\vuser}. This is achieved by implementing a product rating system with rating design principles of the content based recommender systems\cite{Jan10, Isinkaye2015}. The product rating is designed to use the aggregated association scores \vmath{\vrelevance}. \subsubsection{\textbf{Comparable aggregated associations}}\label{subsec:comparable-aggregated-associations} Different products may satisfy the same preference tag via product tags that are related to different \textit{primitive concepts}. For that reason, comparison of aggregated associations for the same preference tag and different products are not easy to interpret, i.e. each product may have completely unique characteristics that satisfy each preference. To be able to compare how different products satisfy a preference, a reference product can be used to normalize all aggregate association scores. The reference products are defined as follows: (i) a reference product \vmath{\vproduct+} that maximally satisfies the user's preferences and (ii) a reference product \vmath{\vproduct-} that maximally opposes them. For example, a reference product can be a theoretical or existing product that contain all ontology product tags related to a preference tag. The maximum possible positive aggregated association score product is defined as the aggregated association score of a product that contains all product tags positively associated with a preference tag: \begin{equation} \begin{gathered} \vrelpos = \sum_{\vproducttag}{\vcorrelation},\\ \left\{\vproducttag\,|\,\vproducttag \in \toSet{\vproducttag}_{\vproduct+} \wedge \vcorrelation > 0 \right\} \end{gathered} \label{eq:relevance:max} \end{equation} Such product is referred to as \emph{positive reference product}, and its association score is the \emph{positive reference association}. Following the same principle, a product with the minimum possible negative aggregated association score is also introduced. Such product is referred to as \emph{negative reference product}, and its association score is the \emph{negative reference association}. The calculation for such score is: \begin{equation} \begin{gathered} \vrelneg = \sum_{\vproducttag}{\vcorrelation},\\ \left\{\vproducttag\,|\,\vproducttag \in \toSet{\vproducttag}_{\vproduct-} \wedge \vcorrelation < 0 \right\} \end{gathered} \label{eq:relevance:min} \end{equation} Once the aggregated association scores are calculated, a normalization is applied by dividing with the preference scores related to a preference tag. Therefore, comparison between different products is possible: \begin{equation} \begin{gathered} \vrelnorm = \left\{ \, \begin{IEEEeqnarraybox}[][c]{l?s} \dfrac{\vrelevance}{\absol{\vrelneg}}\ , \quad \vrelevance < 0 \\ \quad0\qquad, \quad \vrelevance = 0 \\ \dfrac{\vrelevance}{\vrelpos}\ , \quad \vrelevance > 0 \end{IEEEeqnarraybox} \right. \end{gathered} \label{eq:relevance:norm} \end{equation} Existence of overlaps between product tags when calculating the aggregated association of theoretical reference scores based causes the normalized aggregated association to approach \vmath{0}, as the denominator in \refeq{eq:relevance:norm} increases. Still, it is guaranteed that support or opposition towards a preference tag are not switched due to the overlaps in normalization, since the denominator is positive in both \textit{Relations} \ref{eq:relevance:max} and \ref{eq:relevance:min}. The normalized association score is bound in the range \vmath{\left[-1, 1\right]}, since an actual product may have at most the maximum positive or minimum negative aggregated association score towards a preference tag. Therefore, the term \vmath{\vrelnorm} is also bound in range \vmath{\left[-1, 1\right]}. The choice of the reference products is left to the ontology designer. Possible choices for a reference product are: \begin{enumerate} \item an existing product that achieves the highest/negative aggregate association score. \item a theoretical or existing product that shares all positive/negative associations with a preference tag, while respecting the reduction design principle. \item a theoretical or existing product that shares all positive/negative associations with a preference tag, without respecting the reduction design principle. This option calculates the highest possible denominator value in \refeq{eq:relevance:norm}. This clipping mechanism is illustrated in \reffig{fig:clip:aggregate}. \end{enumerate} The above choices were evaluated with the app testers, and the normalized aggregated scores produced with the third choice were used during the ASSET field test. \subsubsection{\textbf{Sustainability Index: Non-personalized Product Representations}}\label{subsec:product-preference-embeddings} The next step to calculate the product ratings is to establish a relationship between preferences and products. Aggregation over the normalized association score of a product and preference tags of a preference state estimates this relationship. This aggregation is performed by using a measure of central tendency as the estimator. More specifically, here the expected value is chosen. The expected value of the normalized aggregated association scores of all the preference tags that are related to the preference is an estimate that quantifies the support or opposition of a product by the preference: \begin{equation} \label{eq:connection} \begin{gathered} \vconnection = \dfrac{\sum_{\vpreferencetag \in \Omega_{\vpreference}} {\vrelnorm}}{\absol{\Omega_{\vpreference}}} \end{gathered} \end{equation} Each preference tag represent a sustainability goal considered in a preference statement. When a product has positive normalized aggregated association score with a preference tag, then it supports in achieving the sustainability goal represented by that tag. In the opposite case, the product may cause the failure of achieving a sustainability goal. Therefore, the above calculation is referred to as the sustainability index of a product for a preference, as it indicates whether purchasing a product supports in achieving or failing a sustainability goal. Calculating the expected preference-product associations for all preferences and a product yields a numerical vector representation for that product in the preference semantic space. Such representations are used to compare products and determine whether a product is expected to be supported or opposed by a set of preferences. Measures of central tendency over a product representation, such as the mean \vmath{\overline{\vconnection}} can be used to calculate the non-personalized ontology estimate of the product sustainability. \subsubsection{\textbf{Self-determined User Personalization}}\label{subsec:self-determined-product-ratings} High preference scores indicate that a preference is important for a user when calculating the product rating. Therefore, a user's preference scores are used as weights of importance for each preference. A user can express both opposition and support towards any preference. Thus, any inaccuracy or bias introduced by the ontology design may be mitigated by the user by adjusting preference scores. This is also considered as an implicit user-determined extra correction on overlapping \textit{primitive concepts}. Opposition and support of a user towards preferences are modeled via the offset of a preference score from the preference score median \vmean{s} as shown in \refeq{eq:offset}: \begin{equation} \label{eq:offset} \begin{gathered} \vscoreoffset{\vpreferencescore} = \vpreferencescore - \vmean{s} \end{gathered} \end{equation} The higher the support or opposition of a user towards a preference, the higher the absolute value of the offset. A weighted average between product-preference association scores and the user preference offsets are used to calculate a personalized association between a user and a product, given the user's self-determined preference scores. The sum of absolute offsets is used as denominator to preserve the sign of the rating while normalizing. Preserving the signs allows to extend the association logic to user-product level. Positive product ratings indicate that the product mostly supports the user supported preferences and opposes user opposed preferences. For negative product ratings, the product opposes user supported preferences and supports user opposed preferences. Although self-determined personalization allows for a user's \vchal{subjectivity} to influence the ratings, the user is made aware about which preferences produce such ratings. This results in a learning effect, that increases user awareness towards their sustainability preferences. For example when a person tunes the preferences to allow their favorite products achieve high scores, they are aware that to do so, they have to go against the preference they originally support. Thus the unscaled product rating is calculated as follows: \begin{equation} \label{eq:rating:raw} \begin{gathered} \varrho^{*}(\vproduct,\vuser) = \dfrac{\sum_{\vpreference}\vconnection\cdot\vscoreoffset{\vpreferencescore}} {\sum_{\vpreference}\absol{\vscoreoffset{\vpreferencescore}}} \end{gathered} \end{equation} The scale of \vmath{[-1, 1]} can be transformed to any range of real numbers by applying a linear scaling with parameters \vmath{\alpha} and \vmath{\beta}. Transforming the rating scale has several applicability scenarios. The rating can be scaled to different ranges to match the most preferred grading system of the country, where the algorithm is deployed\cite{blanton1999better}. Another possible usage of the scaling coefficients is to attribute rating for asymmetric perception of negative and positive rating values\cite{kwon2016third, parguel2011sustainability}. For example, based on the work of Parguel et al.\cite{parguel2011sustainability}, negative values have a higher impact on user perception. In such case, a different lower scaling coefficients \vmath{\alpha, \beta} can be used to reduce the impact. \begin{equation} \label{eq:rating} \begin{gathered} \vrating{\vproduct}{\vuser} = \alpha \cdot \rho^{*}(\vproduct,\vuser) + \beta \end{gathered} \end{equation} The product rating scale is designed to utilize user preference scores and create an association between a user and a product based on the product-preference associations. The rating value is expected to be bounded in a range \vmath{[\beta-\alpha, \beta+\alpha]}. Products that neither support nor oppose the user's preferences are assigned the mean value of the range \vmath{\beta}. If the product supports a user supported preference or opposes a user opposed preference, then the product rating increases. On alternative scenarios the product rating decreases. The rating value compresses \textit{overwhelming information} and shows to the user an estimate of the personalized product sustainability. Depending on the UI design, it is possible to allow the user to further explore the ontology dynamics that result in this rating value. In the \reffig{fig:prod:rating:ontology} all related ontology entities and rating calculations are presented. \subsubsection{\textbf{Algorithm complexity}}\label{subsec:algorithm-complexity} All calculations to compute the product-preference representations rely on information that is not related to the user. Therefore, \textit{Equations~\ref{eq:additive}-\ref{eq:connection}} can be computed without privacy intrusion risks. The computational cost is significantly reduced for the user's device, since it is possible to calculate, store and distribute the product representations \vmath{\vconnection} by using a central database system. The calculation and storage complexity for the worst case scenario, where all products are connected to every product tag, all product tags are associated to all preference tags and all preference tags are connected to all preferences is: \begin{equation} \label{eq:complexity:equi} O(n) = P \cdot T \cdot \Omega \cdot C \end{equation} where: \begin{conditions*} \vmath{P} & The number of all products. \\ \vmath{T} & The number of all product tags. \\ \vmath{\Omega} & The number of all preference tags.\\ \vmath{C} & The number of all preferences. \end{conditions*} Assuming that all the above sizes are equal, the worst case computational and storage complexity for the algorithm is polynomial to the power of \vmath{4}: \begin{equation} \label{eq:complexity} \begin{gathered} (\text{Relation }~\ref{eq:complexity:equi}) \land (P = T = \Omega = C) = O(n^4) \end{gathered} \end{equation} Since the total products and product tags are often significantly more than the preference statements and preference tags, the expected time and space complexity is reduced to quadratic polynomial time \vmath{O(n^{2})}. Therefore, modern CPUs on mobile phones and database servers can handle up to hundreds of thousands of product rating calculations per minute and store several thousands of products and product tags\cite{papadimitriou2019adaptive}. \subsubsection{\textbf{Overlaps and possible errors}}\label{subsec:overlaps-and-possible-error-overflows} As discussed in \refsec{sec:ontology}, the application of the reduction design principle introduces several trade-offs between the efficiency of the rating calculations and maintenance of the ontology. Time constraints and limited resources regarding the construction and testing of the ontology may allow overlaps in the ontology, which introduce errors and biases that may break the bounding properties of \textit{Equation} \ref{eq:total_association}. Thus, in such cases a clipping normalization is introduced to avoid numerical instabilities due to overflows outside the theoretical aggregated association bounds: \begin{equation} \label{eq:normalization} \begin{gathered} \vnorm{a} = \left\{ \, \begin{IEEEeqnarraybox}[][c]{l?s} -\tau\ , \text{if}\quad a \leq -\tau \\ a\quad, \text{if}\quad -\tau < a < \tau \\ \tau\quad, \text{if}\quad a \geq \tau \end{IEEEeqnarraybox} \right. \end{gathered} \end{equation} The introduction of the clipping changes \textit{Relations}~\ref{eq:additive},~\ref{eq:relevance:max} and~\ref{eq:relevance:min} to the following: \begin{equation} \label{eq:relevance:norm:asset} \begin{gathered} \vrelevance = \vnorm{\sum_{\vproducttag \in \toSet{\vproducttag}_{\vproduct} }\vcorrelation} \end{gathered} \end{equation} \begin{equation} \begin{gathered} \vrelpos = \vnorm{\sum_{\vproducttag}{\vcorrelation}},\\ \left\{\vproducttag\,|\,\vproducttag \in \toSet{\vproducttag} \wedge \vcorrelation > 0 \right\} \end{gathered} \label{eq:relevance:max:norm} \end{equation} \begin{equation} \begin{gathered} \vrelneg = \vnorm{\sum_{\vproducttag}{\vcorrelation}},\\ \left\{\vproducttag\,|\,\vproducttag \in \toSet{\vproducttag} \wedge \vcorrelation < 0 \right\} \end{gathered} \label{eq:relevance:min:norm} \end{equation} Even if overlaps affect the rating process, the users are able to mitigate the error by readjusting their preference scores, introducing an extra correction mechanism from their side. An illustration of the clipping mechanism on the normalized aggregate score is found in \reffig{fig:clip:aggregate} in step 1. \subsection{\textbf{Tractable and Explainable Ratings}}\label{subsec:tractable-and-explainable-ratings} The proposed ontology design and rating calculations rely on a fully tractable analytical framework. It is possible to calculate the exact amount that a preference, preference or product tag contributed to the rating. More specifically following \cref{eq:rating:raw,eq:rating}, one could solve to calculate the exact contribution of a specific preference \vmath{\vpreference^*} to the product rating as follows: \begin{equation} \label{eq:rating:raw:contr} \begin{aligned} \varrho(\vproduct,\vuser) &= \alpha\left( \dfrac{\sum_{\vpreference \in \toSet{\vpreference} - \{\vpreference^*\}}\vconnection\cdot\vscoreoffset{\vpreferencescore}} {\sum_{\vpreference}\absol{\vscoreoffset{\vpreferencescore}}} \right.\\ &+ \left. \dfrac{\vconn{\vproduct}{\vpreference^*}\cdot\vscoreoffset{\vpreferencescore^*}} {\sum_{\vpreference}\absol{\vscoreoffset{\vpreferencescore}}} \right) + \beta \end{aligned} \end{equation} Therefore the contribution of preference \vmath{\vpreference^*} to the final rating is calculated as: \begin{equation} \label{eq:contr:preference} \begin{gathered} \alpha\dfrac{\vconn{\vproduct}{\vpreference^*}\cdot\vscoreoffset{\vpreferencescore^*}} {\sum_{\vpreference}\absol{\vscoreoffset{\vpreferencescore}}} \end{gathered} \end{equation} The contribution of a specific preference tag \vmath{\vpreferencetag^*} is calculated following the same decomposition logic on \cref{eq:rating:raw,eq:rating,eq:connection}, the contribution of a specific preference tag to the rating can be calculated as: \begin{equation} \label{eq:contr:prftag} \begin{gathered} \alpha \dfrac{\sum_{\vpreference \in \toSet{\vpreference}} \dfrac{\vrelsupp{*}{\vproduct, \vpreferencetag^*}}{\absol{\Omega_{\vpreference}}} \cdot\vscoreoffset{\vpreferencescore}} {\sum_{\vpreference}\absol{\vscoreoffset{\vpreferencescore}}} \quad \end{gathered} \end{equation} And the contribution of a specific product tag \vmath{\vproducttag^*} to the product rating can be calculated by decomposing \cref{eq:rating:raw,eq:rating,eq:connection,eq:relevance:norm}: \begin{equation} \label{eq:contr:prftag} \begin{gathered} \alpha \dfrac{\sum_{\vpreference \in \toSet{\vpreference}} \dfrac{ \sum_{\vpreferencetag \in \Omega_{\vpreference}} \dfrac{ \vcorr{\vproducttag^*,\vpreferencetag} }{ \eta_{norm} } }{\absol{\Omega_{\vpreference}}} \cdot\vscoreoffset{\vpreferencescore}} {\sum_{\vpreference}\absol{\vscoreoffset{\vpreferencescore}}} \quad \end{gathered} \end{equation} where \vmath{\eta_{norm}} has the corresponding denominator value of either \vmath{\{\vrelpos, \vrelneg\}} that normalizes the aggregated association in \cref{eq:relevance:norm}. In case that clipping is used, as shown in \refeq{eq:relevance:norm:asset}, the contribution is calculated proportionally: \begin{equation} \label{eq:contr:prftag} \begin{gathered} \alpha \dfrac{\sum_{\vpreference \in \toSet{\vpreference}} \dfrac{ \sum_{\vpreferencetag \in \Omega_{\vpreference}} \dfrac{ \dfrac{ \vcorr{\vproducttag^*,\vpreferencetag} }{ \sum_{z}{\vcorrelation} } }{ \eta_{norm} } } {\absol{\Omega_{\vpreference}}} \cdot\vscoreoffset{\vpreferencescore}} {\sum_{\vpreference}\absol{\vscoreoffset{\vpreferencescore}}} \quad \end{gathered} \end{equation} Product tag contributions can also be calculated per preference or preference tag. Such calculations are possible by ommitting the calculation related to the product rating and calculate the amount a product tag contributes to other scores, such as the sustainability index discussed in \Cref{eq:connection}. Finally, contributions can either be stored when calculating the product rating, increasing memory complexity or recalculated after the rating calculation, thus increasing computation complexity. \subsection{\textbf{Crowd Sourced Product Data}}\label{sec:crowd_sourced_product_data} To facilitate wisdom of the crowds, a datathon took place at the University of Tartu, Estonia on November 2017~\cite{datathon}. In total three teams of 3-4 people participated in the datathon, and produced data files and code within 72 hours. The datathon teams processed text data from Wikipedia pages related to product characteristics and sustainability goals. Each team used statistical methods and machine learning techniques based on NLP and sentiment analysis to extract an association score between product tags and sustainability topics. Each score should cite the wikipedia page id that was used to extract such data. This resulted in several thousand association scores between product and preference tags. The ASSET consortium used the majority of these results to evaluate existing association score and discover new ones. Several new product tags and associations were introduced in the ontology, mainly in the environmental and social categories. Further collaboration with members of the winning datathon team took place in order to enrich and evaluate the created ontology. As new product tags and association scores were discovered, the datathon provides a real world example on how machine learning can be used to populate a sustainability ontology. Furthermore, the datathon showcases a working case, where crowd-sourced data can be used for populating a sustainability ontology. \subsection{\textbf{Supportive Backend and Other Smart Phone Libraries}} Data were collected, stored and processed for categorization and classification by AINIA according to GDPR. The smart phone app integrates a library version~\cite{nervousnet} of the Nervousnet system~\cite{Pournaras2015}. While no Nervousnet functionality has been used during the lifetime of this project and work, its integration has been part of a deliverable for the ASSET EU-project. Its modular and flexible sensor data management system has potential future applicability in shopping scenarios from multiple retailer shops. \section*{\textbf{Supplementary Notes}} \setcounter{subsection}{0} \renewcommand\thesubsection{SN.\arabic{subsection}} \subsection{\textbf{Entry and Exit Survey}}\label{subsec:behavioral-change:qualitative} Entry and exit surveys are presented to the user during the field test. The aim of the surveys is to collect data regarding user opinions on sustainable consumption, sustainability preferences and the usage of the application. The number of participants for each survey is summarized in \reftab{tbl:surveys:part} Answers on the exit survey provide useful insights regarding the behavioral change and sustainability awareness of users during the field test. Users confirmed that the rating methodology offers product ratings that justify their preference settings. Access to product information and the product tags is visible in the application for users that click on a product. Such information assists the decision or the product purchase. User declared that it is relatively easy to access the product information and that the provided information justifies the rating (\textit{Supplementary Figures}~\ref{fig:feedback:pos:extrainfo} and~\ref{fig:feedback:pos:justify}). The highly rated products tend to match the preferences of the majority of the users as shown in \textit{Supplementary Figures}~\ref{fig:feedback:pos:prefmatch},~\ref{fig:feedback:pos:preferences:account} and ~\ref{fig:feedback:pos:capture:preferences}. Finally, an increase in discovery of novel products is stated by the users in \reffig{fig:feedback:pos:novelty}. Shopping behavior is affected for some users by using the app. Mainly in retailer B users support that they would not buy products that achieve low ratings and buy high rated products before using the app, which emphasizes their sustainability focus (\textit{Supplementary Figures}~\ref{fig:feedback:awareness:high:before} and~\ref{fig:feedback:awareness:high:before}). Regarding future purchases, users support that they will buy products that achieve high ratings and also avoid buying products that achieve low rating, as shown in \textit{Supplementary Figures}~\ref{fig:feedback:awareness:high:rating} and~\ref{fig:feedback:awareness:low:rating}. Furthermore, users in retailer A estimated that they buy over \vmath{5\%} of highly rated products in retailer A, whereas most retailer B users estimate a value over \vmath{10\%}, as illustrated in \reffig{fig:feedback:percentage:bought}. In both retailers, the majority of users agree to an extent that the usage of the application raised their awareness towards sustainability \reffig{fig:feedback:awareness:awareness} Product information and price seem to be the main decision factors when users decide regarding a product purchase, as illustrated in \reffig{fig:feedback:final}. Concluding, weakly qualitative evaluation indicates that the application provides enough information to the users to purchase highly rated products, thus increasing the sustainability of their consumption. Screenshots from the app UI of the survey and preferences is illustrated in \reffig{fig:app:usage}. Users perceive that the product rating takes into account their preferences and is well justified by the available data. Other factors may affect the participation of users such as technical problems with the app, low usability of UI, seasonality (traveling), limited access to retailers shops for some consumers, etc. \subsection{\textbf{Evaluation of Product Prices}}\label{subsec:prices:eval} \subsubsection*{Sustainability index vs product price} This evaluation studies whether products that highly support a specific preference have a higher price compared to products from the same category. Evaluating sustainability index and price over all products provides insights about the general expenditure. Consumers might be interested in replacing products they buy with more sustainable products from the same category. To evaluate whether more expensive products achieve higher sustainability scores compared to competitive products from the same category, both price per unit and sustainability index are rescaled using the min-max normalization for each product per category. I.e. Each value is normalized by substracting the minimum value and then dividing by the difference between maximum and minimum value\cite{dodge2006oxford}. For the normalization to work, each category needs to contain at least two products with different sustainability index and price values. Therefore, only such categories are used for the analysis. As illustrated in \reffig{fig:price:radial:norm:coop}, purchasing more expensive products per category in retailer A seems to have almost no impact on the sustainability index for most categories. The vegan diet preference "H.12" is negative correlated with price, possibly indicating that the most expensive products per category often contain an animal product. For retailer B, the sustainability index for most preferences is either positively correlated or uncorrelated with prices. Negative correlated preferences with prices are "E.2", "E.3" and "S.1", indicating that one can purchase cheaper products per category, which are farmed in a sustainable manner, distributed in an environmentaly friendly way and passed sustainability auditing process. This result may indicate that in most categories the most expensive product originates from a place that the transportation has high environmental impact, sustainable farming techniques are not followed or sustainable auditing processes do not hold. Furthermore, since retailer B is a sustainability focused retailer, it is expected that the suppliers may mitigate sustainable production costs in their product prices. \begin{comment} \subsubsection{Price vs self-determined sustainability} The correlation analysis can be expanded to determine whether the products perceived as more sustainable from the users are also more expensive. Instead of the sustainability index, the viewed product rating per purchased product is compared against the price per unit. The product rating correlation is evaluated both on price values across all products and normalized price values per category. In general no significant correlation between product price and rating is observed. When normalizing across both values per category, as in \reffig{fig:price:hex:coop:cat}, a low significant positive correlation is calculated. This indicates that the purchases with the highest viewed product rating are also the most expensive ones in the category. Similar patterns and correlation values are observed for retailer B as well in \textit{Figures} \ref{fig:price:hex:wm} and \ref{fig:price:hex:wm:cat}. This indicates that user preferences introduce a weak positive correlation between price and product rating, regardless of the retailer focus. \end{comment} Note that the lower expenditure level of Retailer A during the summer is a seasonality effect that is prominent due to the students' holidays and constructions in the neighborhood. \section*{\textbf{Software Libraries}} \setcounter{subsection}{0} \renewcommand\thesubsection{SN.\arabic{subsection}} For the development and analysis of the presented results several libraries were used. Some notable references are: (i) pycausalimpact\footnote{\url{https://github.com/dafiti/causalimpact}}, (ii) scikit-learn~\cite{scikit-learn}, (iii) scipy~\cite{scipy}, (iv) the discrete information theory package~\cite{dit}, (v)pyclustering~\cite{andrei_novikov_2018_1491324}, (vi) plotly~\cite{plotly}. Several other libraries that were used, are also mentioned in the paper code repository. \printnomenclature
{'timestamp': '2020-05-15T02:10:31', 'yymm': '2004', 'arxiv_id': '2004.09180', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09180'}
arxiv
\section*{Acknowledgments} We would like to acknowledge the Stanford Machine Learning Group (\url{stanfordmlgroup.github.io}) and the Stanford Center for Artificial Intelligence in Medicine and Imaging (\url{AIMI.stanford.edu}) for infrastructure support. Thanks to Alistair Johnson for support in the radiologist benchmark, to Jeremy Irvin for support in the CheXpert labeler, Alex Tamkin for helpful comments, and Yifan Peng for helpful feedback. \section{Analysis} \subsection{T-auto versus CheXpert} We analyze whether T-auto, which is trained exclusively on labels from CheXpert (a rules-based labeler), can generalize beyond those rules. We analyze specific examples in the CheXpert manual test set which T-auto correctly labels but CheXpert mislabels. On one example, T-auto is able to correctly detect uncertainty expressed in the phrase “cannot be entirely excluded,” which CheXpert is not able to detect because the phrase does not match any rule in its ruleset. Similarly, on another example containing “no evidence of pneumothorax or bony fracture,” T-auto correctly labels fracture as negative, while CheXpert labels fracture as positive since the phrasing does match any negation construct part of its ruleset. T-auto, in contrast to CheXpert, also recognizes conditions with misspellings in the report like “cariomegaly” in place of “cardiomegaly” and “mediastnium” in place of “mediastinum”. Examples of T-auto correctly labeling conditions mislabeled by CheXpert are provided in Table \ref{tab:t_auto_vs_chexpert} of the Appendix. Table \ref{tab:chexpert_vs_t_auto} of the Appendix contains examples of CheXpert correctly labeling conditions mislabeled by T-auto. \subsection{CheXbert versus T-auto and CheXpert} We analyze how CheXbert improves on T-auto and CheXpert using examples which CheXbert correctly labels but T-auto and CheXpert incorrectly label. Chexbert is able to correctly detection conditions which CheXpert and T-auto are not able to. On one example, T-auto and CheXpert both mislabel a ``mildly enlarged heart'' as blank for cardiomegaly, while CheXbert correctly labels it positive. On another containing ``Right hilum appears slightly more prominent'' (an indicator for enlarged cardiomediastinum), CheXbert correctly classifies enlarged cardiomediastinum as positive, while T-auto and CheXpert do not detect the condition. Furthermore, CheXbert correctly labels nuanced expressions of negation that both CheXpert and T-auto mislabel. On the example containing ``heart size is slightly larger but still within normal range," CheXpert and T-auto mistakenly label cardiomegaly as positive, while CheXbert correctly labels cardiomegaly as negative. On another example containing the phrase ``interval removal of PICC lines”, CheXpert and T-auto detect ``PICC lines" as an indication of a support device but are unable to detect the negation indicated by ``removal", which CheXbert correctly does. Additionally, CheXbert is able to correctly detect expressions of uncertainty that both CheXpert and T-auto mislabel. On an example containing “new bibasilar opacities, which given the clinical history are suspicious for aspiration,” CheXbert correctly identifies lung opacity as positive while CheXpert and T-auto incorrectly detect uncertainty (associating “suspicious” as a descriptor of “opacities”). More examples which CheXbert correctly labels but CheXpert and T-auto mislabel can be found in Table \ref{tab:chexbert_vs_rest} of the Appendix. \subsection{Report Changes with Backtranslation} We analyze the phrasing and vocabulary changes that backtranslation introduces into the reports. Backtranslation frequently rephrases text. For instance, the sentence ``redemonstration of multiple right-sided rib fractures” is backtranslated to ``redemonstration of several rib fractures of the right side”. Backtranslation also introduces some error: the phrase “left costophrenic angle” is translated to ``left costophrine angle” (``costophrine” is not a word), and the phrase ``left anterior chest wall pacer in place" is backtranslated to ``pacemaker on the left front of the chest wall", which omits the critical attribute of being in place. In many examples, the backtranslated text paraphrases medical vocabulary into possible semantic equivalents: “cutaneous" becomes ``skin", ``left clavicle" becomes ``left collarbone", ``osseous'' becomes ``bone" or ``bony", ``anterior" becomes ``front", and ``rib fracture" becomes ``broken ribs". More backtranslations with analyses are provided in Table \ref{tab:backtranslation} of the Appendix. \section{Conclusion} In this study, we propose a simple method for combining existing report labelers with hand-annotations for accurate radiology report labeling. In this method, a biomedically pretrained BERT model is first trained on the outputs of a labeler, and then further finetuned on the manual annotations, the set of which is augmented using backtranslation. We report five findings on our resulting model, CheXbert. First, we find that CheXbert outperforms models trained only on radiologist-labeled reports, or only on the existing labeler's outputs. Second, we find that CheXbert outperforms the BERT-based model not pretrained on biomedical data. Third, we find that CheXbert outperforms models which do not use backtranslation. Fourth, we find that CheXbert outperforms the previous best labeler, CheXpert (which was rules-based), with an improvement of 0.052 (95\% CI 0.037, 0.067) on the F1 metric; we also find that the best model trained only on manually labeled radiology reports (Tblue-rad-bt) performs at least as well as the CheXpert labeler. Fifth, we find that CheXbert is 0.007 F1 points from the radiologist performance benchmark, suggesting that the gap to ceiling performance is narrow. We expect this method of training medical report labelers is broadly useful within the medical domain, where collection of expert labels can produce a small set of high quality labels, and existing feature engineered labelers can produce labels at scale. Extracting highly accurate labels from medical reports by taking advantage of both sources can enable many important downstream tasks, including the development of more accurate and robust medical imaging models required for clinical deployment. \section{Experiments} \subsection{Supervision Strategies} We investigate models trained using three strategies: trained only on radiologist-labeled reports, trained only on labels generated automatically by the CheXpert labeler \cite{irvin_chexpert_2019}, and trained on a combination of the two. \paragraph{Radiologist Labels} \textbf{T-rad} is obtained by training the model on the CheXpert manual set, finetuning all weights. As baselines, we also train models that freeze all weights in the BERT layers, and only update the weights in the linear heads: \textbf{T.cls-rad} is identical to T-rad in architecture, while \textbf{T.token-rad} averages the non-padding output tokens as the input into the linear heads rather than using the CLS token output. All models are trained using a random 75\%-25\% train-dev split on this set, and are trained until convergence. \paragraph{Automatic Labels} \textbf{T-auto} is obtained using labels generated by the rule-based CheXpert labeler, described in \citet{irvin_chexpert_2019}. T-auto is trained using a random 85\%-15\% train-dev split of the CheXpert training set, different from the models trained on radiologist labels. T-auto is trained for 8 epochs, since slightly higher dev performance is observed compared to the typical 2-4 epochs for BERT fine-tuning tasks. \paragraph{Hybrid Labels} \textbf{T-hybrid} is obtained by initializing a model with the weights of T-auto, and then finetuning it on radiologist-labeled reports, as for T-rad. \paragraph{Results} As shown in Table \ref{tab:headline}, T-rad achieves an F1 of $0.705$ $(0.680, 0.725)$, significantly higher than the performance of the baselines with T.cls-rad at $0.286$ $(0.265, 0.305)$, and T.token-rad at $0.396$ $(0.374, 0.416)$. T-auto achieves a higher F1 of $0.755$ $(0.731, 0.774)$. Superior performance is obtained by T-hybrid, with an F1 of $0.775$ $(0.753, 0.795)$. \subsection{Biomedical Language Representations} We investigate the effect of having models pre-trained on biomedical data. For the following models, we use an identical training procedure to T-rad, but initialize the weights differently. \textbf{Tbio-rad} is obtained by using BioBERT weight initializations \cite{lee_biobert_2019}. BioBERT was obtained by further pretraining the BERT weights on a large biomedical corpus comprising PubMed abstracts (4.5 billion words) and PMC full-text articles (13.5 billion words). \textbf{Tclinical-rad} is obtained by using Clinical BioBERT weight initializations \cite{alsentzer_publicly_2019}, which were obtained by further pretraining the BioBERT weights on 2 million clinical notes from the MIMIC-III database. Finally, \textbf{Tblue-rad} is obtained by using BlueBERT, a BERT model pretrained on PubMed abstracts and clinical notes (MIMIC-III) \cite{peng_transfer_2019}. \paragraph{Results} As shown in Table \ref{tab:headline}, Tbio-rad achieves an F1 of $0.616$ $(0.587, 0.639)$ and Tclinical-rad achieves an F1 of $0.677$ $(0.651, 0.699)$, lower than T-rad. However, Tblue-rad achieves an F1 of $0.741$ $(0.714, 0.763)$, higher than T-rad. The drop in performance with Tbio-rad and Tclinical-rad may possibly be attributed to using different vocabulary, sequence length, and other configurations (stopping procedure, embedding dimensions) than those used by Tblue-rad, which uses the configurations provided in \citet{devlin_bert_2019}. \subsection{Data Augmentation using Backtranslation} We investigate the use of backtranslation to improve the performance of the models. Backtranslation is designed to generate alternate formulations of sentences by translating them to another language and back. Although backtranslation has been successfully used to augment text data in a variety of NLP tasks \citep{yu_qanet_2018, poncelas_investigating_2018}, to our knowledge, the technique is yet to be applied to a medical report extraction task. In this experiment, we augment the CheXpert manual set using Facebook-FAIR's winning submission to the WMT'19 news translation task \cite{ng_facebook_2019} to generate backtranslations. Although this submission includes models that produce German/English and Russian/English translations, initial experiments with Russian did not demonstrate semantically correct translations, so we only continued experiments with German. We use beam search with a beam size of 1 to select the single most likely translation. We perform this experiment using our best models: \textbf{Tblue-rad-bt} is obtained by using an identical training procedure to Tblue-rad on the augmented dataset (which is twice the size of the CheXpert manual set). \textbf{Tblue-hybrid-bt} is obtained by first training a BlueBERT-based labeler on automatically generated CheXpert labels, and then fine-tuning on radiologist-labeled reports of the CheXpert manual set, augmented by backtranslation. We also report the performance of T-rad-bt and T-hybrid-bt. \paragraph{Results} As shown in Table \ref{tab:headline}, T-rad-bt achieves an F1 score of $0.729$ $(0.702, 0.749)$, higher than that of T-rad. Similarly, T-hybrid-bt achieves an F1 of $0.795$ $(0.772, 0.815)$. Tblue-rad-bt achieves an F1 of $0.770$ $(0.747, 0.790)$, higher than that of the CheXpert labeler. Tblue-hybrid-bt achieves a superior F1 score of $0.798$ $(0.775, 0.816)$. \subsection{Comparison to previous SOTA and radiologist benchmark} We compare the performance of our best model to the previous best reported labeler, the CheXpert labeler \cite{irvin_chexpert_2019}, and to a radiologist benchmark. CheXpert is an automated rule-based labeler that extracts mentions of conditions like pneumonia by searching against a large manually curated list of words associated with the condition and then classifies mentions as uncertain, negative, or positive using rules on a universal dependency parse of the report. For the radiologist benchmark, the annotations by one of the 2 radiologists on the MIMIC-CXR test set is used, while the other is used as ground truth. We report the improvement of our best model, Tblue-hybrid-bt, which we also call \textbf{CheXbert}, over the CheXpert labeler by computing the paired differences in F1 scores on 1000 bootstrap replicates and provide the mean difference along with a 95\% two-sided confidence interval. \paragraph{Results} We observe that CheXbert has a statistically significant improvement $(p < 0.001)$ over the existing SOTA, CheXpert, which achieves a score of $0.743$ $(0.719, 0.764)$. Notably, we also find that Tblue-rad-bt, the best model trained only on manually labeled radiology reports, performs at least as well as the CheXpert labeler. Table \ref{tab:chexbert_vs_chexpert} shows the F1 per class (along with 95\% confidence intervals) for CheXbert and for the improvements over CheXpert. CheXbert records an improvement in all but 2 medical conditions, and a statistically significant improvement in 9 of the 14 conditions. The largest improvements are observed for Pneumonia [$0.151$ $(0.093, 0.206)$], Fracture [$0.120$ $(0.019, 0.236)$], Consolidation [$0.105$ $(0.029, 0.192)$], Enlarged Cardiomediastinum [$0.100$ $(0.038, 0.166)$], and No Finding [$0.097$ $(0.007, 0.182)$]. Further significant improvements are observed for Pleural Other [$0.056$ $(0.008, 0.124)$], Cardiomegaly [$0.051$ $(0.018, 0.086)$], Pneumothorax [$0.046$ $(0.015, 0.076)$] and Support Devices [$0.021$ $(0.004, 0.040) $]. Overall, CheXbert achieves a statistically significant improvement on F1 of $0.055$ $(0.039, 0.070)$. The board-certified radiologist achieves an F1 of $0.805$ $(0.784, 0.823)$, which is $0.007$ F1 points higher than the performance of CheXbert. \paragraph{Training times} For all our models except the baselines, training on radiologist-labeled reports takes $\sim30$ minutes, training on the radiologist-labeled reports augmented via backtranslation takes $\sim50$ minutes, and training on the reports labeled by the CheXpert labeler) takes $\sim7$ hours. \section{Introduction} The extraction of labels from radiology text reports enables important clinical applications, including large-scale training of medical imaging models \cite{wang_chestx-ray8_2017}. Many natural language processing systems have been designed to label reports using sophisticated feature engineering of medical domain knowledge \cite{pons_natural_2016}. On chest x-rays, the most common radiological exam, rule-based methods have been engineered to label some of the largest available datasets \cite{johnson_mimic-cxr-jpg_2019}. While these methods have generated considerable advances, they have been unable to capture the full diversity of complexity, ambiguity and subtlety of natural language in the context of radiology reporting. \begin{figure}[t] \includegraphics[width=\columnwidth]{figures/main.pdf} \caption{We introduce a method for radiology report labeling, in which a biomedically pretrained BERT model is first trained on annotations of a rule-based labeler, and then finetuned on a small set of expert annotations augmented with automated backtranslation.} \label{fig:main} \end{figure} More recently, Transformers have demonstrated success in end-to-end radiology report labeling \cite{drozdov_supervised_2020, wood_automated_2020}. However, these methods have shifted the burden from feature engineering to manual annotation, requiring considerable time and expertise for high quality. Moreover, these methods do not take advantage of existing feature-engineered labelers, which represent state-of-the-art on many medical tasks. In this work, we introduce a simple method for gaining the benefits of both existing radiology report labelers with expert annotations to achieve highly accurate automated radiology report labeling. This approach begins with a biomedically pretrained BERT model \cite{devlin_bert_2019, peng_transfer_2019} trained on the outputs of an existing labeler, and further finetuned on a small corpus of expert annotations augmented with automated backtranslation. We apply this approach to the task of radiology report labeling of chest x-rays, and call our resulting model \textit{CheXbert}. CheXbert outperforms the previous best reported labeler \cite{irvin_chexpert_2019} on an external dataset, MIMIC-CXR \cite{johnson_mimic-cxr-jpg_2019}, with an improvement of 0.055 (95\% CI 0.039, 0.070) on the F1 metric, and only 0.007 F1 away from a radiologist performance benchmark. We expect this method of training medical report labelers is broadly useful for natural language processing within the medical domain, where collection of expert labels is expensive, and feature engineered labelers already exist for many tasks. \section{Limitations} Our study has several limitations. First, our hybrid/auto approaches rely on the existence of an existing labeler to generate labels. Second, our report labeler has a maximum input token size of 512 tokens and would need to include further engineering to work on longer medical/radiology reports. Third, our task is limited to the 14 observations labeled for, and we do not test for the model's ability to label rarer conditions. However, CheXbert can mark No Finding as blank, which can indicate the presence of another condition if the other 13 conditions are also blank. Fourth, the ground truth labels for the MIMIC-CXR test set were determined by a single board-certified radiologist, and the use of more radiologists could demonstrate a truer comparison to the radiologist benchmark. Fifth, while we do test performance on a dataset from an institution unseen in training, additional datasets across institutions could be useful in further establishing the model's ability to generalize. \section{Methods} \subsection{Task} The report labeling task is to extract the presence of one or more clinically important observations (e.g. consolidation, edema) from a free-text radiology report. More formally, a labeler takes in as inputs sentences from a radiology report and outputs for 13 observations one of the following classes: blank, positive, negative, and uncertain. For the 14th observation corresponding to \textit{No Finding}, the labeler only outputs one of the two following classes: blank or positive. \subsection{Data} Two existing large datasets of chest x-rays, CheXpert \cite{irvin_chexpert_2019} (consisting of 224,316 images), and MIMIC-CXR \cite{johnson_mimic-cxr-jpg_2019} (consisting of 377,110 images) are used in this study. Both datasets have corresponding radiology reports that have been labeled for the same set of 14 observations using the CheXpert labeler \cite{irvin_chexpert_2019}, from the \textit{Impression} section, or other parts of the radiology report. A subset of both datasets also contain manual annotations by expert radiologists. On CheXpert, a total of 1000 reports (\textit{CheXpert manual set}) were reviewed by 2 board certified radiologists with disagreement resolution through consensus. On MIMIC-CXR, a total of 687 reports (\textit{MIMIC-CXR test set}) were reviewed by 2 board certified radiologists and manually labeled for the same 14 medical observations as in CheXpert. In this study, CheXpert is used for the development of models, and the MIMIC-CXR test set is used for evaluation. Some reports from the same patient appear multiple times in the CheXpert dataset. Removing duplicate reports as well as the CheXpert manual set from the CheXpert dataset results in 190,460 reports, the class prevalences for which are shown in Table \ref{tab:chexpert_prevalences} of the Appendix. We remove excess spaces and newlines from all reports. \subsection{Model Architecture} All models use a modification of the BERT-base architecture \cite{devlin_bert_2019} with 14 linear heads (as shown in Figure \ref{fig:architecture}): 12 heads correspond to various medical abnormalities, 1 to medical support devices, and 1 to `No Finding'. Each radiology report text is tokenized, and the maximum number of tokens in each input sequence is capped at 512. The final-layer’s hidden state corresponding to the CLS token is then fed as input to each of the linear heads. \subsection{Training Details} For all our models, unless otherwise specified, we finetune all layers of the BERT model, including the embeddings, and feed the CLS token into the 14 linear heads to generate class scores for each medical observation. BERT-Base contains $\sim110$ million parameters, and the linear heads contain $\sim40,000$ parameters. All models are trained using cross-entropy loss and Adam optimization with a learning rate of $2 \times 10^{-5}$, as used in \citet{devlin_bert_2019} for fine-tuning tasks. The cross-entropy losses for each of the 14 observations are added to produce the final loss. During training, we periodically evaluate our model on the dev set and saved the checkpoint with the highest performance averaged over all 14 observations. All models are trained using 3 TITAN-XP GPUs with a batch size of 18. \subsection{Evaluation} Models are evaluated on their average performance on three retrieval tasks: positive extraction, negative extraction, and uncertainty extraction. For each of the tasks, the class of interest (e.g. negative for the negative extraction and uncertain for the uncertainty extraction) is treated as the positive class, and the other classes are considered negative. For each of the 14 observations, we compute a weighted average of the F1 scores on each of the above three tasks, weighted by the support for each class of interest, which we call the \textit{weighted-F1} metric, henceforth simply abbreviated to F1. We report the simple average of the F1 across all of the observations. We include the 95\% two-sided confidence intervals of the F1 using the nonparametric percentile bootstrap method with 1000 bootstrap replicates \cite{efron_bootstrap_1986}. \section{Related Work} Many natural language processing systems have been developed to extract structured labels from free-text radiology reports \cite{pons_natural_2016, yadav_automated_2016, hassanpour_performance_2017, annarumma_automated_2019, savova_mayo_2010, wang_clinical_2018, chen_integrating_2018, bozkurt_automated_2019}. In many cases, these methods have relied on heavy feature engineering that include controlled vocabulary and grammatical rules to find and classify properties of radiological findings. NegEx \cite{chapman_simple_2001}, a popular component of rule-based methods, uses simple regular expressions for detecting negation of findings and is often used in combination with ontologies such as the Unified Medical Language System (UMLS) \cite{bodenreider_unified_2004}. NegBio \cite{peng_negbio_2017}, an extension to NegEx, utilizes universal dependencies for pattern definition and subgraph matching for graph traversal search, includes uncertainty detection in addition to negation detection for multiple pathologies in chest x-ray reports, and is used to generate labels for the ChestX-Ray14 dataset \cite{wang_chestx-ray8_2017}. The CheXpert labeler \cite{irvin_chexpert_2019} improves upon NegBio on chest x-ray report classification through more controlled extraction of mentions and an improved NLP pipeline and rule set for uncertainty and negation extraction. The CheXpert labeler has been applied to generate labels for the CheXpert dataset and MIMIC-CXR \cite{johnson_mimic-cxr-jpg_2019}, which are amongst the largest chest x-ray datasets publicly available. Deep learning approaches have also been trained using expert-annotated sets of radiology reports \cite{xue_fine-tuning_2019}. In these cases, training set size, often driving the performance of deep learning approaches, is limited by radiologist time and expertise. \citet{chen_deep_2017} trained CNNs with GloVe embeddings \cite{pennington_glove_2014} on 1000 radiologist-labeled reports for classification of pulmonary embolism in chest CT reports and improved upon the previous rules-based SOTA, peFinder \cite{chapman_document-level_2011}. \citet{bustos_padchest_2019} trained both recurrent and convolutional networks in combination with attention mechanisms on 27,593 physician-labeled radiology reports and apply their labeler to generate labels. More recently, Transformer-based models have also been applied to the task of radiology report labeling. \citet{drozdov_supervised_2020} trained classifiers using BERT \cite{devlin_bert_2019} and XLNet \cite{yang_xlnet_2020} on 3,856 radiologist labeled reports to detect normal and abnormal labels. \citet{wood_automated_2020} developed ALARM, an MRI head report classifier on head MRI data using BioBERT \cite{lee_biobert_2019} models trained on 1500 radiologist-labeled reports, and demonstrate improvement over simpler fixed embedding and word2vec-based \cite{mikolov_distributed_2013} models \cite{zech_natural_2018}. Our work is closely related to approaches to reduce the number of expert annotations required for training medical report labelers \cite{callahan_medical_2019, ratner_snorkel_2020, banerjee_radiology_2018}. A method of weak supervision known as data programming \cite{ratner_snorkel_2018} has seen successful application to medical report labeling: in this method, users write heuristic labelling functions that programmatically label training data. \citet{saab_doubly_2019} used data programming to incorporate labeling functions consisting of regular expressions that look for phrases in radiology reports, developed with the help of a clinical expert in a limited time window, to label for intracranial hemorrhage in head CTs. \citet{dunnmon_cross-modal_2019} demonstrated that in under 8 hours of cumulative clinician time, a data programming method can approach the efficacy of large hand-labeled training sets annotated over months or years for training medical imaging models, including chest x-ray classifiers on the task of normal / abnormal detection. Beyond data programming approaches, \citet{drozdov_supervised_2020} developed a fully unsupervised approach utilizing a Siamese Neural Network and Gaussian Mixture Models, reporting performance similar to the CheXpert labeler without requiring any radiologist-labeled reports on the simplified task of assigning normal and abnormal labels. \section{Setup}
{'timestamp': '2020-05-01T02:08:57', 'yymm': '2004', 'arxiv_id': '2004.09167', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09167'}
arxiv
\section{INTRODUCTION} Artificial Intelligence (AI) systems dedicated to the analysis and interaction with the physical world can have a significant impact on human life. These systems can process a massive amount of data and make/suggest decisions that help solve many real-world problems where humans are at the epicenter. Crucial examples are city mobility, pollution monitoring, or critical infrastructure management, where decision-makers require, for instance, measurements about flows of bicycles, cars or people. Like no other sensing mechanism, networks of city cameras can observe such large dimensions and simultaneously provide visual data to AI systems to extract relevant information from this deluge of data. Different smart cameras across the city are subject to various visual conditions (luminance, position, context). This results in different performance from each of them, and added difficulty in effectively scaling-up the learning task. In this paper, we will address this issue, and we propose a methodology that performs unsupervised domain adaptation among different cameras to reliably compute the number of vehicles in a city. We focus on vehicle counting but the approach is applicable to counting any other type of object. \subsection{Counting as a supervised learning task} The counting problem is the estimation of the number of objects instances in still images or video frames \cite{lempitsky2010learning}. Current systems address the counting problem as a supervised learning process. They fall in two main classes of methods: a) detection-based approaches (\cite{amato2019counting, ciampi2018counting, amato2018wireless}) that try to identify and localize single instances of objects in the image and b)density-based techniques that rely on regression techniques to estimate a density map from the image, and where the final count is given by summing all pixel values~\cite{lempitsky2010learning}. Figure \ref{fig:density} illustrates the mapping of such regression. Concerning vehicle counting in urban spaces, where images are of very low resolution, and most objects are partially occluded, density-based methods have a clear advantage on detection methods~\cite{zhang2016single, guerrero2015extremely, li2018csrnet, boominathan2016crowdnet}. Hinging on Convolution Neural Networks (CNN) to learn the regressor, this class of approaches has shown to be very effective, especially in single-camera scenarios. However, since they require pixel-level ground truth for supervised learning, they may not generalize well to unseen images, especially when there is a large \textit{domain gap} between the training (\textit{source}) and the test (\textit{target}) sets, such as different camera perspectives, weather, or illumination. This gap severely hampers the application of counting methods to very large scale scenarios since annotating images for all the possible cases is inviable. \begin{figure}[t] \centerline{\includegraphics[width=.4\textwidth]{density_example.pdf}} \caption{Example of an image with the bounding box annotations (left) and the corresponding density map that sums to the counting value (right).} \label{fig:density} \end{figure} \subsection{Unsupervised domain adaptation} This paper proposes to generalize the counting process through a new domain adaptation algorithm for density map estimation and counting. Specifically, we suppose to have an annotated training set for a \emph{source domain}, and we want to adapt the system to perform well in an unseen and unlabelled \emph{target domain}. For instance, the source domain consists of images taken from a set of cameras, and the target domain consists of images taken from a different set of cameras, with different luminances, perspectives, contexts. This class of algorithms is commonly referred to as \textit{Unsupervised Domain Adaptation}. We conduct preliminary experiments using the \textit{WebCamT} dataset introduced in \cite{zhang2017understanding}. In particular, we consider a test set containing images from cameras with different perspectives from the training ones, showing that our unsupervised domain adaptation technique can mitigate the perspective domain gap. Traditional approaches of Unsupervised Domain Adaptation have been developed to address the problem of image classification, and they try to align features across the two domains (\cite{ganin2014unsupervised, tzeng2017adversarial}). However, as pointed out in \cite{zhang2017curriculum}, they do not perform well in other tasks, such as semantic segmentation. \section{Proposed Method} We propose an end-to-end CNN-based unsupervised domain adaptation algorithm for traffic density estimation and counting. Inspired by \cite{tsai2018learning}, our method is based on adversarial learning in the \textit{output} space (density maps), which contains rich information such as scene layout and context. In our approach, we rely on the adversarial learning scheme to make the predicted density distributions of the source and target domains consistent. The proposed framework, shown in Fig. \ref{overview_approach}, consists of two modules: 1) a CNN that predicts traffic density maps and estimates the number of vehicles occurring in the scene, and 2) a discriminator that distinguishes whether the density map (received by the density map estimator) is generated processing an image of the source domain or the target domain. In the training phase, the density map predictor learns to map images to densities, based on annotated data from the source domain. At the same time, it learns to fool the discriminator exploiting an adversarial loss, computed using the predicted density map of unlabeled images from the target domain. Consequently, the output space is forced to have similar distributions for both the source and target domains. In the inference phase, the discriminator is discarded, and only the density map predictor is used for the target images. A description of each module and their training is provided in the following subsections. \subsection{Density Estimation Network} We formulate the counting task as a density map estimation problem \cite{lempitsky2010learning}. The density (weight) of each pixel in the map depends on its proximity to a vehicle centroid and the size of the vehicle in the image, as shown in Fig. \ref{fig:density}, so that each vehicle contributes with a total value of 1 to the map. Therefore, it provides statistical information about the location of the vehicles and allows the counting to be estimated by summing of all density values. This task is performed by a CNN-based model, whose goal is to automatically determine the vehicle density map associated with a given input image. Formally, the density map estimator, \(\Psi: \mathcal{R^{C \times W \times H}} \mapsto \mathcal{R^{W \times H}}\), transforms a \(\mathcal C\) channels \(\mathcal W \times \mathcal H\) input image, \(\mathcal{I}\), into a density map, \(D=\Psi(\mathcal{I})\in\mathcal{R^{W \times H}}\). \subsection{Discriminator Network} The discriminator network, denoted by \(\Theta\), also consists of a CNN model. It takes as input the density map, \(D\), estimated by the network \(\Psi\). Its output is a lower resolution probability map where each pixel represents the probability that the corresponding area (from the input density map) comes either from the source or the target domain. The goal of the discriminator is to learn to distinguish between density maps belonging to source or target domains. This, in turn, forces the density estimator to provide density maps with similar distributions in both domains, \textit{i.e.}, the density maps, \(D\), of the target domain have to look realistic, even if network \(\Psi\) was not trained with an annotated training set from that domain. \subsection{Domain Adaptation Learning} The proposed framework is trained based on an alternate optimization of density estimation network, \(\Psi\), and the discriminator network, \(\Theta\). Regarding the former, the training process relies on two components: 1) density estimation using pairs of images and ground truth density maps, which we assume are only available in the source domain; and 2) adversarial training, which aims to make the discriminator fail to distinguish between the source and target domains. As for the latter, images from both domains are used to train the discriminator on correctly classifying each pixel of the probability map as either source or target. \begin{figure*} \centerline{\includegraphics[width=.65\textwidth]{architecture.pdf}} \caption{Algorithm overview. Given images having size \(C \times H \times W\) from source and target domains, we pass them through the density map estimation and counting network to obtain output predictions. For source predictions, a density and counting loss is computed based on the source ground truth. To make target predictions closer to the source ones, we employ a discriminator that aims to distinguish whether the input (i.e., the density map) belongs to the source or target domain. Then an adversarial loss is computed on the target prediction and is back-propagated to the density map estimation and counting network.} \label{overview_approach} \end{figure*} To implement the above training procedure, we introduce two loss functions: one is employed in the first step of the algorithm to train network \(\Psi\), and the other is used in the second step to train the discriminator \(\Theta\). These loss functions are detailed next. \textbf{Network \(\Psi\) Training.} We formulate the loss function for \(\Psi\) as the sum of two main components: \begin{equation} \mathcal{L}(\mathcal{I^\mathcal{S}}, \mathcal{I^\mathcal{T}}) = \mathcal{L}_{density}(\mathcal{I^\mathcal{S}}) + \lambda_{adv}\mathcal{L}_{adv}(\mathcal{I^\mathcal{T}}), \label{global_loss_equation} \end{equation} \noindent where \(\mathcal{L}_{density}\) is a composite loss computed using ground truth annotations available in the source domain, while \(\mathcal{L}_{adv}\) is the adversarial loss that is responsible for making the distribution of the target and the source domain close each other. In particular, we define the density loss \(\mathcal{L}_{density}\) as: \begin{equation} \mathcal{L}_{density}(\mathcal{I^\mathcal{S}}) = \mathcal{L}_{density\_map}(\mathcal{I^\mathcal{S}}) + \mathcal{L}_{regression}(\mathcal{I^\mathcal{S}}), \end{equation} \noindent where \(\mathcal{L}_{density\_map}\) is the mean square error between the predicted and ground truth density maps, i.e. \(\mathcal{L}_{density\_map} = MSE(D^{\mathcal{S}}, D^{\mathcal{S\_GT}})\), while \(\mathcal{L}_{regression}\) is Euclidean loss between predicted and ground truth count. To compute the adversarial loss \(\mathcal{L}_{adv}(\mathcal{I^\mathcal{T}})\), we first forward the images belonging to the target domain and we generate the predicted density maps \(D^{\mathcal{T}}\). Then, we compute \begin{equation} \mathcal{L}_{adv}(\mathcal{I^\mathcal{T}}) = - \sum_{h, w}\log (\Theta(D^{\mathcal{T}})). \end{equation} \noindent This loss forces the distribution of \(D^{\mathcal{T}}\) to be closer to \(D^{\mathcal{S}}\) by training \(\Psi\) to fool the discriminator, maximizing the probability of the target predicted density map to be considered as the source prediction. \textbf{Discriminator \(\Theta\) Training.} Given the estimated density map \(D = \Psi(\mathcal{I})\in\mathcal{R^{W \times H}}\), we forward \(D\) to a fully-convolutional discriminator \(\Theta\) using a binary cross-entropy loss \(\mathcal{L}_{disc}\) for the two classes (i.e., source and target domains). We formulate the loss as: \begin{equation} \mathcal{L}_{disc}(D) = - \sum_{h, w}[(1-y)\log(\Theta(D)^{(h,w,0)}) + y\log(\Theta(D)^{(h,w,1)})], \end{equation} \noindent where \(y = 0\) if the sample is taken from the target domain, and \(y = 1\) if the sample is taken from the source domain. \subsection{Implementation Details} \textbf{Density Map Estimation and Counting Network.} We build our density map estimation network based on U-Net \cite{ronneberger2015u}. U-Net is a popular end-to-end encoder-decoder network for semantic segmentation first used for biomedical image segmentation. The encoder part consists of convolution blocks followed by max-pooling blocks that downscale the feature representations at multiple different levels. The decoder part of the network upsamples the features through upsampling layers followed by regular convolution operations. Furthermore, the upsampled features are concatenated with the same scale features from the encoder, which contain more detailed spatial information and prevents the network from losing spatial awareness due to downsampling. \noindent\textbf{Discriminator.} For the discriminator, we use a Fully Convolutional Network similar to \cite{tsai2018learning, radford2015unsupervised}, composed of 5 convolution layers with kernel \(4\times4\) and stride of 2. The number of channels are \{64, 128, 256, 512, 1\}, respectively. Each convolution layer is followed by a leaky ReLU having a parameter equals to 0.2. \section{EXPERIMENTAL SETUP} We conduct preliminary experiments using the \textit{WebCamT} dataset introduced in \cite{zhang2017understanding}. This dataset is a collection of traffic scenes recorded using city-cameras, and it is particularly challenging for analysis due to the low-resolution \((352\times240)\), high occlusion, and large perspective. We consider a total of about 42,000 images belonging to 10 different cameras and consequently having different perspectives. We employ the existing bounding box annotations of the dataset to generate ground truth density maps, one for each image. In particular, we consider one Gaussian Normal kernel for each vehicle present in the scene, having a value of \(\mu\) and \(\sigma\) equals to the center and proportional to the length of the bounding box surrounding the vehicle, respectively. Firstly, we show the domain gap that we want to face. We generate a first pair of training and validation subsets, picking images at random from the whole dataset. Then, we create a second pair of training and validation subsets, this time picking images belonging to seven different cameras for the first and images belonging to the three remaining ones for the second (\textit{per-camera} splits of the whole dataset). We show the domain gap training our model without the discriminator on the training subsets and then comparing the results obtained over the validation splits. Once we quantified and proved this domain gap, we try to mitigate it, conducting experiments on the per-camera splits using our solution, i.e., the network \(\Psi\) and the discriminator \(\Theta\) that acts on the output space. In particular, during the training, we also use the images belonging to the validation subset \textit{without} the labels to generate an adversarial loss aimed at making the source domain (i.e., the training subset) and the target domain (i.e., the validation subset) close each other. We base the evaluation of the models on three metrics: (i) Mean Absolute Error (MAE) that measures the absolute count error of each image; (ii) Mean Squared Error (MSE) that penalizes large errors more heavily than small ones; (iii) Average Relative Error (ARE), which measures the absolute count error divided by the true count. \section{RESULTS AND DISCUSSION} \begin{figure}[t] \centering \begin{tabular}{cc} \includegraphics[width=.21\textwidth]{mae_domain_gap_bis.png} & \includegraphics[width=.21\textwidth]{baseline_discriminator.png} \\ \includegraphics[width=.21\textwidth]{mse_domain_gap_bis.png} & \includegraphics[width=.21\textwidth]{mse_baseline_discriminator.png} \\ \includegraphics[width=.21\textwidth]{are_domain_gap_bis.png} & \includegraphics[width=.21\textwidth]{are_baseline_discriminator.png}\\ (a) & (b) \end{tabular} \caption{Performance during training: (a) Comparison between the random and the per-camera validation splits showing the domain gap; (b) comparison between the proposed approach with and without discriminator. Each row corresponds to a specific evaluation metric.} \label{plot_results} \end{figure} Figure \ref{plot_results} (a) shows the results for the two validation sets - the random one and the per-camera one, using the density estimation network without the discriminator trained over the two training subsets - the random one and the per-camera one, respectively. Each plot corresponds to one of the three metrics. As we can see, the domain gap is significant: even if all the images of the subsets belong to the same dataset and are collected in the same city under similar conditions, small changes to the perspectives cause a remarkable loss in performance. In other words, the network is not able to generalize well to perspectives that have not seen during the training. When combining the density estimation network with the adversarial component, the performance of the network improves considerably. These results are shown in Figure \ref{plot_results} (b), where the improvements obtained using our model (red line) compared to the baseline model, without discriminator, is clearly visible in all the three metrics. The discriminator mitigates the domain gap and the network is able to generalize better over images having a different perspectives from the ones employed during the training. The results are related to a specific value of \(\lambda\) that showed the most promising results. Since all the metrics that we considered take into account only the counting errors, we also plot some examples of the predicted density maps using our model either with and without the discriminator. Figure \ref{example_outputs} shows the ground truth and the predicted density maps for two random samples of the validation subset. As we can see, the density maps predicted using the model with the discriminator show a decrease of the noise compared with the ones obtained using the baseline model without the discriminator. \begin{figure}[t] \centerline{\includegraphics[height=1.8in]{example_outputs.pdf}} \caption{Examples of predicted density maps belonging to two samples of the validation subset (each row corresponds to a sample). From left to right, the original image, the ground truth density map, the predicted density map obtained using the model without the discriminator, and the predicted density map using our domain adaptation algorithm.} \label{example_outputs} \end{figure} \section{CONCLUSIONS} In this article, we tackle the problem of determining the density and the number of objects present in large sets of images. Building on a CNN-based density estimator, the proposed methodology is capable of generalizing to new sources of data for which there is no training data available. We achieve this generalization by adversarial learning, whereby a discriminator attached to the output induces similar density distribution in the target and source domains. Experiments show a significant improvement relative to the performance of the model without domain adaptation. Given the conventional structure of the estimator, the improvement obtained by just monitoring the output entails a great capacity to generalize training and thus suggesting the application of similar principles to the inner layers of the network. In our view, the surprising outcome of this work opens new perspectives to deal with the scalability of learning methods for large physical systems with scarce supervisory resources. \ack This work was partially supported by LARSyS - FCT Plurianual funding 2020-2023 and by H2020 project AI4EU under GA 825619.
{'timestamp': '2020-04-21T02:26:43', 'yymm': '2004', 'arxiv_id': '2004.09251', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09251'}
arxiv
\section{Introduction} Pre-training models~\citep{radford2018improving,devlin2019bert,radford2019language,song19MASS,Yang2019XLNet,Dong2019Unilm,liu2019roberta,raffel2019exploring} have greatly boosted the accuracy of NLP tasks in the past years. One of the most successful models is BERT~\citep{devlin2019bert}, which mainly adopts masked language modeling (MLM) for pre-training\footnote{We do not consider next sentence prediction here since previous works~\citep{Yang2019XLNet,liu2019roberta,joshi2019spanbert} have achieved good results without next sentence prediction.}. MLM leverages bidirectional context of masked tokens efficiently, but ignores the dependency among the masked (and to be predicted) tokens~\citep{Yang2019XLNet}. To improve BERT, XLNet~\citep{Yang2019XLNet} introduces permuted language modeling (PLM) for pre-training to capture the dependency among the predicted tokens. However, PLM has its own limitation: Each token can only see its preceding tokens in a permuted sequence but does not know the position information of the full sentence (e.g., the position information of future tokens in the permuted sentence) during the autoregressive pre-training, which brings discrepancy between pre-training and fine-tuning. Note that the position information of all the tokens in a sentence is available to BERT while predicting a masked token. In this paper, we find that MLM and PLM can be unified in one view, which splits the tokens in a sequence into non-predicted and predicted parts. Under this unified view, we propose a new pre-training method, masked and permuted language modeling (MPNet for short), which addresses the issues in both MLM and PLM while inherits their advantages: 1) It takes the dependency among the predicted tokens into consideration through permuted language modeling and thus avoids the issue of BERT; 2) It takes position information of all tokens as input to make the model see the position information of all the tokens in the sentence and thus alleviates the position discrepancy of XLNet. We pre-train MPNet on a large-scale text corpora (over 160GB data) following the practice in~\citet{Yang2019XLNet,liu2019roberta}, and fine-tune on a variety of down-streaming benchmark tasks, including GLUE, SQuAD, RACE and IMDB. Experimental results show that MPNet outperforms MLM and PLM by a large margin, which demonstrates that 1) the effectiveness of modeling the dependency among the predicted tokens (MPNet vs. MLM), and 2) the importance of the position information of the full sentence (MPNet vs. PLM). Moreover, MPNet outperforms previous well-known models BERT, XLNet and RoBERTa by 4.6, 3.2 and 1.3 points respectively on GLUE tasks under the same model setting, indicating the great potential of MPNet for language understanding\footnote{We are still pre-training MPNet in larger model setting. We also welcome someone who has computation resources to pre-train larger MPNet models based on our released code to further advance the state of the art.}. \begin{comment} \end{comment} \begin{figure*}[h] \centering \begin{subfigure}[t]{0.49\textwidth} \centering \includegraphics[width=\textwidth]{mlm2.pdf} \caption{MLM} \end{subfigure} \begin{subfigure}[t]{0.49\textwidth} \centering \includegraphics[width=\textwidth]{plm2.pdf} \caption{PLM} \end{subfigure} \vspace{-8pt} \caption{A unified view of MLM and PLM, where $x_i$ and $p_i$ represent token and position embeddings. The left side in both MLM (a) and PLM (b) are in original order, while the right side in both MLM (a) and PLM (b) are in permuted order and are regarded as the unified view.} \label{Permuted_view} \end{figure*} \section{MPNet} \subsection{Background} \label{sec_background} The key of pre-training methods~\citep{radford2018improving,devlin2019bert,song19MASS,Yang2019XLNet,clark2020electra} is the design of self-supervised tasks/objectives for model training to exploit large language corpora for language understanding and generation. For language understanding, masked language modeling (MLM) in BERT~\citep{devlin2019bert} and permuted language modeling (PLM) in XLNet~\citep{Yang2019XLNet} are two representative objectives. In this section, we briefly review MLM and PLM, and discuss their pros and cons. \paragraph{MLM in BERT} BERT~\cite{devlin2019bert} is one of the most successful pre-training models for natural language understanding. It adopts Transformer~\cite{Vaswani2017transformer} as the feature extractor and introduces masked language model (MLM) and next sentence prediction as training objectives to learn bidirectional representations. Specifically, for a given sentence $x =(x_1, x_2, \cdots, x_n)$, MLM randomly masks $15\%$ tokens and replace them with a special symbol $[M]$. Denote $\mathcal{K}$ as the set of masked positions, $x_{\mathcal{K}}$ as the set of masked tokens, and $x_{\setminus \mathcal{K}}$ as the sentence after masking. As shown in the example in the left side of Figure~\ref{Permuted_view}(a), $\mathcal{K} = \{2, 4\}$, $x_{\mathcal{K}} = \{x_2, x_4\}$ and $x_{\setminus \mathcal{K}} = (x_1, [M], x_3, [M], x_5)$. MLM pre-trains the model $\theta$ by maximizing the following objective \begin{equation} \log P(x_{\mathcal{K}}|x_{\setminus \mathcal{K}}; \theta) \approx \sum\limits_{k \in \mathcal{K}} \log P(x_k|x_{\setminus \mathcal{K}};\theta). \label{eq1_mlm} \end{equation} \paragraph{PLM in XLNet} Permuted language model (PLM) is proposed in XLNet~\cite{Yang2019XLNet} to retain the benefits of autoregressive modeling and also allow models to capture bidirectional context. For a given sentence $x =(x_1, x_2, \cdots, x_n)$ with length of $n$, there are $n!$ possible permutations. Denote $\mathcal{Z}_n$ as the permutations of set $\{1, 2, \cdots, n\}$. For a permutation $z \in \mathcal{Z}_n$, denote $z_t$ as the $t$-th element in $z$ and $z_{<t}$ as the first $t-1$ elements in $z$. As shown in the example in the right side of Figure~\ref{Permuted_view}(b), $z = (1, 3, 5, 2, 4)$, and if $t=4$, then $z_t = 2$, $x_{z_t}=x_2$ and $z_{<t} = \{ 1, 3, 5\}$. PLM pre-trains the model $\theta$ by maximizing the following objective \begin{equation} \log P(x;\theta) = \mathbb{E}_{z \in \mathcal{Z}_n} \sum\limits_{t=c+1}^{n} \log P(x_{z_t}|x_{z_{<t}};\theta), \label{eq2_plm} \end{equation} where $c$ denotes the number of non-predicted tokens $x_{z_{<=c}}$. In practice, only a part of last tokens $x_{z_{>c}}$ (usually $c = 85\%*n$) are chosen to predict and the remaining tokens are used as condition in order to reduce the optimization difficulty~\citep{Yang2019XLNet}. \paragraph{Pros and Cons of MLM and PLM} We compare MLM and PLM from two perspectives: the dependency in the predicted (output) tokens and the discrepancy between pre-training and fine-tuning in the input sentence. \begin{itemize}[leftmargin=*] \item \textbf{Output Dependency}: As shown in Equation~\ref{eq1_mlm}, MLM assumes the masked tokens are independent with each other and predicts them separately, which is not sufficient to model the complicated context dependency in natural language~\citep{Yang2019XLNet}. In contrast, PLM factorizes the predicted tokens with the product rule in any permuted order, as shown in Equation~\ref{eq2_plm}, which avoids the independence assumption in MLM and can better model dependency among predicted tokens. \item \textbf{Input Discrepancy} Since in fine-tuning of downstream language understanding tasks, a model can see the full input sentence, to reduce the discrepancy between pre-training and fine-tuning, the model should see as much information as possible of the full sentence during pre-training. In MLM, although some tokens are masked, their position information (i.e., the position embeddings) are available to the model to (partially) represent the information of full sentence (how many tokens in a sentence, i.e., the sentence length). However, each predicted token in PLM can only see its preceding tokens in a permuted sentence but does not know the position information of the full sentence during the autoregressive pre-training, which brings discrepancy between pre-training and fine-tuning. \end{itemize} As can be seen, PLM is better than MLM in terms of leveraging output dependency while worse in terms of pre-training and fine-tuning discrepancy. A natural question then arises: can we address the issues in both MLM and PLM while inherit their advantages? \begin{figure*}[!t] \centering \begin{subfigure}[t]{0.51\textwidth} \centering \includegraphics[width=\textwidth]{mpnet_1a.pdf} \caption{} \label{MPNet_a} \end{subfigure} \begin{subfigure}[t]{0.47\textwidth} \centering \includegraphics[width=\textwidth]{mpnet_2a.pdf} \caption{} \label{MPNet_b} \end{subfigure} \vspace{-10pt} \caption{(a) The structure of MPNet. (b) The attention mask of MPNet. The light grey lines in (a) represent the bidirectional self-attention in the non-predicted part $(x_{z_{<=c}},M_{z_{>c}}) =(x_1, x_5, x_3, [M], [M], [M])$, which correspond to the light grey attention mask in (b). The blue and green mask in (b) represent the attention mask in content and query streams in two-stream self-attention, which correspond to the blue, green and black lines in (a). Since some attention masks in content and query stream are overlapped, we use black lines to denote them in (a). Each row in (b) represents the attention mask for a query position and each column represents a key/value position. The predicted part $x_{z_{>c}}=(x_4, x_6, x_2)$ is predicted by the query stream.} \label{MPNet} \end{figure*} \subsection{A Unified View of MLM and PLM} To address the issues and inherit the advantages of MLM and PLM, in this section, we provide a unified view to understand MLM and PLM. Both BERT and XLNet take Transformer~\cite{Vaswani2017transformer} as their backbone. Transformer takes tokens and their positions in a sentence as input, and is not sensitive to the absolute input order of those tokens, only if each token is associated with its correct position in the sentence. This inspires us to propose a unified view for MLM and PLM, which rearranges and splits the tokens into non-predicted and predicted parts, as illustrated in Figure~\ref{Permuted_view}. For MLM in Figure~\ref{Permuted_view}(a), the input in the left side is equal to first permuting the sequence and then masking the tokens in rightmost ($x_2$ and $x_4$ are masked in the permuted sequence $(x_1,x_3,x_5,x_2,x_4)$ as shown in the right side). For PLM in Figure~\ref{Permuted_view}(b), the sequence $(x_1,x_2,x_3,x_4,x_5)$ is first permuted into $(x_1,x_3,x_5,x_2,x_4)$ and then the rightmost tokens $x_2$ and $x_4$ are chosen as the predicted tokens as shown in the right side, which equals to the left side. That is, in this unified view, the non-masked tokens are put in the left side while the masked and to be predicted tokens are in the right side of the permuted sequence for both MLM and PLM. Under this unified view, we can rewrite the objective of MLM in Equation~\ref{eq1_mlm} as \begin{equation} \mathbb{E}_{z \in \mathcal{Z}_n} \sum\limits_{t=c+1}^{n} \log P(x_{z_t}|x_{z_{<=c}}, M_{z_{>c}};\theta), \label{eq3_mlm_unify} \end{equation} where $M_{z_{>c}}$ denote the mask tokens $\rm{[M]}$ in position $z_{>c}$. As shown in the example in Figure~\ref{Permuted_view}(a), $n=5$, $c=3$, $x_{z_{<=c}} = (x_1,x_3,x_5)$, $x_{z_{>c}} = (x_2,x_4)$ and $M_{z_{>c}}$ are two mask tokens in position $z_4=2$ and $z_5=4$. We also put the objective of PLM from Equation~\ref{eq2_plm} here \begin{equation} \mathbb{E}_{z \in \mathcal{Z}_n} \sum\limits_{t=c+1}^{n} \log P(x_{z_t}|x_{z_{<t}};\theta). \label{eq4_plm_unify} \end{equation} As can be seen from Equation~\ref{eq3_mlm_unify} and~\ref{eq4_plm_unify}, under this unified view, MLM and PLM share similar mathematical formulation but just with slight difference in the conditional part in $P(x_{z_t}|\cdot;\theta)$: MLM conditions on $x_{z_{<=c}}$ and $M_{z_{>c}}$, and PLM conditions on $x_{z_{<t}}$. In the next subsection, we describe how to modify the conditional part to address the issues and inherit the advantages of MLM and PLM. \subsection{Our Proposed Method} \label{sec_fuse} Figure~\ref{MPNet} illustrates the key idea of MPNet. The training objective of MPNet is \begin{equation} \mathbb{E}_{z \in \mathcal{Z}_n} \sum\limits_{t=c+1}^{n} \log P(x_{z_t}|x_{z_{<t}}, M_{z_{>c}};\theta). \label{eq5_mpnet} \end{equation} As can be seen, MPNet conditions on $x_{z_{<t}}$ (the tokens preceding the current predicted token $x_{z_t}$) rather than only the non-predicted tokens $x_{z_{<=c}}$ in MLM as shown in Equation~\ref{eq3_mlm_unify}; comparing with PLM as shwon in Equation~\ref{eq4_plm_unify}, MPNet takes more information (i.e., the mask symbol $[M]$ in position $z_{>c}$) as inputs. Although the objective seems simple, it is challenging to implement the model efficiently. To this end, we describe several key designs of MPNet in the following paragraphs. \paragraph{Input Tokens and Positions} For a token sequence $x=(x_1, x_2, \cdots, x_{6})$ with length $n=6$, we randomly permute the sequence and get a permuted order $z=(1, 3, 5, 4, 6, 2)$ and a permuted sequence $x_{z} = (x_1, x_3, x_5, x_4, x_6, x_2)$, where the length of the non-predicted part is $c=3$, the non-predicted part is $x_{z_{<=c}} = (x_1, x_3, x_5)$, and the predicted part is $x_{z_{>c}} = (x_4, x_6, x_2)$. Additionally, we add mask tokens $M_{z_{>c}}$ right before the predicted part, and obtain the new input tokens $(x_{z_{<=c}}, M_{z_{>c}}, x_{z_{>c}})=(x_1, x_3, x_5, [M], [M], [M], x_4, x_6, x_2)$ and the corresponding position sequence $(z_{<=c},z_{>c},z_{>c})=(p_1, p_3, p_5, p_4, p_6, p_2, p_4, p_6, p_2)$, as shown in Figure~\ref{MPNet_a}. In MPNet, $(x_{z_{<=c}},M_{z_{>c}}) =(x_1, x_3, x_5, [M], [M], [M])$ are taken as the non-predicted part, and $x_{z_{>c}}=(x_4, x_6, x_2)$ are taken as the predicted part. For the non-predicted part $(x_{z_{<=c}}, M_{z_{>c}})$, we use bidirectional modeling~\cite{devlin2019bert} to extract the representations, which is illustrated as the light grey lines in Figure~\ref{MPNet_a}. Next, we describe how to model the dependency among the predicted part in next paragraph. \begin{table*}[h] \centering \begin{tabular}{l | l } \toprule \textbf{Objective} & \textbf{Factorization} \\ \midrule MLM (BERT) & $\log P($sentence $|$ the task is {\color{cyan}$\rm{[M]~ [M]}$}$)$ + $\log P($classification $|$ the task is {\color{cyan}$\rm{[M]~ [M]}$}$)$ \\ PLM (XLNet) & $\log P($sentence $|$ the task is$)$ ~~~~~~~~~~~~~~+ $\log P($classification $|$ the task is {\color{cyan}sentence}$)$ \\ \midrule MPNet & $\log P($sentence $|$ the task is {\color{magenta} $\rm{[M]~[M]}$}$)$ + $\log P($classification $|$ the task is {\color{magenta}sentence $\rm{[M]}$}$)$ \\ \bottomrule \end{tabular} \vspace{-5pt} \caption{An example sentence ``the task is sentence classification" to illustrate the conditional information of MLM, PLM and MPNet. } \label{tab_obj_example} \end{table*} \paragraph{Modeling Output Dependency with Two-Stream Self-Attention} For the predicted part $x_{z_{>c}}$, since the tokens are in permuted order, the next predicted token could occur in any position, which makes it difficult for normal autoregressive prediction. To this end, we follow PLM to adopt two-stream self-attention~\citep{Yang2019XLNet} to autoregressively predict the tokens, which is illustrated in Figure~\ref{fig_tssa}. In two-stream self-attention, the query stream can only see the previous tokens and positions as well as current position but cannot see current token, while the content stream can see all the previous and current tokens and positions, as shown in Figure~\ref{MPNet_a}. For more details about two-stream self-attention, please refer to~\citet{Yang2019XLNet}. One drawback of two-stream self-attention in PLM is that it can only see the the previous tokens in the permuted sequence, but does not know the position information of the full sentence during the autoregressive pre-training, which brings discrepancy between pre-training and fine-tuning. To address this limitation, we modify it with position compensation as described next. \begin{figure}[!t] \vspace{-10pt} \centering \includegraphics[width=0.45\textwidth]{mpnet_tssa.pdf} \caption{The two-stream self-attention mechanism used in MPNet, where the query stream re-uses the hidden from the content stream to compute key and value.} \label{fig_tssa} \end{figure} \paragraph{Reducing Input Discrepancy with Position Compensation} We propose position compensation to ensure the model can see the full sentence, which is more consistent with downstream tasks. As shown in Figure~\ref{MPNet_b}, we carefully design the attention masks for the query and content stream to ensure each step can always see $n$ tokens, where $n$ is the length of original sequence (in the above example, $n=6$)\footnote{One trivial solution is to let the model see all the input tokens, i.e., $115\%*n$ tokens, but introduces new discrepancy as the model can only see $100\%*n$ tokens during fine-tuning.}. For example, when predicting token $x_{z_5}=x_6$, the query stream in the original two-stream attention~\citep{Yang2019XLNet} takes mask token $M_{z_5}=[M]$ and position $p_{z_5}=p_6$ as the attention query, and can only see previous tokens $x_{z_{<5}}=(x_1, x_3, x_5, x_4)$ and positions $p_{z_{<5}} =(p_1, p_3, p_5, p_4)$ in the content stream, but cannot see positions $p_{z_{>=5}}=(p_6, p_2)$ and thus miss the full-sentence information. Based on our position compensation, as shown in the second last line of the query stream in Figure~\ref{MPNet_b}, the query stream can see additional tokens $M_{z>=5}=([M], [M])$ and positions $p_{z_{>=5}}=(p_6, p_2)$. The position compensation in the content stream follows the similar idea as shown in Figure~\ref{MPNet_b}. In this way, we can greatly reduce the input discrepancy between pre-training and fine-tuning. \begin{table}[!t] \centering \begin{tabular}{l | c c } \toprule \textbf{Objective} & \textbf{\# Tokens} & \textbf{\# Positions} \\ \midrule MLM (BERT) & 85\% & 100\% \\ PLM (XLNet) & 92.5\% & 92.5\% \\ \midrule MPNet & 92.5\% & 100\% \\ \bottomrule \end{tabular} \vspace{-5pt} \caption{The percentage of input information (tokens and positions) leveraged in MLM, PLM and MPNet, assuming they predict the same amount ($15\%$) of tokens.} \label{tab_obj_percent} \end{table} \subsection{Advantage} The main advantage of MPNet over BERT and XLNet is that it conditions on more information while predicting a masked token, which leads to better learnt representations and less discrepancy with downstream tasks. As shown in Table~\ref{tab_obj_example}, we take a sentence $\rm{[The, task, is, sentence, classification]}$ as an example to compare the condition information of MPNet/BERT/XLNet. Suppose we mask two words $\rm{[sentence, classification]}$ for prediction. As can be seen, while predicting a masked word, MPNet conditions on all the position information to capture a global view of the sentence (e.g., the model knows that there two missing tokens to predict, which is helpful to predict two tokens ``sentence classification" instead of three tokens ``sentence pair classification"). Note that PLM does not have such kind of information. Furthermore, to predict a word, MPNet conditions on all preceding tokens including the masked and predicted ones for better context modeling (e.g., the model can better predict ``classification" given previous token ``sentence", instead of predicting ``answering" as if to predict ``question answering"). In contrast, MLM does not condition on other masked tokens. Based on the above example, we can derive Table~\ref{tab_obj_percent}, which shows how much conditional information is used on average to predict a masked token in each pre-training objective. We assume all the three objectives mask and predict the same amount of tokens ($15\%$), following the common practice in BERT~\citep{devlin2019bert} and XLNet~\citep{Yang2019XLNet}\footnote{XLNet masks and predicts 1/7 tokens, which are close to $15\%$ predicted tokens.}. As can be seen, MLM conditions on $85\%$ tokens and $100\%$ positions since masked tokens contains position information; PLM conditions on all the $85\%$ unmasked tokens and positions and $15\%/2=7.5\%$ masked tokens and positions\footnote{PLM is actually a language model, which predicts the $i$-th token given the previous $i-1$ tokens. Therefore, the number of tokens can be leveraged on average is $(n-1)/2$ where $n$ is number of predicted tokens.}, resulting in $92.5\%$ tokens and positions in total. MPNet conditions on $92.5\%$ tokens similar to PLM, but $100\%$ positions like that in MLM thanks to the position compensation. To summarize, MPNet utilizes the most information while predicting masked tokens. On the one hand, MPNet can learn better representations with more information as input; on the other hand, MPNet has the minimal discrepancy with downstream language understanding tasks since $100\%$ token and position information of an input sentence is available to a model for those tasks (e.g., sentence classification tasks). \begin{table*}[h] \centering \begin{tabular}{l|c c c c c c c c | c} \toprule \small & \textbf{MNLI} & \textbf{QNLI} & \textbf{QQP} & \textbf{RTE} & \textbf{SST} & \textbf{MRPC} & \textbf{CoLA} & \textbf{STS} & \textbf{Avg} \\ \midrule \multicolumn{10}{l}{\emph{Single model on dev set}} \\ \midrule BERT\small{~\citep{devlin2019bert}} & 84.5 & 91.7 & 91.3 & 68.6 & 93.2 & 87.3 & 58.9 & 89.5 & 83.1\\ XLNet\small{~\citep{Yang2019XLNet}} & 86.8 & 91.7 & 91.4 & 74.0 & 94.7 & 88.2 & 60.2 & 89.5 & 84.5\\ RoBERTa\small{~\citep{liu2019roberta}} & 87.6 & 92.8 & \textbf{91.9} & 78.7 & 94.8 & 90.2 & 63.6 & \textbf{91.2} & 86.4\\ \midrule MPNet & \textbf{88.5} & \textbf{93.3} & \textbf{91.9} & \textbf{85.2} & \textbf{95.4} & \textbf{91.5} & \textbf{65.0} & 90.9 & \textbf{87.7} \\ \bottomrule \toprule \multicolumn{10}{l}{\emph{Single model on test set}} \\ \midrule BERT\small{~\citep{devlin2019bert}} & 84.6 & 90.5 & 89.2 & 66.4 & 93.5 & 84.8 & 52.1 & 87.1 & 79.9\\ ELECTRA\small{~\citep{clark2020electra}} & \textbf{88.5} & \textbf{93.1} & 89.5 & 75.2 & \textbf{96.0} & 88.1 & \textbf{64.6} & \textbf{91.0} & 85.8\\ \midrule MPNet & \textbf{88.5} & 93.0 & \textbf{89.6} & \textbf{80.5} & 95.6 & \textbf{88.2} & 64.0 & 90.7 & \textbf{86.3} \\ \bottomrule \end{tabular} \caption{Comparisons between MPNet and the previous strong pre-trained models under $\text{BERT}_{\small \text{BASE}}$ setting on the dev and test set of GLUE tasks. We only list the results on each set that are available in the published papers. STS is reported by Pearman correlation, CoLA is reported by Matthew's correlation, and other tasks are reported by accuracy.} \label{GLUE} \end{table*} \iffalse \begin{table*}[h] \small \centering \begin{tabular}{l|c c c c c c c c | c} \toprule & MNLI & QNLI & QQP & RTE & SST-2 & MRPC & CoLA & STS & Avg \\ \midrule \multicolumn{10}{l}{\emph{Single model on dev set}} \\ \midrule BERT~\citep{devlin2019bert} & 86.6/- & 92.3 & 91.3 & 70.4 & 93.2 & 88.0 & 60.6 & 90.0 & 84.1 \\ MLM & 86.8/- & 92.7 & 91.3 & 74.0 & 93.9 & 88.1 & 62.6 & 90.1 & 84.9 \\ PLM & 86.9/- & 92.9 & 91.4 & 74.9 & 93.8 & 88.5 & 62.9 & 90.3 & 85.2 \\ MPNet & 88.1/- & 94.1 & 91.8 & 80.9 & 95.0 & 88.9 & 66.6 & 91.5 & \textbf{87.1} \\ \midrule \multicolumn{10}{l}{\emph{Single model on test set}} \\ \midrule BERT~\citep{devlin2019bert} & 86.7/85.9 & 92.7 & 89.3 & 70.1 & 94.9 & 89.3 & 60.5 & 86.5 & 84.0 \\ MPNet & 88.0/87.1 & 94.1 & 89.9 & 80.1 & 95.5 & 90.2 & 66.2 & 89.3 & \textbf{86.7} \\ \bottomrule \end{tabular} \vspace{-5pt} \caption{Comparisons between MPNet and the baseline methods MLM and PLM, as well as BERT~\citep{devlin2019bert} on the dev set and test set of GLUE tasks. MNLI: matched/mismatched accuracies. STS: Spearman correlation, CoLA: Matthew's correlation.} \label{GLUE} \end{table*} \fi \section{Experiments and Results} \subsection{Experimental Setup} We conduct experiments under the BERT base setting ($\text{BERT}_{\small \text{BASE}}$)~\citep{devlin2019bert}, where the model consists of 12 transformer layers, with 768 hidden size, 12 attention heads as 12, and 110M model parameters in total. For the pre-training objective of MPNet, we randomly permute the sentence following PLM~\citep{Yang2019XLNet}\footnote{Note that we only improve upon PLM in XLNet, and we do not use long-term memory in XLNet.}, choose the rightmost $15\%$ tokens as the predicted tokens, and prepare mask tokens following the same 8:1:1 replacement strategy in BERT~\citep{devlin2019bert}. Additionally, we also apply whole word mask~\cite{Yiming2019WWM} and relative positional embedding~\cite{shaw-etal-2018-self}\footnote{We follow~\citet{2019t5} to adopt a shared relative position embedding across each layer for efficiency.} in our model pre-training since these tricks have been successfully validated in previous works~\citep{Yang2019XLNet,2019t5}. For pre-training corpus, we follow the data used in RoBERTa~\citep{liu2019roberta}, which includes: Wikipedia and BooksCorpus~\cite{Zhu_2015_ICCV}, OpenWebText~\cite{radford2019GPT2}, CC-News~\cite{Yinhan2019Roberta} and Stories~\cite{Trieu2018Stories}, with 160GB data size in total. We use a sub-word dictionary with 30K BPE codes in BERT~\cite{devlin2019bert} to tokenize the sentences. We limit the length of sentences in each mini-batch up to 512 tokens following the previous practice~\cite{Yinhan2019Roberta,joshi2019spanbert} and use a batch size of 8192 sentences. We use Adam~\cite{kingma2014method} with $\beta_1 = 0.9$, $\beta_2 = 0.98$ and $\epsilon = 1e-6$. We pre-train our model for 500K steps to be comparable with state-of-the-art models like XLNet~\citep{Yang2019XLNet}, RoBERTa~\citep{liu2019roberta} and ELECTRA~\cite{clark2020electra}. We use 32 NVIDIA Tesla V100 GPUs, with 32GB memory and FP16 for pre-training, which is estimated to take 35 days\footnote{Note that MPNet is still under pre-training with only 270K steps, but has already outperformed previous models. We will update the results once pre-trained for 500K steps.}. During fine-tuning, we do not use query stream in two-stream self-attention and use the original hiddens to extract context representations following ~\citet{Yang2019XLNet}. The fine-tuning experiments on each downstream tasks are conducted 5 times and the median value is chosen as the final result. For experimental comparison, we mainly compare MPNet with previous state-of-the-art pre-trained models using the same $\text{BERT}_{\text{BASE}}$ setting unless otherwise stated. We will also pre-train MPNet in $\text{BERT}_{\text{LARGE}}$ setting in the future. \iffalse \begin{table*}[h] \centering \begin{tabular}{l| c c | r r|r r|c c} \toprule \multirow{2}{*}{Model} & \multirow{2}{*}{wwm} & \multirow{2}{*}{rel} & \multicolumn{2}{c|}{SQuAD v1.1} & \multicolumn{2}{c|}{SQuAD v2.0} & \multirow{2}{*}{MNLI} & \multirow{2}{*}{SST-2}\\ & & & EM & F1 & EM & F1 & & \\ \midrule MPNet & \Checkmark & \Checkmark & & & 80.5 & 83.3 & 86.2 & 94.0 \\ & & \Checkmark & & & 80.0 & 82.8 & 85.6 & 93.8 \\ & \Checkmark & & & & 79.8 & 82.6 & 85.3 & 93.6 \\ & & & 82.2 & 89.6 & 77.7 & 80.7 & 84.8 & 93.4 \\ \bottomrule \end{tabular} \caption{Ablation Study} \label{tab:my_label} \end{table*} \fi \iffalse \subsection{Implementation and Evaluation} We implement MPNet as well as the pre-training and fine-tuning pipeline on fairseq~\cite{ott2019fairseq}. Following BERT~\citep{devlin2019bert}, we use English Wikipedia and BooksCorpus (WikiBooks, with 16GB size) as the pre-training corpus. We train 1M steps with a batch size of 256 sequences. According to the previous works~\cite{Joshi2019Spanbert,Yinhan2019Roberta}, we do not use next sentence prediction (NSP) task and limit the length of the consecutive sentence as up to 512 tokens. We randomly mask $15\%$ tokens in each batch following the masking strategy in~\citet{devlin2019bert}. We follow the base and large model setting in BERT~\citep{devlin2019bert} as the model configurations of MPNet, and list configuration details in the supplementary materials. For fair comparison, we also use the same model settings to train MLM and PLM\footnote{We do not use recurrent segment, relative positional embedding and span based prediction for PLM as used in XLNet~\citep{Yang2019XLNet}, due to that our work focuses to address the problems in MLM and PLM, but not aims to introduce advanced tricks and large-scale data and model for pre-training.}. The models are trained on single DGX-2 machine with 16 NVIDIA 32GB Tesla V100 GPUs, with FP16 for speedup. During fine-tuning, we let the model see the full sentence with bidirectional self-attention. Following previous practice~\citep{devlin2019bert,Yang2019XLNet}, we evaluate our method on General Language Understanding Evaluation (GLUE) datasets~\cite{wang2019glue} and Standford Question Answering Dataset (SQuAD v1.1~\cite{rajpurkar2016squad} and SQuAD v2.0~\cite{rajpurkar2018know}). \fi \subsection{Results on GLUE Benchmark} The General Language Understanding Evaluation (GLUE)~\cite{wang2019glue} is a collection of 9 natural language understanding tasks, which include two single-sentence tasks (CoLA~\cite{Alex2018CoLA}, SST-2~\cite{socher2013sst}), three similarity and paraphrase tasks (MRPC~\cite{dolan2005mrpc}, STS-B~\cite{cer2017stsb}, QQP), four inference tasks (MNLI~\cite{williams2018mnli}, QNLI~\cite{rajpurkar2016squad}, RTE~\cite{dagan2006rte}, WNLI~\cite{winograd2012wnli}). We follow RoBERTa hyper-parameters for single-task fine-tuning, where RTE, STS-B and MRPC are started from the MNLI fine-tuned model. We list the results of MPNet and other existing strong baselines in Table~\ref{GLUE}. All of the listed results are reported in $\text{BERT}_{\text{BASE}}$ setting and from single model without any data augmentation for fair comparisons. On the dev set of GLUE tasks, MPNet outperforms BERT~\citep{devlin2019bert}, XLNet~\citep{Yang2019XLNet} and RoBERTa~\citep{liu2019roberta} by 4.6, 3.2, 1.3 points on average. On the test set of GLEU tasks, MPNet outperforms ELECTRA~\citep{clark2020electra}, which achieved previous state-of-the-art accuracy on a variety of language understanding tasks, by 0.5 point on average, demonstrating the advantages of MPNet for language understanding. Since MPNet is still under pre-training, we believe there still exists large improvement space for MPNet. \begin{table}[!t] \centering \begin{tabular}{l|r r} \toprule \textbf{SQuAD v1.1} & \textbf{EM} & \textbf{F1} \\ \midrule BERT{~\citep{devlin2019bert}} & 80.8 & 88.5 \\ RoBERTa~\citep{liu2019roberta} & 84.6 & 91.5 \\ \midrule MPNet & \textbf{86.8} & \textbf{92.5} \\ \bottomrule \toprule \textbf{SQuAD v2.0} & \textbf{EM} & \textbf{F1} \\ \midrule BERT{~\citep{devlin2019bert}} & 73.7 & 76.3 \\ XLNet~\citep{Yang2019XLNet} & 80.2 & - \\ RoBERTa~\citep{liu2019roberta} & 80.5 & 83.7 \\ \midrule MPNet & \textbf{82.8} & \textbf{85.6} \\ \bottomrule \end{tabular} \vspace{-5pt} \caption{Comparison between MPNet and the previous strong pre-trained models under $\text{BERT}_{\small \text{BASE}}$ setting on the SQuAD dev set. We report results by exact match (EM) and F1 score.} \label{SQuAD} \end{table} \subsection{Results on Question Answering (SQuAD) } The Stanford Question Answering Dataset (SQuAD) task requires to extract the answer span from the provided context based on the question. We evaluate our model on SQuAD v1.1~\cite{rajpurkar2016squad} and SQuAD v2.0~\cite{rajpurkar2018know}. SQuAD v1.1 always exists the corresponding answer for each question and the corresponding context, while some questions do not have the corresponding answer in SQuAD v2.0. For v1.1, we add a classification layer on the outputs from the pre-trained model to predict whether the token is a start or end position of the answer. For v2.0, we additionally add a binary classification layer to predict whether the answer exists. \begin{table*}[h] \centering \begin{tabular}{l|c c | c c | c c} \toprule & \multicolumn{2}{c|}{\textbf{SQuAD v1.1}} & \multicolumn{2}{c|}{\textbf{SQuAD v2.0}} & \multicolumn{2}{c}{\textbf{GLUE}} \\ \textbf{Model Setting} & EM & F1 & EM & F1 & MNLI & SST-2 \\ \midrule MPNet & \textbf{85.0} & \textbf{91.4} & \textbf{80.5} & \textbf{83.3} & \textbf{86.2} & \textbf{94.0} \\ \midrule ~$-$ position compensation ( = PLM) & 83.0 & 89.9 & 78.5 & 81.0 & 85.6 & 93.4 \\ ~$-$ permutation ( = MLM + output dependency) & 84.1 & 90.6 & 79.2 & 81.8 & 85.7 & 93.5 \\ ~$-$ permutation \& output dependency ( = MLM) & 82.0 & 89.5 & 76.8 & 79.8 & 85.6 & 93.3 \\ \bottomrule \end{tabular} \vspace{-5pt} \caption{Ablation study of MPNet under $\text{BERT}_{\text{BASE}}$ setting on the dev set of SQuAD tasks (v1.1 and v2.0) and GLUE tasks (MNLI and SST-2). The experiments in ablation study are all pre-trained on the Wikipedia and BooksCorpus (16GB size) for 1M steps, with a batch size of 256 sentences, each sentence with up to 512 tokens.} \label{tab_ablation} \end{table*} The results of MPNet on SQuAD dev set are reported on Table~\ref{SQuAD}. All of the listed results are reported in $\text{BERT}_{\text{BASE}}$ setting and from single model without any data augmentation for fair comparisons. It can be seen that MPNet outperforms BERT, XLNet and RoBERTa by a large margin, both in SQuAD v1.1 and v2.0, which are consistent with the results on GLUE tasks, demonstrating the advantages of MPNet. \begin{table}[!t] \centering \begin{tabular}{l|c c c | c} \toprule &\multicolumn{3}{c|}{\textbf{RACE}} & \textbf{IMDB} \\ &\textbf{Acc.} & \textbf{Middle} & \textbf{High} & \textbf{Err.} \\ \midrule BERT* & 65.0 & 71.7 & 62.3 & 5.4 \\ XLNet* & 66.8 & - & - & 4.9 \\ \midrule MPNet* & 70.4 & \textbf{76.8} & 67.7 & 4.8\\ MPNet & \textbf{72.0} & 76.3 & \textbf{70.3} & \textbf{4.4} \\ \bottomrule \end{tabular} \caption{Results on the RACE and IMDB test set under $\text{BERT}_{\text{BASE}}$ setting. For RACE, the results of BERT are from the RACE leaderboard\protect\footnotemark and the results of XLNet are obtained from the original paper~\citep{Yang2019XLNet}. ``Middle'' and ``High'' denote the accuracy on the middle school set and high school set in RACE. For IMDB, the result of BERT is from \citet{Chi2019IMDB} and the result of XLNet is ran by ourselves with only PLM pre-training objective but no long context memory~\citep{Yang2019XLNet}. ``*" represents pre-training only on Wikipedia and BooksCorpus (16GB size).} \label{race_imdb} \end{table} \footnotetext{http://www.qizhexie.com/data/RACE\_leaderboard.html} \subsection{Results on RACE} The ReAding Comprehension from Examinations (RACE)~\cite{lai2017race} is a large-scale dataset collected from the English examinations from middle and high school students. In RACE, each passage has multiple questions and each question has four choices. The task is to select the correct choice based on the given options. The results on RACE task are listed in Table~\ref{race_imdb}. We can only find the results from BERT and XLNet pre-trained on Wikipedia and BooksCorpus (16GB data). For a fair comparison, we also pre-train MPNet on 16GB data (marked as * in Table~\ref{race_imdb}). MPNet greatly outperforms BERT and XLNet across the three metrics, demonstrating the advantages of MPNet. When pre-training MPNet with the default 160GB data, an additional 1.6 points gain (72.0 vs. 70.4) can be further achieved. \iffalse \begin{table}[h] \centering \begin{tabular}{l|c } \toprule & Error \\ \midrule BERT* & 5.4 \\ XLNet (PLM)* & 4.9 \\ \midrule MPNet* & 4.8 \\ MPNet & \textbf{4.4} \\ \bottomrule \end{tabular} \caption{Results of \emph{BASE setting} on the imdb test set based on single model. The result of BERT is from ~\citep{Chi2019IMDB}. PLM result is rerun by ourselves. ``*'' means using Wikibooks dataset (16GB size).} \label{imdb} \end{table} \fi \subsection{Results on IMDB} We further study MPNet on the IMDB text classification task~\cite{maas-EtAl2011imdb}, which contains over 50,000 movie reviews for binary sentiment classification. The results are reported in Table~\ref{race_imdb}. It can be seen that MPNet trained on Wikipedia and BooksCorpus (16GB data) outperform BERT and PLM (XLNet) by 0.6 and 0.1 point. When pre-training with 160GB data, MPNet achieves additional 0.4 point gain. \subsection{Ablation Study} We further conduct ablation studies to analyze several design choices in MPNet, including introducing dependency among predicted tokens to MLM, introducing position compensation to PLM, etc. The results are shown in Table~\ref{tab_ablation}. We have several observations: \begin{itemize}[leftmargin=*] \item After removing position compensation, MPNet degenerates to PLM, and its accuracy drops by 0.6-2.3 points in downstream tasks. This demonstrates the effectiveness of position compensation and the advantage of MPNet over PLM. \item After removing permutation operation but still keeping the dependency among the predicted tokens with two-stream attention (\emph{i.e.}, MLM + output dependency), the accuracy drops slightly by 0.5-1.7 points. This verifies the gain of permutation used in MPNet. \item If removing both permutation and output dependency, MPNet degenerates to MLM, and its accuracy drops by 0.5-3.7 points, demonstrating the advantage of MPNet over MLM. \end{itemize} \iffalse From the above ablation experiments, we can conclude that \begin{itemize}[leftmargin=*] \item PLM indeed has advantage over MLM (0.6-2.3 points drop in PLM vs. 0.5-3.7 points drop in MLM in Table~\ref{tab_ablation}). \item Although one motivation of PLM is to solve the drawbacks of MLM, we find that PLM does not improve MLM well\footnote{Although we improve upon PLM in this paper, we do not challenge the value of PLM in XLNet, and we also appreciate the techniques such as two-stream self-attention, permutation and long-term memory proposed in XLNet.}, since simply adding output dependency on MLM (``MLM + output dependency" in Table~\ref{tab_ablation}) achieves higher accuracy than PLM (``PLM" in Table~\ref{tab_ablation}). \item PLM solves the output dependency issue in MLM, but discards the advantage of MLM (seeing the full sentence). Therefore, MPNet addresses the problems in MLM and PLM by combining the best of both worlds, and achieves much better accuracy. \end{itemize} \fi \section{Conclusion} In this paper, we proposed MPNet, a novel pre-training method that addresses the problems of MLM in BERT and PLM in XLNet. MPNet leverages the dependency among the predicted tokens through permuted language modeling and makes the model to see auxiliary position information to reduce the discrepancy between pre-training and fine-tuning. Experiments on various tasks demonstrate that MPNet outperforms MLM and PLM, as well as previous strong pre-trained models such as BERT, XLNet, RoBERTa by a large margin. In the future, we will pre-train MPNet with larger model setting for better performance, and apply MPNet on more diverse language understanding tasks.
{'timestamp': '2020-04-21T02:27:20', 'yymm': '2004', 'arxiv_id': '2004.09297', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09297'}
arxiv
\section{Introduction} \label{sec:intro} Automatic speech recognition (ASR) performance in difficult reverberant and noisy conditions has improved tremendously in the last decade \cite{VirtanenTechniquesNoiseRobustness2012, Li2015, newera, Vincent2018, Makino2018, haeb2019speech}. This can be attributed to advances in speech processing, audio enhancement, and machine learning, but also to the availability of real speech corpora recorded in cars \cite{SpeechDat-_Car_1, CUMove}, quiet indoor environments \cite{TED, MC-WSJ-AV_PASCAL_SSC2_2012_MMA_REVERB_RealData_2}, noisy indoor and outdoor environments \cite{CHiME3, CHiME4}, and challenging broadcast media \cite{ETAPE, MGB}. Among the applications of robust ASR, voice command in domestic environments has attracted a great deal of interest recently, due in particular to the release of the Amazon Echo, Google Home and other devices targeting home automation and multimedia systems. The CHiME-1 \cite{Barker2013} and CHiME-2 \cite{CHiME_1_CHiME_2_Grid_1} challenges and corpora have contributed to popularizing research on this topic, together with the DICIT \cite{DICIT_1}, Sweet-Home \cite{SweetHome}, and DIRHA \cite{Ravanelli2015} corpora. These corpora feature single-speaker reverberant and/or noisy speech recorded or simulated in a single home, which precludes the use of modern speech enhancement techniques based on machine learning. The two voiceHome corpora \cite{voiceHome,voiceHome2} address this issue, but they are fairly small. In parallel to research on acoustic robustness, research on conversational speech recognition has also made great progress, as illustrated by the recent announcements of super-human performance \cite{Xiong2017, Saon2017} achieved on the Switchboard telephone conversation task \cite{Switchboard} and by the ASpIRE challenge \cite{harper2015automatic}. Distant-microphone recognition of noisy, overlapping, conversational speech is now widely believed to be the next frontier. Early attempts in this direction can be traced back to the ICSI \cite{ICSI}, CHIL \cite{CHIL}, and AMI \cite{AMI} meeting corpora, the LLSEC \cite{LLSEC} and COSINE \cite{COSINE} face-to-face interaction corpora, and the Sheffield Wargames corpus \cite{SWC}. These corpora were recorded using advanced microphone array prototypes which are not commercially available, and as result could only be installed in a few laboratory rooms. The VOiCES corpus \cite{richey2018voices} utilizes an ad-hoc array of commercial microphones, with pre-recorded speech and noise played over speakers. The DIPCO corpus \cite{van2019dipco}, inspired by the CHiME-5 challenge \cite{Fifth-Barker2018} but of shorter duration, provides recordings of dinner table interactions between four participants recorded simultaneously on several commercially available microphone arrays. The Santa Barbara Corpus of Spoken American English [30] stands out as the only large-scale corpus of naturally occurring spoken interactions between a wide variety of people recorded in real everyday situations including face-to-face or telephone conversations, card games, food preparation, on-the-job talk, story-telling, and more. Unfortunately, it was recorded via a single microphone. The CHiME-6 challenge, which builds upon CHiME-5 \cite{Fifth-Barker2018}, targets the problem of distant microphone conversational speech recognition in everyday home environments. The speech material has been collected from twenty real dinner parties that have taken place in real homes. The recordings have been made using multiple commercially available 4-channel microphone arrays and have been fully transcribed. The challenge features: \begin{itemize}[noitemsep] \item simultaneous recordings from multiple microphone arrays; \item real conversation, i.e.~talkers speaking in a relaxed and unscripted fashion; \item a range of room acoustics from 20 different homes each with two or three separate recording areas; \item real domestic background noises, e.g., kitchen appliances, air conditioning, movement, etc. \end{itemize} In the following, we introduce the recording scenario and the two proposed challenge tracks in Section \ref{sec:scenario}. We describe the software baselines and the challenge instructions for Tracks 1 and 2 in Sections \ref{sec:track1_software} and \ref{sec:track2_software}, respectively. We report the corresponding results in Section \ref{sec:results} and conclude in Section \ref{sec:summary}. More details can be found on the challenge website: \\ \centerline{\url{https://chimechallenge.github.io/chime6/}} \section{Scenario and tracks} \label{sec:scenario} \subsection{The scenario}\label{the-scenario} The dataset is made up of the recording of twenty separate dinner parties taking place in real homes. Each dinner party has four participants --- two acting as hosts and two as guests. The party members are all friends who know each other well and who are instructed to behave naturally. Efforts have been taken to make the parties as natural as possible. The only constraints are that each party should last a minimum of 2 hours and should be composed of three phases, each corresponding to a different location: \begin{itemize} \item kitchen: preparing the meal in the kitchen area \item dining: eating the meal in the dining area \item living: a post-dinner period in a separate living room area \end{itemize} Participants have been allowed to move naturally from one location to another but with the instruction that each phase should last at least 30 minutes. Participants are free to converse on topics of their choosing --- there is no artificial scenario. Some personally identifying material has been redacted post-recording as part of the consent process. Background television and commercial music has been disallowed in order to avoid capturing copyrighted content. \subsection{The recording set up}\label{the-recording-set-up} Each party has been recorded with a set of six Microsoft Kinect devices. The devices have been strategically placed such that there are always at least two capturing the activity in each location. Each Kinect device has a linear array of 4 sample-synchronised microphones and a camera. The raw microphone signals and video have been recorded. Each Kinect is recorded onto a separate laptop computer. In addition to the Kinects, to facilitate transcription, each participant is wearing a set of Soundman OKM II Classic Studio binaural microphones. The audio from these is recorded via a Soundman A3 adapter onto Tascam DR-05 stereo recorders being worn by the participants. The recordings have been divided into training, development test, and evaluation test sets. Each set features non-overlapping homes and speakers. For more details about these datasets, see \cite{Fifth-Barker2018}. \subsection{Tracks} \label{tracks} For the first time, the challenge moves beyond automatic speech recognition (ASR) and also considers the task of diarization, i.e., estimating the start and end times and the speaker label of each utterance. The challenge features two tracks: \begin{enumerate} \item ASR only: recognise a given evaluation utterance given ground truth diarization information, \item diarization+ASR: perform both diarization and ASR \end{enumerate} Both tracks are multi-array, i.e., all microphones of all arrays can be used. Track 1 is a rerun of the CHiME-5 challenge \cite{Fifth-Barker2018} and Track 2 is similar to the ``Diarization from multichannel audio using system SAD'' track of the DIHARD II challenge \cite{ryant2019second}, with the following key differences: \begin{itemize} \item an \textbf{accurate array synchronization} script is provided, \item the \textbf{impact of diarization error on speech recognition error} will be measured, \item \textbf{upgraded, state-of-the-art baselines} are provided for diarization, enhancement, and recognition. \end{itemize} These baselines and related implementations are integrated in the Kaldi speech recognition toolkit \cite{Kaldi-Povey2011} as a recipe. For each track, we will produce two separate ASR rankings: \begin{itemize} \item[\textbf{A}] Systems based on conventional acoustic modeling and official language modeling: the outputs of the acoustic model must remain frame-level tied phonetic (senone) targets and the lexicon and language model must not be changed compared to the conventional ASR baseline, \item[\textbf{B}] All other systems, including systems based on the end-to-end ASR baseline or systems whose lexicon and/or language model have been modified. \end{itemize} Ranking \textbf{A} focuses on acoustic robustness only, while ranking \textbf{B} addresses all aspects of the scenario. \section{Track 1} \label{sec:track1_software} Concerning Track 1, we provide baseline systems for array synchronization, speech enhancement, and speech recognition. All systems are integrated in the Kaldi CHiME-6 recipe\footnote{\url{https://github.com/kaldi-asr/kaldi/tree/master/egs/chime6/s5_track1}}. \subsection{Overview}\label{sec:track1_software_overview} The main script (\texttt{run.sh}) executes array synchronization, data preparation, data augmentation, feature extraction, Gaussian mixture model - hidden Markov model (GMM-HMM) training, data cleaning, and chain model training. After training, \texttt{run.sh} calls the inference script (\texttt{local/decode.sh}), which includes speech enhancement and recognition given the trained model. Participants can also execute \texttt{local/decode.sh} independently with their own ASR models or pre-trained models downloaded from the Kaldi model storage site\footnote{\url{http://kaldi-asr.org/models/m12}}. Detailed technical descriptions of system components can be found in \cite{acoustic-manohar2019}. We outline the process below. \begin{enumerate} \item Array synchronization (stage 0)\\ This stage first downloads the array synchronization tool, and generates the synchronized audio files across arrays along with their corresponding JSON files. Note that this requires sox v14.4.2, which is installed via miniconda in \texttt{./local/check\_tools.sh}. Details of the array synchronization procedure are presented in Section~\ref{sec:array-synchronization}. \item Data, dictionary, and language model (stages 1--3)\\ These stages prepare data directories, the lexicon, and language models in the format expected by Kaldi. The lexicon has a 127,712 word vocabulary. We use a maximum entropy-based 3-gram language model, which achieves the best perplexity on the development set. \item Data augmentation (stages 4--7)\\ In these stages, we augment and fix the training data. Point source noises are extracted from the noise regions in the CHiME-6 corpus. Here, we use a subset of 400~k utterances from the array microphones, their augmentations, and all worn microphone utterances during training. We did not include enhanced speech data for training to maintain the simplicity of the system. \item Feature extraction (stage 8)\\ We extract 13-dimensional Mel-frequency cepstral coefficient (MFCC) features for GMM-HMM systems. \item GMM training (stages 9--13)\\ These stages train monophone and triphone GMM-HMM models. These models are used for cleaning training data and generating lattices for training the chain model. \item Data cleaning (stage 14)\\ This stage performs cleanup of the training data using the GMM model. \item Chain model training (stage 15)\\ We use a factorized time delay neural network (TDNN-F) adapted from the Switchboard recipe 7q model \cite{semiorthogonal-povey2018}. \item Decoding (stage 16)\\ This stage performs speech enhancement and recognition for the test set. This stage calls \texttt{local/decode.sh}, which includes speech enhancement (described in Section~\ref{sec:speech-enhancement}) and decoding and scoring (described in Section~\ref{sec:decoding-and-scoring}). \end{enumerate} \subsection{Array synchronization}\label{sec:array-synchronization} The new array synchronisation baseline is available on GitHub\footnote{\url{https://github.com/chimechallenge/chime6-synchronisation}}. It compensates for two separate issues: \emph{audio frame-dropping} (which affects the Kinect devices only) and \emph{clock-drift} (which affects all devices). It operates in the following two stages: \begin{enumerate} \item \emph{Frame-dropping} is compensated by inserting 0's into the signals where samples have been dropped. These locations have been detected by comparing the Kinect audio with an uncorrupted stereo audio signal recovered from the video AVI files that were recorded (but not made publicly available). The frame-drop locations have been precomputed and stored in the file \texttt{chime6\_audio\_edits.json}, which is then used to drive the synchronisation software. \item \emph{Clock-drift} is computed by comparing each device's signal to the session's `reference' binaural recordings (the binaural mic of the speaker with the lowest ID number). Specifically, cross-correlation is used to estimate delays between the device and the reference at regular intervals throughout the recording session. A relative speed-up or slow-down can then be approximated using a linear fit through these estimates. The signal is then synchronised to the reference using a \texttt{sox} command to adjust the speed of the signal appropriately. This adjustment is typically very subtle, i.e., less than 100~ms over a 2.5~h recording session. Note, the approach failed for devices \emph{S01\_U02} and \emph{S01\_U05} which appear to have temporarily changed speeds during the recording session and have required a piece-wise linear fit. The adjustments for clock-drift compensation have been precomputed and the parameters to drive the \texttt{sox} commands are stored in \texttt{chime6\_audio\_edits.json}. \end{enumerate} Note, after frame-drop and clock-drift compensation, the WAV files that are generated for each device will have slightly different durations. For each session, device signals can be safely truncated to the duration of the shortest signal across devices, but this step is not performed by the synchronisation tool. Finally, the CHiME-5 transcript JSON files are processed to fit the new alignment. In the new version, utterances will have the \textit{same} start and end time on every device. \subsection{Speech enhancement}\label{sec:speech-enhancement} We provide two baseline speech enhancement front-ends based on open-source implementations of guided source separation (GSS) \cite{boeddeker2018front} and BeamformIt \cite{Acoustic-Anguera2007}, respectively. Both of them are combined with an open source version \cite{NaraWPE-Drude2018} of weighted prediction error (WPE) dereverberation \cite{nakatani2010speech}, and integrated into our Kaldi recipe. They can be installed in the Kaldi tool installation directory. The first front-end consists of WPE, a spatial mixture model that uses time annotations (GSS), beamforming. They are applied to multiple arrays. GSS is performed with the setup of \texttt{multiarray=outer\_array\_mics} meaning that only the first and last microphones of each array are used. This is the default speech enhancement front-end for the CHiME-6 Track 1 recipe. The alternative front-end applies WPE based dereverberation and weighted delay-and-sum beamforming (BeamformIt) to the reference array. Users can easily switch from GSS to BeamformIt by specifying the enhancement option (e.g., \texttt{--enhancement beamformit}). \subsection{Decoding and scoring}\label{sec:decoding-and-scoring} We perform two-stage decoding, which refines i-vector extraction based on the first pass decoding result to achieve robust decoding of noisy speech \cite{acoustic-manohar2019}. We also provide a scoring script for both development and evaluation: \texttt{local/} \texttt{score\_for\_submit.sh}. The language model weight and insertion penalty are optimized based on the development set. Note that, during scoring, we filter the tags ({[}noise{]}, {[}inaudible{]}, {[}laughs{]}, and {[}redacted{]}), and normalize ambiguous filler words\footnote{For example, we perform the following replacements to filter out variants of the filler word `hmm': \texttt{sed -e 's/\textbackslash<mhm\textbackslash>/hmm/g; s/\textbackslash<mm\textbackslash>/hmm/g; s/\textbackslash<mmm\textbackslash>/hmm/g;'}. The actual filtering rules can be found in \texttt{local/wer\_output\_filter}.}. \section{Track 2} \label{sec:track2_software} Concerning Track 2, we provide baseline systems for array synchronization, speech enhancement, speech activity detection (SAD), speaker diarization, and speech recognition. All systems are integrated in the Kaldi CHiME-6 recipe\footnote{\url{https://github.com/kaldi-asr/kaldi/tree/master/egs/chime6/s5_track2}}. \subsection{Overview}\label{overview} The main script (\texttt{run.sh}) is similar to \texttt{run.sh} in Track 1 as described in Section \ref{sec:track1_software}, which performs array synchronization, data preparation, data augmentation, feature extraction, GMM-HMM training, data cleaning, and chain model training. \texttt{run.sh} in Track 2 additionally includes SAD model training on the CHiME-6 dataset, and diarization model training on the VoxCeleb dataset \cite{nagrani2020voxceleb}. We allow the participants to use VoxCeleb in addition to CHiME-6 data, since it is necessary to build a good diarization system. After training, \texttt{run.sh} finally calls the inference script (\texttt{local/decode.sh}), which performs speech enhancement, SAD, speaker diarization, and speech recognition based on the trained models. Participants can also execute \texttt{local/} \texttt{decode.sh} independently with their own SAD, diarization, and ASR models or pre-trained models. Stages 1--7 are the same as those of Track 1, as described in Section~\ref{sec:track1_software_overview}. But these are followed by new subsequent stages: \begin{enumerate} \item SAD training\\ We use a TDNN+LSTM (long short-term memory) model trained on the CHiME-6 dataset with ground truth alignments obtained by a GMM-HMM. Participants can also download a pretrained SAD model\footnote{\url{http://kaldi-asr.org/models/12/0012_sad_v1.tar.gz}}. \item Diarization training\\ An x-vector neural diarization model \cite{sell2018diarization} is trained with the VoxCeleb data \cite{nagrani2020voxceleb}. This script is adapted from the Kaldi VoxCeleb v2 recipe. A probabilistic linear discriminant analysis (PLDA) model \cite{kenny2010bayesian} is trained on the CHiME-6 dataset. Participants can also download a pretrained diarization model\footnote{\url{http://kaldi-asr.org/models/12/0012_diarization_v1.tar.gz}}. \item Decoding and scoring (stage 16)\\ In Track 2, only raw recordings are given without segment or speaker information; i.e., \texttt{local/decode.sh} has to perform the whole pipeline consisting of speech enhancement, SAD, speaker diarization, and ASR decoding and scoring. These steps are detailed below. \end{enumerate} \subsection{Array synchronization} Track 2 uses the exact same array synchronization technique as described in Section~\ref{sec:array-synchronization}. \subsection{Speech enhancement}\label{speech-enhancement-track2} Unlike Track 1, Track 2 only provides the BeamformIt-based speech enhancement front-end (see Section~\ref{sec:speech-enhancement}) due to the risk of degradation in GSS performance using estimated diarization information instead of ground truth speech segment information (which is unavailable). \subsection{Speech activity detection}\label{sec:speech-activity-detection} The SAD baseline relies on the neural architecture in \cite{ghahremani2016acoustic}. It was trained using data (\texttt{train\_worn\_u400k}) from 1) the CHiME-6 worn microphone utterances and 2) a randomly selected subset of 400~k array microphone utterances. We generate speech activity labels using an HMM-GMM system trained with the \texttt{train\_worn\_simu\_u400k} data from 1) the CHiME-6 worn microphone utterances perturbed with various room impulse responses generated from a room simulator and 2) a randomly selected subset of 400~k array microphone utterances. As a neural network architecture, we use 40-dimensional MFCC features as input, 5 TDNN layers, and 2 layers of statistics pooling \cite{ghahremani2016acoustic}. The overall context of the network is set to be around 1~s, with around 0.8~s of left context and 0.2~s of right context. The network is trained with a cross-entropy objective to predict speech/non-speech labels. During inference, SAD labels for the test recordings are obtained by Viterbi decoding using an HMM with minimum duration constraints of 0.3~s for speech and 0.1~s for silence. We also prepared an SAD decoding script to evaluate the SAD performance on the CHiME-6 data. Note that the baseline system only performs SAD (and all other post-processing steps including speaker diarization and ASR) for the U06 array for simplicity. Exploring multi-array fusion techniques for SAD, diarization, and ASR is an integral part of the challenge. \subsection{Speaker diarization}\label{sec:speaker-diarization} The speaker diarization baseline relies on the segment files obtained by SAD. It is an x-vector system \cite{snyder2018x} with a 5-layer TDNN trained on the VoxCeleb dataset \cite{nagrani2020voxceleb}. PLDA is trained on CHiME-6 data (\texttt{train\_worn\_simu\_u400k}). Agglomerative hierarchical clustering (AHC) \cite{anguera2012speaker} is performed. Since the number of speakers in CHiME-6 is four in every session, this prior information is used by AHC. Our speaker diarization system consistently uses the reference RTTM converted from the original JSON file via data preparation (\texttt{run.sh\ -\/-stage\ 1}) by using the Kaldi RTTM conversion script\footnote{\url{https://github.com/kaldi-asr/kaldi/blob/master/egs/wsj/s5/steps/segmentation/convert_utt2spk_and_segments_to_rttm.py}}. The diarization result is also obtained as an RTTM file, and the diarization error rate (DER) and Jaccard error rate (JER) are computed using dscore\footnote{\url{https://github.com/nryant/dscore}} (used in the DIHARD II challenge). Similar to the SAD system, this baseline system only performs diarization for the U06 array for simplicity. \subsection{Decoding and scoring} The RTTM files obtained by speaker diarization in Section~\ref{sec:speaker-diarization} are converted to the Kaldi data format. We perform two-stage decoding, which refines the i-vector extraction based on the first pass decoding result to achieve robust decoding for noisy speech \cite{acoustic-manohar2019}. Again, the baseline system only performs ASR for the U06 array for simplicity. We provide a scoring script for both development and evaluation. The language model weight and insertion penalty are optimized based on the development set. Multispeaker scoring is performed to obtain the concatenated minimum-permutation word error rate (cpWER). The cpWER is computed as follows: \begin{enumerate} \item Concatenate all utterances of each speaker for both reference and hypothesis files. \item Compute the WER between the reference and all possible speaker permutations of the hypothesis. There are 24 such permutations. \item Pick the lowest WER among them (this is assumed to be the best permutation). \end{enumerate} cpWER is directly affected by the speaker diarization results. In addition to the cpWER, which shows the error rate of entire recordings, we also report detailed errors per utterance by recovering the utterance information from the reference. \subsection{RTTM refinement} \label{sec:rttm_refine} In the original CHiME-5 annotations, utterance boundaries are marked by human annotators, among other information, in an RTTM file. While these utterance boundaries are sufficient for training and testing ASR, there are utterances that include long pauses between words, making them an imperfect reference for diarization. To obtain a more precise diarization reference, we apply forced alignment between the transcripts and the cleaner binaural recordings. The acoustic model we use for forced alignment is the triphone GMM-HMM model trained in the baseline system (see Section~\ref{sec:track1_software_overview}). We use \texttt{steps/align\_si.sh} to align the worn (binaural) microphone recordings for both the development set and the evaluation set. The decoding beam size is 20 by default, but if this search fails we perform a second alignment with a beam size of 150. These alignment results are at the word level. In order to merge them into utterances, we identify all contiguous words separated by gaps of at most 300~ms of silence. Instances of {[}noise{]} also separate utterances. These alignments are then saved in the RTTM format as the refined reference for SAD and diarization. \section{Baseline results} \label{sec:results} \subsection{Track 1} Table \ref{tab:track1baselineAsr} presents the Track 1 baseline ASR results with the official 3-gram language model (corresponding to category A). The CHiME-6 baseline is significantly better than the baseline and close to the best system \cite{du2018ustc} for the CHiME-5 multiple device track, which is equivalent to CHiME-6 Track 1. Note that the CHiME-6 baseline is designed to be a compromise between performance and simplicity, e.g., we purposefully did not use system combination but the result is still close to \cite{du2018ustc}, which is based on complex multi-path enhancement processing with system combination. \begin{table}[tbp] \centering \begin{tabular}{lcc} \toprule & Dev. WER & Eval. WER \\ \midrule CHiME-6 baseline & 51.8\% & 51.3\% \\ \midrule CHiME-5 baseline \cite{Fifth-Barker2018} & 81.1\% & 73.3\% \\ CHiME-5 top system \cite{du2018ustc} & 45.6\% & 46.6\% \\ \bottomrule \end{tabular} \caption{CHiME-6 Track 1 baseline ASR results, compared to the baseline and top systems for the (equivalent) CHiME-5 multiple device track.} \label{tab:track1baselineAsr} \end{table} \begin{table*}[tbp] \centering \begin{tabular}{l|ccc|ccc} \toprule & \multicolumn{3}{c}{Dev.} & \multicolumn{3}{c}{Eval.} \\ & Missed speech & False alarm & Total error & Missed speech & False alarm & Total error \\ \midrule Annotation RTTM & 2.5\% & 0.8\% & 3.3\% & 4.1\% & 1.8\% & 5.9\% \\ Alignment RTTM & 1.9\% & 0.7\% & 2.6\% & 4.3\% & 1.5\% & 5.8\% \\ \bottomrule \end{tabular} \caption{CHiME-6 Track 2 baseline SAD results. Annotation RTTM is the original RTTM obtained by human annotation while alignment RTTM is based on forced alignment and is considered as the official RTTM file for the challenge.} \label{table:sad} \end{table*} \subsection{Track 2} Table \ref{table:sad} shows the SAD performance obtained by the CHiME-6 baseline SAD system, as described in Section~\ref{sec:speech-activity-detection}. It lists the SAD results computed against both human-annotated (old) and force-aligned (new) RTTMs, as described in Section~\ref{sec:rttm_refine}. This result shows that the evaluation set is more difficult than the development set in terms of SAD performance. Also, the new and old RTTMs have significant differences in the development set while they have marginal difference in the evaluation set. \begin{table}[tbh] \begin{tabular}{l|cc|cc} \toprule & \multicolumn{2}{c}{Dev.} & \multicolumn{2}{c}{Eval.} \\ & DER & JER & DER & JER \\ \midrule Annotation RTTM & 61.6\% & 69.8\% & 62.0\% & 71.4\% \\ Alignment RTTM & 63.4\% & 70.8\% & 68.2\% & 72.5\% \\ \bottomrule \end{tabular} \caption{CHiME-6 Track 2 baseline diarization results. Annotation RTTM is the original RTTM obtained by human annotation while alignment RTTM is based on forced alignment and is considered as the official RTTM file for the challenge.} \label{tab:track2baselineDiarization} \end{table} Table \ref{tab:track2baselineDiarization} shows the DER and JER obtained by the CHiME-6 baseline speaker diarization system, as described in Section \ref{sec:speaker-diarization}. In spite of using a state-of-the-art diarization technique \cite{sell2018diarization}, both metrics show over 60\% error rates and improving the diarization performance is one of the main challenges in Track 2. \begin{table} \centering \begin{tabular}{l|c|c|cc} \toprule & & & Dev. & Eval. \\ & Enhancement & Segmentation & WER & WER \\ \midrule Track 1 & BeamformIt & Oracle & 69.8\% & 61.2\% \\ Track 1 & GSS & Oracle & 51.8\% & 51.3\% \\ Track 2 & BeamformIt & Diarization & 84.3\% & 77.9\% \\ \bottomrule \end{tabular} \caption{CHiME-6 Track 1 and 2 baseline ASR results with BeamformIt-based \cite{Acoustic-Anguera2007} and GSS-based \cite{boeddeker2018front} speech enhancement. We used the same acoustic and language models for both tracks.} \label{tab:track2baselineAsr} \end{table} Finally, Table \ref{tab:track2baselineAsr} shows the performance gap between the Track 1 and Track 2 baselines. The main differences between the Track 1 and 2 baselines come from the use of advanced speech enhancement (GSS \cite{boeddeker2018front}, as described in Section~\ref{sec:speech-enhancement}) and the use of speech segmentation from manual annotations or automatic speaker diarization. Note that both tracks use the same acoustic and language models. Therefore, by comparing Tracks 1 and 2 with BeamformIt, we can observe that the main degradation (around 15\% absolute) comes from speaker diarization. \section{Summary} \label{sec:summary} This paper describes the CHiME-6 challenge outline, baselines, and experimental results. Newly introduced audio synchronization and a state-of-the-art Kaldi baseline simplify challenge entry for Track 1, while Track 2 significantly increases the difficulty due to the need for speaker diarization. To help the challenge participants tackle these difficulties, we provide a complete set of open source Kaldi recipes for both Track 1 and Track 2 which combine speech enhancement, speaker diarization, and speech recognition. This is the first trial in the community to provide open source recipes for unsegmented multispeaker ASR, and a lot of effort has been provided through volunteer activities by speech separation and recognition researchers in addition to the challenge organizers. Our future work is to provide the analysis of this challenge including the investigation of the effectiveness of the techniques proposed during the challenge, a review of evaluation metrics, the relationship between diarization and speech recognition errors, and so on. Through this analysis, we would like to make significant progress toward this challenging, realistic, and unsolved multispeaker speech processing problem. \bibliographystyle{IEEEtran} \balance
{'timestamp': '2020-05-05T02:09:10', 'yymm': '2004', 'arxiv_id': '2004.09249', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09249'}
arxiv
\section{Introduction} \begin{figure} \begin{center} \includegraphics[width=1\linewidth]{figures/illustration-class.pdf} \end{center} \caption{Illustrations of multi-label classification for unsupervised person ReID. We target to assign each unlabeled person image with a multi-class label reflecting the person identity. This is achieved by iteratively running MPLP for prediction and MMCL for multi-label classification loss computation. This procedure guides CNN to produce discriminative features for ReID.} \label{fig:idea} \end{figure} Recent years have witnessed the great success of person re-identification (ReID), which learns discriminative features from labeled person images with deep Convolutional Neural Network (CNN)~\cite{zheng2016person, krizhevsky2012imagenet, he2016deep,su2015multi,li2019pose,su2017pose,su2016deep,su2017attributes}. Because it is expensive to annotate person images across multiple cameras, recent research efforts start to focus on unsupervised person ReID. Unsupervised person ReID aims to learn discriminative features from unlabeled person images. Compared with supervised learning, unsupervised learning relieves the requirement for expensive data annotation, hence shows better potential to push person ReID towards real applications. The challenge of unsupervised person ReID lies in learning discriminative features without true labels. To conquer this challenge, most of recent works~\cite{yu2017cross, zhong2019invariance, Lv_2018_CVPR, lin2018multi,wang2018transferable} define unsupervised person ReID as a transfer learning task, which leverages labeled data on other domains for model initialization or label transfer. Among them, some works assign each image with a single-class label~\cite{zhong2019invariance}. Some others leverage spatio-temporal cues or additional attribute annotations~\cite{Lv_2018_CVPR,lin2018multi,wang2018transferable}. Detailed review of existing methods will be presented in Sec.~\ref{sec:relatedwork}. Thanks to the above efforts, the performance of unsupervised person ReID has been significantly boosted. However, there is still a considerable gap between supervised and unsupervised person ReID. Meanwhile, the setting of transfer learning leads to limited flexibility. For example, as discussed in many works~\cite{long2015learning,Yan_2017_CVPR,wei2018person}, the performance of transfer learning is closely related to the domain gap, \emph{e.g.}, large domain gap degrades the performance. It is non-trivial to estimate the domain gap and select suitable source datasets for transfer learning in unsupervised person ReID. This paper targets to boost unsupervised person ReID without leveraging any labeled data. As illustrated in Fig.~\ref{fig:idea}, we treat each unlabeled person image as a class and train the ReID model to assign each image with a multi-class label. In other words, the ReID model is trained to classify each image to multiple classes belonging to the same identity. Because each person usually has multiple images, multi-label classification effectively identifies images of the same identity and differentiates images from different identities. This in-turn facilitates the ReID model to optimize inter and intra class distances. Compared with previous methods~\cite{lin2019bottom,wu2018unsupervised}, which classify each image into a single class, the multi-label classification has potential to exhibit better efficiency and accuracy. Our method iteratively predicts multi-class labels and updates the network with multi-label classification loss. As shown in Fig.~\ref{fig:idea}, to ensure the quality of predicted labels, we propose the Memory-based Positive Label Prediction (MPLP), which considers both visual similarity and cycle consistency for label prediction. Namely, two images are assigned with the same label if they a) share large similarity and b) share similar neighbors. To further ensure the accuracy of label prediction, MPLP utilizes image features stored in the memory bank, which is updated with augmented features after each training iteration to improve feature robustness. Predicted labels allow for CNN training with a multi-label classification loss. Since each image is treated as a class, the huge number of classes makes it hard to train classifiers like Fully Connected (FC) layers. As shown in Fig.~\ref{fig:idea}, we adopt the feature of each image stored in the memory bank as a classifier. Specifically, a Memory-based Multi-label Classification Loss (MMCL) is introduced. MMCL accelerates the loss computation and addresses the vanishing gradient issue in traditional multi-label classification loss~\cite{zhang2013review,Durand_2019_CVPR} by abandoning the sigmoid function and enforcing the classification score to 1 or -1. MMCL also involves hard negative class mining to deal with the imbalance between positive and negative classes. We test our approach on several large-scale person ReID datasets including Market-1501~\cite{zheng2015scalable}, DukeMTMC-reID~\cite{ristani2016performance} and MSMT17~\cite{wei2018person} without leveraging other labeled data. Comparison with recent works shows our method achieves competitive performance. For instance, we achieve rank-1 accuracy of 80.3\% on Market-1501, significantly outperforming the recent BUC~\cite{lin2019bottom} and DBC~\cite{ding12dispersion} by 14.1\% and 11.1\%, respectively. Our performance is also better than the HHL~\cite{zhong2018generalizing} and ECN~\cite{zhong2019invariance}, which use extra DukeMTMC-reID~\cite{ristani2016performance} for transfer learning. Our method is also compatible with transfer learning. Leveraging DukeMTMC-reID for training, we further achieve rank-1 accuracy of 84.4\% on Market-1501. In summary, our method iteratively runs MPLP and MMCL to seek true labels for multi-label classification and CNN training. As shown in our experiments, this strategy, although does not leverage any labeled data, achieves promising performance. The maintained memory bank reinforces both label prediction and classification. Our work also shows that, unsupervised training has potential to achieve better flexibility and accuracy than existing transfer learning strategies. \section{Related Work} \label{sec:relatedwork} This section briefly reviews related works on unsupervised person ReID, unsupervised feature learning, and multi-label classification. \emph{Unsupervised person ReID} works can be summarized into three categories. The first category utilizes hand-craft features~\cite{liao2015person,zheng2015scalable}. However, it is difficult to design robust and discriminative features by hand. The second category~\cite{fan2018unsupervised,Fu_2019_ICCV} adopts clustering to estimate pseudo labels to train the CNN. However, these methods require good pre-trained model. Apart from this, Lin \emph{et al.}~\cite{lin2019bottom} treat each image as a cluster, through training and merging clusters, this method achieves good performance. The third category~\cite{lin2018multi,wang2018transferable,yu2019unsupervised,wei2018person,deng2018image,zhong2018generalizing,zhong2019invariance, Chen_2019_ICCV,Wu_2019_ICCV,Li_2019_ICCV,Qi_2019_ICCV,Zhang_2019_ICCV} utilizes transfer learning to improve unsupervised person ReID. Some works~\cite{lin2018multi,wang2018transferable} use transfer learning and minimize the attribute-level discrepancy by utilizing extra attribute annotations. MAR~\cite{yu2019unsupervised} uses the source dataset as a reference to learn soft labels, which hence supervise the ReID model training. Generative Adversarial Network (GAN) is also utilized for transfer learning. PTGAN~\cite{wei2018person} and SPGAN~\cite{deng2018image} first generate transferred images from source datasets, then uses transferred image for training. HHL~\cite{zhong2018generalizing} generates images under different cameras and trains network using triplet loss. ECN~\cite{zhong2019invariance} utilizes transfer learning and minimizes the target invariance. Transfer learning requires a labeled source dataset for training. Our method differs with them that, it does not require any labeled data. It also achieves better performance than many transfer learning methods. \emph{Unsupervised feature learning} aims to relieve the requirement on labeled data for feature learning. It can be applied in different tasks. Some works adopt unsupervised feature learning for neural network initialization. For example, RotNet~\cite{komodakis2018unsupervised} predicts the rotation of image to learn a good representation. Li \emph{et al.}~\cite{li2018unsupervised} use motion and view as supervision to learn an initialization for action recognition. Some other works utilize unsupervised feature learning to acquire features for image classification and retrieval. \cite{iscen2018mining} utilizes manifold learning to seek positive and negative samples to compute the triplet loss. Wu \emph{et al.}~\cite{wu2018unsupervised} regard each image as single class, and propose a non-parametric softmax classifier to train CNN. Our work shares certain similarity with \cite{wu2018unsupervised}, in that we also use non-parametric classifiers. However, we consider multi-label classification, which is important in identifying images of the same identity as well as differentiating different identities. \emph{Multi-label classification} is designed for classification tasks with multi-class labels~\cite{zhang2013review,Durand_2019_CVPR,wang2018transferable,lin2018multi}. Durand \emph{et al.}~\cite{Durand_2019_CVPR} deal with multi-label learning based on partial labels and utilize GNN to predict missing labels. Wang \emph{et al.}~\cite{wang2018transferable,lin2018multi} use multi-label classification to learn attribute feature. This paper utilizes multi-label classification to predict multi-class labels and focuses on learning identity feature for person ReID. To the best of our knowledge, this is an early work utilizing multi-label classification for unsupervised person ReID. \section{Methodology} \subsection{Formulation} ~\label{sec:formulate} Given an unlabeled person image dataset $\mathcal X=\{x_1,x_2,...,x_n\}$, our goal is to train a person ReID model on $\mathcal X$. For any query person image $q$, the person ReID model is expected to produce a feature vector to retrieve image $g$ containing the same person from a gallery set $G$. In other words, the ReID model should guarantee $q$ share more similar feature with $g$ than with other images in $G$. We could conceptually denote the goal of person ReID as, \begin{equation} g^* = \arg\min_{g\in G} \operatorname {dist}(f_g,f_q), \end{equation} where $f \in \mathbb{R}^d$ is a $d$-dimensional L2-normalized feature vector extracted by the person ReID model. $\operatorname {dist}(\cdot)$ is the distance metric, \emph{e.g.}, the L2 distance. To make training on $\mathcal X$ possible, we start by treating each image as an individual class and assign $x_i$ with a label $y_i$. This pseudo label turns $\mathcal X$ into a labeled dataset, and allows for the ReID model training. $y_i$ is initialized to a two-valued vector, where only the value at index $i$ is set to $1$ and the others are set to $-1$, \emph{i.e.}, \begin{equation} y_i[j]=\left\{ \begin{array}{rcl} 1 & & {j = i}\\ -1 & & {j \neq i} \end{array} \right. \end{equation} Since each person may have multiple images in $\mathcal X$, the initial label vector is not valid in representing person identity cues. Label prediction is required to assign multi-class labels to each image, which can be used for ReID model training with a multi-label classification loss. Labels of $x_i$ can be predicted by referring its feature $f_i$ to features of other images, and find consistent feature groups. On the other hand, due to the huge number of image classes in $\mathcal X$, it is hard to train a multi-label classifier. One efficient solution is to use the $f_i$ as the classifier for the $i$-th class. This computes the classification score for any image $x_j$ as, \begin{equation} c_j[i]= f_i^\top \times f_j, \end{equation} where $c_j$ denotes the multi-label classification score for $x_j$. It is easy to infer that, both label prediction and multi-label classification require features of images in $\mathcal X$. We hence introduce a $n \times d$ sized memory bank $\mathcal{M}$ to store those features, where $\mathcal{M}[i] =f_i$. With $\mathcal{M}$, we propose the Memory-based Positive Label Prediction (MPLP) for label prediction and Memory-based Multi-label Classification Loss (MMCL) for ReID model training, respectively. As shown in Fig.~\ref{fig:idea}, MPLP takes a single-class label as input and outputs the multi-label prediction $\bar y_i$ based on memory bank $\mathcal{M}$, \emph{i.e.}, \begin{equation}~\label{eq:mplp} \bar y_i = \operatorname {MPLP}(y_i, \mathcal{M}), \end{equation} where $\operatorname {MPLP}(\cdot)$ denotes the MPLP module and $\bar y$ is the multi-class label. MMCL computes the multi-label classification loss by taking the image feature $f$, label $\bar y$, and the memory bank $\mathcal{M}$ as inputs. The computed loss $\mathcal{L}_{MMCL}$ can be represented as, \begin{equation}\label{eq:mmcl} \mathcal{L}_{MMCL} = \sum_{i=1}^{n} \mathcal D(\mathcal{M}^\top \times f_i, \bar y_i), \end{equation} where $\mathcal{M}^\top \times f_i$ computes the classification score, and $\mathcal D(\cdot)$ computes the loss by comparing classification scores and predicted labels. $\mathcal{M}$ is updated after each training iteration as, \begin{equation} \mathcal{M}[i]^t = \alpha \cdot f_i + (1-\alpha) \cdot \mathcal{M}[i]^{t-1}, \end{equation} where the superscript $t$ denotes the $t$-th training epoch, $\alpha$ is the updating rate. $\mathcal{M}[i]^t$ is then L2-normalized by $\mathcal{M}[i]^t \leftarrow||\mathcal{M}[i]^t||_2$. It is easy to infer that, both MPLP and MMCL require robust features in $\mathcal{M}$ to seek reliable labels and classification scores, respectively. We use many data argumentation techniques to reinforce $\mathcal{M}$. In other words, each $\mathcal{M}[i]$ combines features of different augmented samples form $x_i$, hence it presents better robustness. More details are given in Sec.~\ref{sec:implement}. MPLP considers both similarity and cycle consistency to predict $\bar y_i$, making it more accurate than the classification score. This makes the loss computed with Eq.~\eqref{eq:mmcl} valid in boosting the ReID model, which in-turn produces positive feedbacks to $\mathcal{M}[i]$ and label prediction. This loop makes it possible to train discriminative ReID models on unlabeled dataset. Implementations to MPLP and MMCL can be found in the following parts. \subsection{Memory-based Positive Label Prediction}\label{section:mplp} As shown in Eq.~\eqref{eq:mplp}, given an initial two-valued label $y_i$ of image $x_i$, MPLP aims to find other classes that $x_i$ may belong to. For $x_i$, MPLP first computes a rank list ${R}_{i}$ according to the similarity between $x_i$ and other features, \emph{i.e.}, \begin{equation}\label{eq:labelrank} {R}_{i} = \mathop{\arg \operatorname {sort}}_j (s_{i,j}), j \in [1,n], \end{equation} \begin{equation}\label{eq:mem_sim} s_{i,j} = \mathcal{M}[i]^\top \times \mathcal{M}[j], \end{equation} where $s_{i,j}$ denotes the similarity score of $x_i$ and $x_j$. ${R}_{i}$ finds candidates for reliable labels for $x_i$, \emph{e.g.}, labels at the top of rank list. However, variances of illumination, viewpoint, backgrounds, \emph{etc}., would degrade the robustness of the rank list. \emph{E.g.}, noisy labels may appear at the top of rank list. To ensure the quality of predicted labels, MPLP refers to the similarity score and cycle consistency for label prediction. \textbf{Label filtering by similarity score:} We first select positive label candidates for $x_i$ based on its rank list. Inspired by~\cite{zhang2013review}, that uses a threshold to select relevant labels for query, we select candidate labels with a predefined similarity threshold. Given a similarity score threshold $t$, $k_i$ label candidates can be generated by removing labels with similarity smaller than $t$, \emph{i.e.}, \begin{equation} \begin{aligned}\label{eq:t_select} {P}_{i} = {R}_{i}[1:k_i], \end{aligned} \end{equation} where ${R}_{i}[k_i]$ is the last label with similarity score higher than $t$, ${P}_{i}$ is the collection of label candidates for $x_i$. $t$ largely decides the quantity of label candidates. It will be tested in Sec.~\ref{section:pa}. Eq.~\eqref{eq:t_select} adaptively finds different numbers of candidates labels for different images, which is better than selecting fixed number of labels, \emph{i.e.}, the KNN in Fig.~\ref{fig:visualization}. We proceed to introduce cycle consistency to find positive labels from ${P}_{i}$. \begin{figure} \begin{center} \includegraphics[scale=0.19]{figures/visualization2.pdf} \end{center} \caption{Illustration of the label prediction by MPLP. (a) reports the precision and recall of MPLP in finding true positive labels, where MPLP consistently outperforms KNN at different training stages. (b) shows positive labels and negative labels selected by MPLP, where MPLP effectively rejects hard negative labels.} \vspace{-1mm} \label{fig:visualization} \end{figure} \textbf{Label filtering by cycle consistency:} Inspired by k-reciprocal nearest neighbor\cite{jegou2007contextual,zhong2017re}, we assume that, if two images belong to the same class, their neighbor image sets should also be similar. In other words, two images should be mutual neighbor for each other if they can be assigned with similar labels. With this intuition, we propose a cycle consistency scheme to filter hard negative labels in $P_i$. MPLP traverses labels in $P_i$ from head to tail. For a label $j$ in ${P}_{i}$, MPLP computes its top-$k_i$ nearest labels with Eq.~\eqref{eq:labelrank}. If label $i$ is also one of the top-$k_i$ nearest labels of $j$, $j$ is considered as a positive label for $x_i$. Otherwise, it is treated as a hard negative label. The traverse is stopped when the first hard negative label is found. This leads to a positive label set $P^*_i$ as well as a hard negative label for image $x_i$. We denote the positive label set as, \begin{equation} {P}^*_{i} = {P}_{i}[1:l], \end{equation} where $l$ satisfies $i \in {R}_{{P_i[l]}}[1:k_i] ~\&~ i \notin {R}_{{P_i[l+1]}}[1:k_i]$. As ${P}^*_{i}$ contains $l$ labels, $x_i$ would be assigned with a multi-class label $\bar y_i$ with $l$ positive classes, \begin{equation} \bar y_i[j]=\left\{ \begin{array}{rcl} 1 & & {j\in {P}^*_{i}}\\ -1 & & {j \notin {P}^*_{i}} \end{array} \right. \end{equation} As Fig.~\ref{fig:visualization} shows that, MPLP predicts accurate positive labels. Experimental evaluations will be presented in Sec.~\ref{section:ablation}. \subsection{Memory-based Multi-label Classification Loss}\label{section:mmcl} \textbf{Traditional multi-label classification loss:} The predicted multi-class labels are used for training the ReID model with a multi-label classification loss. In traditional multi-label classification methods, sigmoid and logistic regression loss is a common option~\cite{zhang2013review,Durand_2019_CVPR,wang2018transferable,lin2018multi}. For a task with $n$ classes, it adopts $n$ independent binary classifiers for classification. The loss of classifying image $x_i$ to class $j$ can be computed as, \begin{equation}~\label{eq:mcl} \ell(j|x_i) = \log (1 + \exp (-\bar y_i[j]\times \mathcal{M}[j]^\top \times f_i)), \end{equation} where $\mathcal{M}[j]^\top \times f_i$ computes the classification score of image $x_i$ for the class $j$. $\bar y_i[j]$ is the label of image $x_i$ for class $j$. With the loss at a single class, we can obtain the Multi-Label Classification (MCL) loss, \emph{i.e.}, $\mathcal{L}_{MCL}$, \begin{equation} \mathcal{L}_{MCL} = \sum_{i=1}^{n}\sum_{j=1}^{n}\ell(j|x_i), \end{equation} where $n$ is the number of images in the dataset $\mathcal X$, which equals to the class number in our setting. \begin{figure} \begin{center} \includegraphics[scale=0.25]{figures/gradientanalysis.pdf} \end{center} \caption{Gradient Analysis for MCL-$\tau$ and MMCL. It is clear that, MMCL does not suffer from the vanishing gradient issue.} \vspace{-2mm} \label{fig:gradientanalysis} \end{figure} Because the $\mathcal{M}[j]^\top$ and $f_i$ are L2 normalized, the classification score is restricted between $[-1,1]$. This limits the range of sigmoid function in Eq.~\eqref{eq:mcl}, making the loss non-zero even for correct classifications. This issue can be addressed by introducing a scalar $\tau$ on the classification score. This updates Eq.~\eqref{eq:mcl} as, \begin{equation}~\label{eq:mcl-t} \ell_\tau(j|x_i) = \log (1 + \exp (-\bar y_i[j]\times \mathcal{M}[j]^\top \times f_i/\tau)). \end{equation} We denote the corresponding MCL loss as $\mathcal{L}_{MCL-\tau}$. The gradient of $\mathcal{L}_{MCL-\tau}$ can be computed as, \begin{equation}~\label{eq:grad_mcl} \begin{aligned} \frac{\partial{\mathcal{L}_{MCL-\tau}}}{\partial{f_i}} = -\frac{\exp(-\bar y_i[j] \mathcal{M}[j]^\top f_i /\tau)}{1+\exp(-\bar y_i[j]\mathcal{M}[j]^\top f_i/\tau)}\frac{\bar y_i[j]\mathcal{M}[j]}{\tau}. \end{aligned} \end{equation} With Eq.~\eqref{eq:grad_mcl}, we illustrate the gradient of $\mathcal{L}_{MCL-\tau}$ with different values of $\tau$ when $\bar y_i[j]=1$ in Fig.~\ref{fig:gradientanalysis}. It is clear that, the updated MCL loss still suffers from substantial vanishing gradient issue as the classification score larger than 0.25 or smaller than -0.25. Another issue with MCL loss is that, our task involves a large number of classes, making the positive and negative classes unbalanced. Treating those negative classes equally in Eq.~\eqref{eq:mcl-t} may cause a model collapse. We hence proceed to propose MMCL to address those issues. \textbf{Memory-based Multi-label Classification Loss:} MMCL is proposed to address two issues in traditional MCL. For the first issue, since the score is bounded by $[-1,1]$, we can abandon the sigmoid function and directly compute the loss by regressing the classification score to 1 and -1. This simplifies the loss computation and improves the training efficiency. The loss of classifying image $x_i$ to class $j$ can be updated as, \begin{equation} \ell^*(j|x_i) = ||\mathcal{M}[j]^\top \times f_i -\bar y_i[j]||^2, \end{equation} where $f_i$ is the feature of image $x_i$. The second problem is the imbalance between positive and negative classes. MMCL introduces hard negative class mining to solve it. This is inspired by the sample mining in deep metric learning~\cite{wu2017sampling}, where hard negative samples are more informative for training. Similarly in our multi-label classification, the training should focus more on hard negative classes than easy negative classes. For $x_i$, its negative classes can be denoted as $R_{i} \backslash P^*_{i}$. We rank them by their classification scores and select the top $r\%$ classes as the hard negative classes. The collection of hard negative classes for $x_i$ can be denoted as ${N}_{i}, |{N}_{i}|=(n-|P^*_{i}|)\cdot r\%$. The MMCL is computed on positive classes and sampled hard negative classes as follows, \begin{equation}\label{mmcl} \begin{aligned} \mathcal{L}_{MMCL} = \sum_{i=1}^{n} \frac{\delta}{|{P}^*_{i}|}\sum_{p \in \mathcal{P}^*_{i}}\ell^*(p|x_i) + \\ \frac{1}{|{N}_{i}|}\sum_{s \in {N}_{i}}\ell^*(s|x_i) \end{aligned} \end{equation} where $\delta$ is a coefficient measuring the importance of positive class loss and negative class loss, which will be tested in experiments. We also illustrate the gradients of $\mathcal{L}_{MMCL}$ similarly when $\bar y_i[j]=1$, in Fig.~\ref{fig:gradientanalysis}, where the gradient of $\mathcal{L}_{MMCL}$ can be computed as, \begin{equation} \begin{aligned} \partial{\mathcal{L}_{MMCL}}/{\partial{f_i}}= 2\delta (\mathcal{M}[j]^\top \times f_i -\bar y_i[j])\mathcal{M}[j]. \end{aligned} \end{equation} \textbf{Discussions:} Comparison between MCL and MMCL in Fig.~\ref{fig:gradientanalysis} clearly shows that, the vanishing gradient issue is effectively addressed by MMCL. Because of vanishing gradient, $\mathcal{L}_{MCL-\tau}$ won't enforce the classifier to classify positive labels with large scores. This is harmful for decreasing the intra-class variance. Therefore, MMCL is more effective than MCL in optimizing the ReID model. Fig.~\ref{fig:gradientanalysis} also shows that, $\delta$ controls the magnitude of the gradient of MMCL. As discussed in \cite{NIPS2018_8094}, mean square loss is inferior to log-based loss (\emph{e.g.} cross entropy) when classification score is near the decision boundary. $\delta$ effectively solves this issue by scaling the gradient magnitude of MMCL. By adopting the hard negative class mining strategy, MMCL not only works for multi-label classification, it also could be applied in single-label classification, where the unbalanced class issue still exists. Compared with cross entropy loss and MCL, MMCL abandons activation functions like softmax and sigmoid, leading to more efficient computation. As discussed in many works~\cite{morin2005hierarchical, gutmann2010noise}, a huge number of classes degrades the speed of softmax computation. Existing solutions include hierarchical softmax~\cite{morin2005hierarchical} and noise-contrastive estimation~\cite{gutmann2010noise}. As MMCL does not involve softmax computation, it does not suffer from such issues. \subsection{Transfer Learning with Labeled Dataset}\label{section:transfer} Our method is also compatible with transfer learning setting. Given a dataset containing labeled person images, we can adopt the commonly used cross entropy loss and triplet loss on labeled data to train the model. The training loss can be denoted as $\mathcal{L}_{labeled}$. The overall training loss for transfer learning can be represented as the sum of MMCL and loss on labeled dataset, \emph{i.e.}, \begin{equation} \mathcal {L}_{transfer} = \mathcal{L}_{labeled} + \mathcal{L}_{MMCL}. \end{equation} The performance of our methods on transfer learning will be tested in the next section. \section{Experiments} \vspace{-1mm} \subsection{Dataset and Evaluation Metrics} \vspace{-1mm} \emph{Market-1501}~\cite{zheng2015scalable} contains 32,668 labeled person images of 1,501 identities collected from 6 non-overlapping camera views. \emph{DukeMTMC-reID}~\cite{ristani2016performance} has 8 cameras and 36,411 labeled images of 1,404 identities. \emph{MSMT17}~\cite{wei2018person} is a newly released person ReID dataset. It is composed of 126,411 person images from 4,101 identities collected by 15 cameras. The dataset suffers from substantial variations of scene and lighting, and is more challenging than the other two datasets. All three datasets are collected under similar scenario, \emph{i.e.}, campus, which makes the transfer learning possible. We follow the standard settings~\cite{zheng2015scalable,ristani2016performance,wei2018person} on them to conduct experiments. Performance is evaluated by the Cumulative Matching Characteristic (CMC) and mean Average Precision (mAP). \begin{figure} \begin{center} \includegraphics[scale=0.24]{figures/pa-sst.pdf} \end{center} \vspace{-2mm} \caption{Evaluation of similarity score $t$ in MPLP.} \vspace{-2mm} \label{figure:pa-sst} \end{figure} \vspace{-1mm} \subsection{Implementation Details}\label{sec:implement} \vspace{-1mm} All experiments are implemented on PyTorch. We use ResNet-50~\cite{he2016deep} as backbone to extract the feature and initialize it with parameters pre-trained on ImageNet~\cite{5206848}. After pooling-5 layer, we remove subsequent layers and add a batch normalization layer~\cite{ioffe2015batch}, which produces a 2048-dim feature. During testing, we also extract the pooling-5 feature to calculate the distance. For multi-label classification, we allocate a memory bank to store L2 normalized image features. The memory bank is initialized to all zeros, and we start using MPLP for label prediction when the memory is fully updated 5 times (after 5 epochs). As mentioned in section \ref{section:mplp}, we leverage CamStyle~\cite{zhong2018camera} as a data augmentation strategy for unlabeled images. Strategies like random crop, random rotation, color jitter, and random erasing are also introduced to improve the feature robustness. The input image is resized to 256*128. We use SGD to optimize the model, the learning rate for ResNet-50 base layers are 0.01, and others are 0.1. The memory updating rate $\alpha$ starts from $0$ and grows linearly to $0.5$. We train the model for 60 epochs, and the learning rate is divided by 10 after every 40 epochs. The batch size for model training is 128. We fix the similarity threshold $t$ in MPLP as 0.6. In MMCL, the weight $\delta$ is fixed to 5 and we select the 1\% top-ranked negative classes to compute the loss through the parameter analysis in Sec.~\ref{section:pa}. For transfer learning with labeled dataset, we apply the same batch size on the labeled dataset. A fully connected layer is added after batch normalization layer for classification. We optimize the $\mathcal {L}_{transfer}$ in section \ref{section:transfer} following the same baseline training strategy as described in \cite{Fu_2019_ICCV}. \vspace{-1mm} \subsection{Parameter Analysis}\label{section:pa} \vspace{-1mm} This section aims to investigate some important hyper-parameters in our method, including the similarity score threshold $t$ in MPLP, coefficient $\delta$, and hard negative mining ratio $r$\% in MMCL. Each experiment varies the value of one hyper-parameter while keeping others fixed. All experiments are conducted with unsupervised ReID setting on both Market-1501 and DukeMTMC-reID. \begin{table} \footnotesize \begin{center} \begin{tabular}{p{1cm}<{\centering}|cc|cc} \hline \multirow{2}{*}{$\delta$} & \multicolumn{2}{c|}{Market-1501} & \multicolumn{2}{c}{DukeMTMC-reID}\\ \cline{2-5} & Rank-1 & mAP & Rank-1 & mAP \\ \hline\hline 1 & 59.3 & 19.4 & 52.6 & 22.8 \\ 2 & 71.3 & 31.1 & 58.8 & 31.0 \\ 3 & 76.6 & 40.0 & 62.6 & 35.6 \\ 4 & 79.9 & 44.9 & 64.9 & 39.1 \\ 5 & \textbf{80.3} & \textbf{45.5} & \textbf{65.2} & \textbf{40.2}\\ 6 & 78.1 & 45.0 & 65.0 & 39.8\\ 7 & 73.2 & 41.3 & 64.1 & 39.4\\ \hline \end{tabular} \end{center} \vspace{-2mm} \caption{Evaluation of parameter $\delta$ in Eq.~\eqref{mmcl}.} \vspace{-2mm} \label{table:pa-delta} \end{table} \textbf{Similarity threshold $t$:} Fig.\ref{figure:pa-sst} investigates the effect of similarity threshold $t$ in MPLP. We vary $t$ from $0.3$ to $0.7$ and test the model performance. A low similarity score $t$ will harm the model performance. For example, when $t$ is in range $[0.3,0.5]$, a substantial performance drop can be observed compared with larger $t$. This is because that, low similarity threshold introduces many negative labels. More accurate labels can be selected as $t$ becomes larger. However, too large $t$ decreases the number of selected labels. The best $t$ is 0.6 for both Market-1501 and DukeMTMC-reID. We hence set $t=0.6$. \textbf{Coefficient $\delta$:} Table~\ref{table:pa-delta} reports the analysis on coefficient $\delta$ of MMCL. As discussed in Sec.~\ref{section:mmcl}, $\delta$ plays a role to scale the gradient of MMCL. $\delta=1$ means that we do not scale the gradient. In this case, the MMCL cannot produce large gradients to pull positive samples together, leading to bad performance. For example, the rank-1 accuracy is dropped to 59.3\% on Market-1501 and 52.6\% on DukeMTMC-reID. As $\delta$ becomes larger, MMCL effectively improves the similarity of positive samples, leading to better performance. However, too large $\delta$ may make the training unstable. According to Table~\ref{table:pa-delta}, we set $\delta=5$. \textbf{Hard negative mining ratio $r$\%:} Fig.~\ref{figure:pa-hnmr} shows effects of hard negative mining ratio $r$\% in network training. $r=100$ means using all negative classes for loss computation. It is clear that, $r=100$ is harmful for the performance. This implies that, not all of the negative classes are helpful for unsupervised ReID training. As $r$ becomes smaller, hard negative mining would be activated and it boosts the performance. Too small $r$ selects too few negative classes, hence is also harmful for the performance. According to Fig.~\ref{figure:pa-hnmr}, $r=1$ is used in our experiments. \begin{figure} \begin{center} \includegraphics[scale=0.25]{figures/pa-hnmr.pdf} \end{center} \vspace{-2mm} \caption{Evaluation of hard negative mining ratio $r$ in MMCL.} \label{figure:pa-hnmr} \end{figure} \begin{table} \footnotesize \begin{center} \begin{tabular}{l||c|c||c|c} \hline \multirow{2}{*}{Method} & \multicolumn{2}{c||}{Market-1501} & \multicolumn{2}{c}{DukeMTMC-reID}\\ \cline{2-5} & Rank-1 & mAP & Rank-1 & mAP \\ \hline\hline Supervised & 87.1 & 68.3 & 75.9 & 57.9 \\ \hline ImageNet Pre-trained & 7.8 & 2.1 & 5.1 & 1.4 \\ MMCL + Single Label & 49.0 & 17.8 & 42.0 & 16.6\\ MMCL + MPLP$\dagger$ & {66.6} & {35.3} & {58.0} & {36.3} \\ MMCL + MPLP & \textbf{80.3} & \textbf{45.5} & \textbf{65.2} & \textbf{40.2} \\ \hline \end{tabular} \end{center} \vspace{-2mm} \caption{Test of validity of MMCL and MPLP. $\dagger$ denotes not using CamStyle~\cite{zhong2018camera} for data augmentation.} \vspace{-2mm} \label{table:ablation} \end{table} \vspace{-1mm} \subsection{Ablation Study}\label{section:ablation} \vspace{-1mm} This part evaluates the effectiveness of MPLP and MMCL by making comparison with supervised learning, MMCL+single-class label, and MMCL+MPLP. Experimental results are reported in Table \ref{table:ablation}, where the performance of ImageNet pre-trained model is also reported as the baseline. As shown in the table, the supervised learning achieves high accuracy, \emph{e.g.}, 87.1\% in rank-1 accuracy and 68.3\% in mAP on Market-1501. ImageNet pre-trained model performs badly on both Market-1501 and DukeMTMC-reID. MMCL with single-class pseudo labels boosts the baseline performance, indicating the validity of leveraging unlabeled dataset in training. Table \ref{table:ablation} also shows that, combining MMCL with MPLP significantly boosts the performance, \emph{e.g.}, from baseline 7.8\% to 80.3\% in rank-1 accuracy on Market-1501. Table \ref{table:ablation} also shows that, CamStyle~\cite{zhong2018camera} boosts the performance, indicating the importance of data augmentation as discussed in Sec.~\ref{sec:formulate}. \textbf{Effectiveness of MPLP:} To verify that MPLP is a reasonably good solution for label prediction, we compare MPLP against several other label prediction methods, \emph{e.g.}, the KNN search and selection by Similarity Score (SS). Table \ref{table:labelandloss} (a) summarizes the results. From Table \ref{table:labelandloss} (a), we can observe that KNN (K=8, which achieves the best peformance) achieves 73.3\% rank-1 accuracy and 35.4\% mAP on Market-1501. Selecting positive labels by Similarity Score (SS) gains improvements over KNN. This indicates that, adaptively select positive labels with similarity threshold is more reasonable than fixing the positive label number for different images. Table \ref{table:labelandloss} (a) also shows that, MPLP achieves the best performance. This indicates that combining cycle consistency and similarity score effectively ensure the quality of predicted labels. Visualization of predicted labels by MPLP can be found in Fig.~\ref{fig:visualization}. \begin{table} \footnotesize \begin{center} \begin{tabular}{l||c|c||c|c} \hline \multirow{2}{*}{Method} & \multicolumn{2}{c||}{Market-1501} & \multicolumn{2}{c}{DukeMTMC-reID}\\ \cline{2-5} & Rank-1 & mAP & Rank-1 & mAP \\ \hline\hline MMCL + KNN &73.3 & 35.4 & 59.5 & 33.5 \\ MMCL + SS & 77.6 & 43.0 & 62.7 & 38.5 \\ MMCL + MPLP & \textbf{80.3} & \textbf{45.5} & \textbf{65.2} & \textbf{40.2} \\ \hline \multicolumn{5}{c}{(a)}\\ \hline CE + Single Label & 31.4 & 9.9 & 31.5 & 11.8 \\ MMCL + Single Label & 49.0 & 17.8 & 42.0 & 16.6\\ CE + Ground Truth & 85.5 & 65.5 & 70.4 & 50.3 \\ MMCL + Ground Truth & 86.5 & 67.2 & 74.5 & 56.9\\ CE + MPLP & 65.0& 34.2 & 60.2 & 35.1\\ MMCL + MPLP & 80.3 & 45.5 & 65.2 & 40.2 \\ \hline \multicolumn{5}{c}{(b)}\\ \end{tabular} \end{center} \vspace{-2mm} \caption{Ablation study on different label prediction algorithms and loss functions.} \vspace{-2mm} \label{table:labelandloss} \end{table} \textbf{Effectiveness of MMCL:} To test the validity of MMCL, this part proceeds to compare it against Cross Entropy (CE) loss with different training settings. Experimental results are summarized in Table \ref{table:labelandloss} (b). We first test MPLP and CE using single-class labels for model learning. MMCL gets 49.0\% rank-1 accuracy and 17.8\% mAP on Market-1501, substantially better than CE. We further test MMCL and CE using ground truth labels for learning. Note that, we modify CE according to \cite{zhong2019invariance} to make it applicable in multi-class learning. With ground truth labels, MMCL still performs better than CE, especially on DukeMTMC-reID. We finally test MMCL and CE with labels predicted by MPLP. MMCL still outperforms CE by large margins. Note that, MMCL uses non-parameters classifiers for training. It still achieves comparable performance with the supervised learning in Table \ref{table:ablation}. Table \ref{table:labelandloss} (b) thus demonstrates the effectiveness of MMCL and the training paradigm of our method. \begin{table*} \footnotesize \begin{center} \setlength{\tabcolsep}{2.5mm}{ \begin{tabular}{l||c||c|c|c|c|c||c|c|c|c|c} \hline \multirow{2}{*}{Method} & \multirow{2}{*}{Reference} & \multicolumn{5}{c||}{Market-1501} & \multicolumn{5}{c}{DukeMTMC-reID} \\ \cline{3-12} & & Source & Rank-1 & Rank-5 & Rank-10 & mAP & Source & Rank-1 & Rank-5 & Rank-10 & mAP \\ \hline\hline LOMO\cite{liao2015person} & CVPR15& None & 27.2& 41.6& 49.1 &8.0& None & 12.3 &21.3& 26.6& 4.8 \\ BOW\cite{zheng2015scalable} & ICCV15&None & 35.8& 52.4& 60.3 &14.8 & None &17.1& 28.8& 34.9 &8.3 \\ BUC\cite{lin2019bottom} & AAAI19 & None & 66.2 & 79.6 & 84.5 & 38.3 & None& 47.4 & 62.6 & 68.4 & 27.5 \\ DBC\cite{ding12dispersion} & BMVC19 & None & 69.2 & 83.0 & 87.8 & 41.3 & None& 51.5 & 64.6 & 70.1 & 30.0 \\ \hline Ours & This paper & None& \textbf{80.3} & \textbf{89.4} & \textbf{92.3} & \textbf{45.5} & None & \textbf{65.2} & \textbf{75.9} & \textbf{80.0} & \textbf{40.2} \\ \hline \hline PUL\cite{fan2018unsupervised} & TOMM18 & Duke & 45.5 &60.7 &66.7& 20.5& Market & 30.0 &43.4 &48.5 &16.4 \\ PTGAN\cite{wei2018person} &CVPR18& Duke & 38.6& -& 66.1& -& Market & 27.4& - &50.7 & - \\ SPGAN\cite{deng2018image} & CVPR18& Duke & 51.5& 70.1 &76.8& 22.8& Market &41.1& 56.6& 63.0& 22.3 \\ CAMEL\cite{yu2017cross} & ICCV17& Multi & 54.5& -& -& 26.3&- & -& -& - & -\\ MMFA\cite{lin2018multi} & BMVC19 & Duke &56.7& 75.0& 81.8& 27.4& Market & 45.3& 59.8 &66.3& 24.7 \\ TJ-AIDL\cite{wang2018transferable} & CVPR18& Duke &58.2 &74.8 &81.1 &26.5& Market & 44.3& 59.6 &65.0& 23.0 \\ HHL\cite{zhong2018generalizing} &ECCV18 & Duke & 62.2 & 78.8 & 84.0 & 31.4 &Market &46.9 & 61.0 & 66.7 & 27.2 \\ ECN\cite{zhong2019invariance} & CVPR19 & Duke & 75.1 & 87.6 & 91.6 & 43.0 &Market & 63.3 & 75.8 & 80.4 & 40.4 \\ MAR\cite{yu2019unsupervised} &CVPR19 & MSMT & 67.7 &81.9 &- &40.0 & MSMT & 67.1 & 79.8 & - &48.0\\ PAUL\cite{Yang_2019_CVPR} & CVPR19 & MSMT & 68.5 & 82.4 & 87.4 & 40.1 & MSMT & 72.0 & 82.7 & \textbf{86.0} & 53.2 \\ SSG\cite{Fu_2019_ICCV} & ICCV19 & Duke & \underline{80.0} & \underline{90.0} & \underline{92.4} & \underline{58.3} & Market & \textbf{73.0} & 80.6 & 83.2 & \underline{53.4} \\ CR-GAN\cite{Chen_2019_ICCV} & ICCV19 & Duke & 77.7 & 89.7 & 92.7 & 54.0 & Market & 68.9 & 80.2 & 84.7 & 48.6 \\ CASCL\cite{Wu_2019_ICCV} & ICCV19 & MSMT & 65.4 & 80.6 & 86.2 & 35.5 & MSMT & 59.3 & 73.2 & 77.5 & 37.8\\ PDA-Net\cite{ Li_2019_ICCV} & ICCV19 & Duke & 75.2 & 86.3 & 90.2 & 47.6 & Market & 63.2 & 77.0 & 82.5 & 45.1\\ UCDA\cite{Qi_2019_ICCV} & ICCV19 & Duke & 64.3 & - & - & 34.5 & Market & 55.4 & - & - & 36.7\\ PAST\cite{Zhang_2019_ICCV} & ICCV19 & Duke & 78.38 & - & - & 54.62 & Market & 72.35 & - & - & \textbf{54.26}\\ \hline Ours (transfer) & This paper & Duke & \textbf{84.4} & \textbf{92.8} & \textbf{95.0} & \textbf{60.4} &Market & \underline{72.4} & \textbf{82.9} & \underline{85.0} & 51.4 \\ \hline \end{tabular} } \end{center} \vspace{-2mm} \caption{Unsupervised person re-ID performance comparison with state-of-the-art methods on Market-1501 and DukeMTMC-reID.} \vspace{-2mm} \label{table:sota-market-duke} \end{table*} \begin{table} \footnotesize \begin{center} \begin{tabular}{l|c|c|c|c|c} \hline \multirow{2}{*}{Method} & \multirow{2}{*}{Source} & \multicolumn{4}{c}{MSMT17} \\ \cline{3-6} & &Rank-1 & Rank-5 & Rank-10 & mAP \\ \hline\hline Ours & None & \textbf{35.4} & \textbf{44.8} & \textbf{49.8}& \textbf{11.2} \\ \hline\hline PTGAN~\cite{wei2018person} & Market &10.2 & - & 24.4 & 2.9 \\ ECN~\cite{zhong2019invariance} & Market & 25.3 & 36.3 & 42.1 & 8.5 \\ SSG~\cite{Fu_2019_ICCV} & Market & 31.6 & - & 49.6 & 13.2\\ Ours (transfer) & Market & \textbf{40.8} & \textbf{51.8} & \textbf{56.7} & \textbf{15.1} \\ \hline PTGAN~\cite{wei2018person} & Duke &11.8 & - & 27.4 & 3.3 \\ ECN~\cite{zhong2019invariance} & Duke & 30.2 & 41.5 & 46.8 & 10.2 \\ SSG~\cite{Fu_2019_ICCV} & Duke & 32.2 & - & 51.2 & 13.3\\ Ours (transfer) & Duke & \textbf{43.6} & \textbf{54.3} & \textbf{58.9} & \textbf{16.2}\\ \hline \end{tabular} \end{center} \vspace{-2mm} \caption{Comparison with state-of-the-art methods on MSMT17.} \vspace{-2mm} \label{table:sota-msmt17} \end{table} \vspace{-1mm} \subsection{Comparison with the State of the Art} We compare our method against state-of-the-art unsupervised learning and transfer learning approaches on Market-1501~\cite{zheng2015scalable}, DukeMTMC-reID~\cite{ristani2016performance} and MSMT17~\cite{wei2018person}. Table \ref{table:sota-market-duke} and Table \ref{table:sota-msmt17} summarize the comparison. Table \ref{table:sota-market-duke} reports comparisons on Market-1501 and DukeMTMC-reID. We compare two types of methods, including unsupervised learning methods: LOMO~\cite{liao2015person}, BOW~\cite{zheng2015scalable}, BUC~\cite{lin2019bottom} and DBC~\cite{ding12dispersion}, and transfer learning based approaches: PUL~\cite{fan2018unsupervised}, PTGAN~\cite{wei2018person}, SPGAN~\cite{deng2018image}, CAMEL~\cite{yu2017cross}, MMFA~\cite{lin2018multi}, TJ-AIDL~\cite{wang2018transferable}, HHL~\cite{zhong2018generalizing}, ECN~\cite{zhong2019invariance}, MAR~\cite{yu2019unsupervised}, PAUL~\cite{Yang_2019_CVPR}, SSG~\cite{Fu_2019_ICCV}, CR-GAN~\cite{Chen_2019_ICCV}, CASCL~\cite{Wu_2019_ICCV}, PDA-Net~\cite{ Li_2019_ICCV}, UCDA~\cite{Qi_2019_ICCV} and PAST~\cite{Zhang_2019_ICCV}. We first compare with unsupervised learning methods. LOMO and BOW utilize hand-crafted features, which show lower performance. BUC and DBC treat each image as a single cluster then merges clusters, thus share certain similarity to our work. However, our method outperforms them by large margins. The reasons could be because: 1) BUC tries to keep different clusters with similar size, hence could suffer from the issue of imbalanced number of positive labels. MPLP could alleviate this issue by adaptively selecting positive labels for different images. 2) As discussed in ablation studies, MMCL performs better than the cross entropy loss when using memory bank as classifier. Therefore, MPLP and MMCL effectively boost our performance. Under the transfer learning setting, our method achieves the best performance on Market-1501 in Table \ref{table:sota-market-duke}. For example, our rank-1 accuracy of on Market-1501 achieves 84.4\%, when using DukeMTMC-reID as the source dataset. Similarly, we get 72.4\% rank-1 accuracy on DukeMTMC-reID using Market-1501 as the source dataset. Although SSG and PAST achieve slightly better performance, our method is more flexible and can be used without labeled dataset. It is also interesting to observe that, with unsupervised learning setting, our method still outperforms several recent transfer learning methods, \emph{e.g.}, our rank-1 accuracy of 80.3\% on Market-1501 vs. 78.38\% and 64.3\% of PAST~\cite{Zhang_2019_ICCV} and UCDA~\cite{Qi_2019_ICCV}. We also conduct experiments on MSMT17, a larger and more challenging dataset. A limited number of works report performance on MSMT17, \emph{i.e.}, PTGAN~\cite{wei2018person}, ECN~\cite{zhong2019invariance}, and SSG~\cite{Fu_2019_ICCV}. As table \ref{table:sota-msmt17} shows, our approach outperforms existing methods by large margins under both unsupervised and transfer learning settings. For example, our method achieves 35.4\% and 43.6\%/40.8\% rank-1 accuracy respectively. This outperforms SSG by 11.4\% in rank-1 accuracy. The above experiments on three datasets demonstrate the promising performance of our MPLP and MMCL. \section{Conclusion} This paper proposes a multi-label classification method to address unsupervised person ReID. Different from previous works, our method works without requiring any labeled data or a good pre-trained model. This is achieved by iteratively predicting multi-class labels and updating the network with a multi-label classification loss. MPLP is proposed for multi-class label prediction by considering both visual similarity and cycle consistency. MMCL is introduced to compute the multi-label classification loss and address the vanishing gradient issue. Experiments on several large-scale datasets demonstrate the effectiveness of the proposed methods in unsupervised person ReID. \vspace{5mm} \noindent\textbf{Acknowledgement} This work is supported in part by The National Key Research and Development Program of China under Grant No. 2018YFE0118400, in part by Beijing Natural Science Foundation under Grant No. JQ18012, in part by Natural Science Foundation of China under Grant No. 61936011, 61425025, 61620106009, 61572050, 91538111. {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2020-04-21T02:25:59', 'yymm': '2004', 'arxiv_id': '2004.09228', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09228'}
arxiv
\section{Introduction} \emph{Positive and Unlabeled learning} (PU learning) is emerging in real-world applications since labeling large amounts of data is often prohibitive due to time, financial, and expertise constraints. PU learning typically deals with binary classification and has been applied to novelty or outlier detection~\cite{DBLP:conf/kdd/ElkanN08}, software clone detection~\cite{wei2018ijcai}, and disease gene identification~\cite{yang2014ensemblepu}. Given a large number of application scenarios, PU learning has been well studied in recent decades. Previous literature can be divided into two categories based on how unlabeled data is handled. The first line of research is called problem transformation. Through identifying reliable negative examples from unlabeled data, PU learning is transformed into supervised learning~\cite{DBLP:conf/icml/LiuLYL02,li2003ijcai}. Some other work regards unlabeled data directly as negative and considers hidden positive examples among unlabeled data as mislabeled examples. The PU learning problem is transformed into label noise learning~\cite{DBLP:conf/icml/LeeL03,shi2018ijcai}. The second line of research is developing unbiased PU learning risk estimators. This type of research can be seen as cost-sensitive classification~\cite{DBLP:conf/kdd/ElkanN08,DBLP:conf/nips/PlessisNS14,DBLP:conf/icml/PlessisNS15,DBLP:conf/nips/KiryoNPS17}. These unbiased risk estimators typically rely on the knowledge of class-prior which is usually unavailable in real-world problems. Although several approaches have been proposed to estimate the class-prior from PU data~\cite{DBLP:conf/icml/MenonROW15,DBLP:conf/icml/RamaswamyST16,DBLP:journals/ml/PlessisNS17,DBLP:conf/aaai/BekkerD18}, inaccurate estimation usually results in severe performance degeneration as illustrated in Figure~\ref{img:estimation-error}. It is worth noting that although deep learning achieves excellent performance in semi-supervised learning tasks~\cite{DBLP:conf/nips/SajjadiJT16}, it has not been fully applied to PU learning. Moreover, in much recent work, many effective strategies have been proposed for the training of deep neural networks leveraging unlabeled data, such as \emph{consistency regularization}~\cite{DBLP:conf/nips/TarvainenV17,miyato2018vat} and \emph{mixup}~\cite{DBLP:conf/iclr/ZhangCDL18}. It is demonstrated that these approaches help enhance the performance for semi-supervised learning with a large margin on various problems In this paper, we introduce~{\textsc{MixPUL}}, a new consistency-based data augmentation algorithm. Unlike previous approaches,~{\textsc{MixPUL}}~does not require the knowledge of class-prior. We introduce a unified loss term for PU data that seamlessly improves AUC while encouraging consistency between datapoints. By using mixup, it interpolates pairs of datapoints and their corresponding class labels. The network is then regularized to minimize the distance between its output and the interpolated class labels. It is observed that mixup can move the decision boundary to low-density regions of the data distribution~\cite{DBLP:conf/ijcai/VermaLKBL19} and encourage the model to generalize better to unseen data. Due to the absence of negative samples for training, we propose to mine reliable negative examples from unlabeled data to facilitate supervised consistency loss. In extensive ablation studies, we show the effectiveness of consistency regularization and negative example mining techniques. In summary, our contributions are: \begin{itemize} \item We apply consistency regularization to PU learning to yield a simple yet effective approach which does not need the knowledge of class-prior compared with existing state of the art. \item We examine three reliable negative mining methods and show that the randomized technique works best. \item We conduct experiments showing that applying consistency regularization can yield substantial improvements over prior state of the art. For example, the proposed method improves classification error from 16.49 to 13.09 on average over the CIFAR-10 dataset. \end{itemize} The rest of this paper is arranged as follows. We start by a brief introduction to the problem setting and consistency regularization. Next, we present the proposed algorithm. After that, experimental results are reported followed by the conclusion of this work. \begin{figure}[tb] \centering \includegraphics[width=0.5\linewidth]{ill-estimation-error-nnpu.pdf} \caption{The performance comparison (AUC) using nnPU with true and estimated class-frequency is demonstrated. We vary the class-frequency $c = |{\mathcal P}| / (|{\mathcal P}| + \pi |{\mathcal U}|)$ to simulate PU problems in the wild where $\pi$ is class-prior.}\label{img:estimation-error} \end{figure} \section{Preliminaries} \subsection{Problem Setup} Given $N$ samples ${\mathcal D} = \{{\boldsymbol x}_i, s_i\}_{i = 1}^{N}$ where ${\boldsymbol x}_i \in \mathbb{R}^d$ and $s_i \in \{0, 1\}$. ${\boldsymbol x}_i$ is regarded as a positive example if $s_i = 1$, otherwise an unlabeled example. We denote the set of positive examples as ${\mathcal P}$ and unlabeled set as ${\mathcal U} = {\mathcal D} \setminus {\mathcal P}$. The positive set ${\mathcal P}$ of data is sampled independently from the underlying joint density $p({\boldsymbol x} | y = 1)$ and ${\mathcal U}$ is sampled from a mixture density $p({\boldsymbol x}) = \pi p({\boldsymbol x} | y = 1) +(1 - \pi) p({\boldsymbol x} | y = 0)$ where $\pi$ indicates the \emph{class-prior probability} and $y$ represents the true class label of instance ${\boldsymbol x}$. The same as conventional supervised learning, PU learning aims to learn a classifier $p(y = 1 | {\boldsymbol x})$ which distinguishes positive and negative data. \subsection{Interpolation Consistency Regularization} The mixup operator was first introduced by~\cite{DBLP:conf/iclr/ZhangCDL18} for supervised learning and can be defined as: \begin{equation*} \operatorname{Mix}_{\lambda}({\boldsymbol x}_a, {\boldsymbol x}_b)=\lambda \cdot {\boldsymbol x}_a+(1-\lambda) \cdot {\boldsymbol x}_b, \end{equation*} where ${\boldsymbol x}_a, {\boldsymbol x}_b$ are two labeled examples and the coefficient $\lambda$ is sampled from the Beta distribution. Later,~\cite{DBLP:journals/corr/abs-1905-02249} adapts mixup to semi-supervised learning and applies interpolation between unlabeled datapoints. Interpolation-based consistency trains a prediction model $f_{\theta}$ to provide consistent predictions at interpolations of unlabeled points: \begin{equation*} f_{\theta}\left(\operatorname{Mix}_{\lambda}\left({\boldsymbol x}_{j}, {\boldsymbol x}_{k}\right)\right) \approx \operatorname{Mix}_{\lambda}\left(f_{\theta^{\prime}}\left({\boldsymbol x}_{j}\right), f_{\theta^{\prime}}\left({\boldsymbol x}_{k}\right)\right), \end{equation*} where ${\boldsymbol x}_j, {\boldsymbol x}_k$ are a pair of unlabeled examples and $\theta^{\prime}$ is a moving average of the network parameter $\theta$. The interpolation-based consistency can be seen as encouraging the model to have strictly linear behavior ``between'' examples, by requiring that the model's output for a convex combination of two inputs is close to the convex combination of the output for each individual input. The mixup regularizer and consistency loss have not been previously investigated in PU learning and it is interesting to investigate its efficiency. \section{Method} \subsection{Consistency Regularization for PU Learning} During training phase of neural networks $f_\theta$, given a batch ${\mathcal X}_{{\mathcal P}} \subset {\mathcal P}$ of positively labeled examples with corresponding targets and an equally-sized batch ${\mathcal X}_{{\mathcal U}} \subset {\mathcal U}$ of unlabeled examples,~{\textsc{MixPUL}}~produces a processed batch of augmented unlabeled examples ${\mathcal X}_{{\mathcal U}}^{\prime}$ with ``soft'' labels using mixup. ${\mathcal X}_{{\mathcal U}}^{\prime}$ is then used in computing the unsupervised consistency loss term. For each pair of two unlabeled samples and their ``soft'' labels $({\boldsymbol x}_j, \hat{y}_j), ({\boldsymbol x}_k, \hat{y}_k)$ where $\hat{y}_j = f_{\theta^{\prime}}\left({\boldsymbol x}_{j}\right), \hat{y}_k = f_{\theta^{\prime}}\left({\boldsymbol x}_{k}\right)$, an augmented unlabeled datapoint $({\boldsymbol x}^\prime, \hat{y}^\prime)$ is obtained as follows using mixup operator: \begin{equation} {\boldsymbol x}^{\prime} = \lambda {\boldsymbol x}_j + (1 - \lambda) {\boldsymbol x}_k \end{equation} and \begin{equation}\label{equ:mixlabel} \hat{y}^{\prime} = \lambda \hat{y}_j + (1 - \lambda) \hat{y}_k, \end{equation} where \begin{equation} \lambda \sim \operatorname{Beta}(\alpha, \alpha) \end{equation} and $\alpha$ is a hyperparameter of the Beta distribution. In our implementations, we first collect unlabeled examples with their guessed labels into: \begin{equation} {\mathcal X}_{{\mathcal U}} = \{({\boldsymbol x}_1, \hat{y}_1), \dots, ({\boldsymbol x}_B, \hat{y}_B)\}. \end{equation} and after performing mixup we get: \begin{equation} {\mathcal X}_{{\mathcal U}}^{\prime} = \left\{\bigl(\mathrm{Mix}\left({\boldsymbol x}_i, {\boldsymbol x}_{r_i}\right), \mathrm{Mix}\left(\hat{y}_i, \hat{y}_{r_i}\right)\bigr)\right\}_{i = 1}^{B}, \end{equation} where $r$ is a random permutation of $[B]$. Notably, instead of predicting soft labels $\hat{y}_j$ and $\hat{y}_k$ in Equation (\ref{equ:mixlabel}) using network $f_{\theta}$, we maintain a moving average $\theta^{\prime}$ of parameter $\theta$ following~\cite{DBLP:conf/nips/TarvainenV17,DBLP:conf/ijcai/VermaLKBL19} and set $\hat{y}_j = f_{\theta^\prime}({\boldsymbol x}_j)$. Then, we perform ${\mathcal W} = \text{Shuffle}({\mathcal X}_{{\mathcal U}})$ which will serve as a data source for mixup. For each the $i$-th example and label pair $({\boldsymbol x}_i, \hat{y}_i) \in {\mathcal X}_{{\mathcal U}}$ and $({\boldsymbol x}_{r_i}, \hat{y}_{r_i}) \in {\mathcal W}$, we apply the mixup operator and add the result to the collection ${\mathcal X}_{{\mathcal U}}^{\prime}$. Note that the interpolation is only applied between unlabeled datapoints so far and on each mini-batch we sample a random $\lambda$ from $\mathrm{Beta}(\alpha, \alpha)$ for mixup. To summarize, by using mixup, ${\mathcal X}_{{\mathcal U}}$ is transformed into ${\mathcal X}_{{\mathcal U}}^{\prime}$, a collection of multiple augmentations of each unlabeled example with corresponding ``soft'' label. \subsection{Reliable Negative Mining} It is noteworthy that applying mixup requires reasonably good ``soft'' labels, which is realized by training networks on labeled data in semi-supervised learning. In PU learning, it is unrealistic to train the networks by feeding only positive data. We alleviate this problem by identifying a subset of reliable negative (RN) examples from the unlabeled set. In this work, three different types of methods are considered. \begin{itemize} \item \emph{Rand:} We construct a set of ``pseudo'' negative examples by randomly downsampling the unlabeled set. \item \emph{Dist:} Unlabeled instances with the farthest averaged distance from positive data are selected as negative. \item \emph{NTC:} An Non-Traditional Classifier (NTC) is trained to discriminate ${\mathcal P}$ and ${\mathcal U}$. Instances with the smallest prediction scores are selected as negative. \end{itemize} The positive set ${\mathcal P}$ and the selected reliable negative samples ${\mathcal N} \subset {\mathcal U}$ are used to compute supervised consistency loss. Even when combining a positive sample and a false negative sample the loss computed can still be useful as the positive sample contains the true label of the other one. It is noteworthy that~{\textsc{MixPUL}}~does not reduce cross-entropy loss in case of overfitting. By leveraging consistency training, it can better explore the data space even when labeled data is scarce. We compare three RN mining methods in the experiments. \subsection{Objective Function} We describe each part of~{\textsc{MixPUL}}'s objective function in the following. Given batch ${\mathcal X}_{{\mathcal P}}$, ${\mathcal X}_{{\mathcal N}}$, and ${\mathcal X}_{{\mathcal U}}$, we construct ${\mathcal X}_{{\mathcal P}{\mathcal N}}^{\prime}$ by applying mixup operator on ${\mathcal X}_{{\mathcal P}}$ and ${\mathcal X}_{{\mathcal N}}$. Similarly, ${\mathcal X}_{{\mathcal U}}^{\prime}$ is formed by mixing unlabeled data ${\mathcal X}_{{\mathcal U}}$. We then combine the consistency loss and the margin loss. More formally, the combined loss $\mathcal{L}$ for our proposed~{\textsc{MixPUL}}~is computed as Equation~(\ref{equ:obj}): \begin{equation}\label{equ:obj} \begin{aligned}\mathcal{L} &=\mathcal{L}_{\mathcal{PN}} + \beta \mathcal{L}_{\mathcal{U}} + \gamma \mathcal{L}_{\mathcal{PU}}. \end{aligned} \end{equation} The first two terms respectively represent the supervised and unsupervised interpolation-based consistency loss and can be written as: \begin{equation}\label{equ:sup-consistencyloss} \begin{aligned} \mathcal{L}_{\mathcal{PN}} &=\frac{1}{\left|\mathcal{X}_\mathcal{PN}^{\prime}\right|} \sum_{{\boldsymbol x}, \hat{y} \in \mathcal{X}_\mathcal{PN}^{\prime}}\left\|\hat{y} - f_{\theta}({\boldsymbol x})\right\|_{2}^{2} \end{aligned} \end{equation} \begin{equation}\label{equ:consistencyloss} \begin{aligned} \mathcal{L}_{\mathcal{U}} &=\frac{1}{\left|\mathcal{X}_\mathcal{U}^{\prime}\right|} \sum_{{\boldsymbol x}, \hat{y} \in \mathcal{X}_\mathcal{U}^{\prime}}\left\|\hat{y} - f_{\theta}({\boldsymbol x})\right\|_{2}^{2} \end{aligned} \end{equation} By imposing consistency loss, it regularizes the network to have strictly linear behavior. Using ``soft'' labels can also alleviate the problem of absence of negative data. Since the consistency terms function as regularizers, we introduces a risk function, i.e., margin loss, between pairs of positive and unlabeled samples, which takes the following form: \begin{equation}\label{equ:pairwiseloss} \begin{aligned} \mathcal{L}_{\mathcal{PU}} &=\frac{1}{\left|\mathcal{X}_{\mathcal{P}}\right| \cdot \left|\mathcal{X}_\mathcal{U}\right|} \sum_{\substack{{\boldsymbol x}_{p} \in \mathcal{X}_{\mathcal{P}}, {\boldsymbol x}_{u} \in {\mathcal X}_{{\mathcal U}}}} \left|f_{\theta}({\boldsymbol x}_u) - f_{\theta}({\boldsymbol x}_p) + \eta \right|_{+}, \end{aligned} \end{equation} where $|z|_{+}$ returns $z$ if $z > 0$, otherwise $0$. $\eta$ is the margin parameter. By imposing $\mathcal{L}_{\mathcal{PU}}$,~{\textsc{MixPUL}}~is desired to produce higher prediction score for positive samples than unlabeled samples. It is shown that $\mathcal{L}_{\mathcal{PU}}$ can be viewed as an estimation of its supervised counterpart. Finally, we use hyperparameters $\beta$ and $\gamma$ to trade-off these three terms. When optimizing Problem~(\ref{equ:obj}), we compute the gradient $\nabla_{\theta} {\mathcal L}$ and update $\theta$ using standard SGD or Adam. Then we update the exponential moving average $\theta^{\prime}$ of network parameter $\theta$ following~\cite{DBLP:conf/nips/TarvainenV17}. \subsection{Theoretical Interpretation of Equation~(\ref{equ:obj})} We further explain our objective function from the perspective of empirical risk minimization. If we regard the consistency loss $\mathcal{L}_{\mathcal{PN}}$ and $\mathcal{L}_{\mathcal{U}}$ in Equation~(\ref{equ:obj}) as regularizations, the last term $\mathcal{L}_{\mathcal{PU}}$ can be interpreted as a risk function. The consistency loss can move the decision boundary to low-density regions of the data distribution~\cite{DBLP:conf/ijcai/VermaLKBL19}. The pairwise ranking loss is designated for PU-AUC risk minimization. Inspired by~\cite{DBLP:conf/aaai/XieL18}, the risk function in AUC optimization from PU data is equivalent to the risk in supervised AUC optimization. Particularly, let $\ell_{01} (z)$ denote the zero-one loss which returns 1 if $z < 0$, 0.5 if $z = 0$, and 0 otherwise. Supposing that unlabeled data is sampled from a mixture of class distribution $P({\boldsymbol x} | y = 0)$ and $P({\boldsymbol x} | y = 1)$ completely at random, we show that PU-AUC risk $R_{\mathrm{PU}}$ is an equivalent estimation of PN-AUC risk $R_{\mathrm{PN}}$ as follows. \begin{equation* \begin{aligned} R_{\mathrm{PU}} =& \underset{\boldsymbol{x} \sim \mathcal{X}_{\mathrm{P}}}{\mathbb{E}}\;\underset{\boldsymbol{x}^{\prime} \sim \mathcal{X}_{\mathrm{U}}}{\mathbb{E}}\ell_{01} \bigl( f(\boldsymbol{x})-f(\boldsymbol{x}^{\prime})\bigr)\\ =& \underset{\boldsymbol{x} \in \mathcal{X}_{\mathrm{P}}}{\mathbb{E}} [\pi \underset{\overline{\boldsymbol{x}} \sim \mathcal{X}_{\mathrm{P}}}{\mathbb{E}}\ell_{01} \bigl( f(\boldsymbol{x})-f(\overline{\boldsymbol{x}})\bigr) \\& + (1 - \pi) \underset{\hat{\boldsymbol{x}} \sim \mathcal{X}_{\mathrm{N}}}{\mathbb{E}}\ell_{01} \bigl( f(\boldsymbol{x})-f(\hat{\boldsymbol{x}})\bigr) ]\\ =& \pi \underset{\boldsymbol{x} \sim \mathcal{X}_{\mathrm{P}}}{\mathbb{E}}\;\underset{\overline{\boldsymbol{x}} \sim \mathcal{X}_{\mathrm{P}}}{\mathbb{E}}\ell_{01} \bigl( f(\boldsymbol{x})-f(\overline{\boldsymbol{x}})\bigr)\\ &+ (1 - \pi) \underset{\boldsymbol{x} \sim \mathcal{X}_{\mathrm{P}}}{\mathbb{E}}\;\underset{\hat{\boldsymbol{x}} \sim \mathcal{X}_{\mathrm{N}}}{\mathbb{E}}\ell_{01} \bigl( f(\boldsymbol{x})-f(\hat{\boldsymbol{x}})\bigr) \end{aligned} \end{equation*} The above equation holds thanks to the linearity of expectation. Note that the first term at the right hand side of the equation is a constant which equals to $\frac{\pi}{2}$. Therefore, it can be omitted in the optimization. Surprisingly, the second term coincides with PN-AUC risk $R_{\mathrm{PN}}$. In other words, we get: \begin{equation*} R_{\mathrm{PU}}= (1 - \pi) R_{\mathrm{PN}} +\frac{\pi}{2} \end{equation*} It is effortless to see that $R_{\mathrm{PU}}$ is a linear transformation of $R_{\mathrm{PN}}$. During training, the zero-one loss is usually replaced with a surrogate loss for the convenience of optimization. In our implementation, we substitute it with margin loss defined in Equation~(\ref{equ:pairwiseloss}) which is enough for AUC risk optimization when it gets minimized. \section{Experiments} To validate the superiority of~{\textsc{MixPUL}}, we conduct experiments on the MNIST\footnote{http://yann.lecun.com/exdb/mnist/}, CIFAR-10\footnote{https://www.cs.toronto.edu/~kriz/cifar.html}, and UCI datasets~\footnote{https://archive.ics.uci.edu/ml/datasets.php}. The comprehensive statistics of used datasets are listed in Table~\ref{exp:dataset}. Notably, the class-ratio of each dataset is the percentage of positive examples among training data. \begin{table}[ht] \centering \begin{tabular}{ L{1.5cm} C{1cm} C{1cm} C{1.2cm} C{1.6cm} } \toprule Dataset & \#Train & \#Test & \#Feature & Class-ratio\\ \midrule ethn & 1,840 & 790 & 30 & 0.50 \\ krvskp & 2,237 & 959 & 36 & 0.49 \\ titanic & 1,540 & 661 & 3 & 0.32 \\ spambase & 3,220 & 1,381 & 57 & 0.40 \\ MNIST & 60,000 & 10,000 & 784 & 0.49 \\ CIFAR-10 & 50,000 & 10,000 & 3,072 & 0.40 \\ \bottomrule \end{tabular} \caption{Dataset statistics}\label{exp:dataset} \end{table} \subsection{Implementation Details} Unless otherwise noted, in all experiments we use the multilayer perceptron. We simply evaluate models using an exponential moving average of their parameters with a decay rate of 0.999. We find in practice that most of~{\textsc{MixPUL}}'s hyperparameters can be fixed and do not need to be tuned on a per-experiment or per-dataset basis. Specifically, for all experiments, we respectively set the hyperparameters $\beta$ and $\gamma$ the objective function of~{\textsc{MixPUL}}~to $1$ and $1$ for simplicity. Further, we only change and $\alpha$ on a per-dataset basis; we found that $\alpha = 1$ are good starting points for tuning. We used the SGD with nesterov momentum optimizer for all of our experiments. For the experiments in Table 1 and Table 2, we run the experiments for 200 epochs. The initial learning rate was set to $10^{-5}$ on CIFAR-10 and $10^{-3}$ for other datasets. The momentum parameter was set to 0.9. We used a $L_2$ regularization coefficient $10^{-4}$ and a batch-size of 128 in our experiments. All the experiments were done with Pytorch\footnote{https://pytorch.org/}. \subsection{Competing Methods} The following methods are compared: \begin{itemize} \item \emph{Supervised}: This method trains a supervised classifier with lightGBM~\cite{DBLP:conf/nips/KeMFWCMYL17}. It treats unlabeled data as negative and uses hyperopt~\cite{komer2014hyperopt} for hyperparameter optimization. \item \emph{WSVM}: The method of~\cite{DBLP:conf/kdd/ElkanN08}. This method treats each unlabeled instance as a combination of positive and negative examples. \item \emph{Ramp}: The method of~\cite{DBLP:conf/nips/PlessisNS14} through optimizing ramp loss. This method is used for comparison with~{\textsc{MixPUL}}~on MNIST dataset. \item \emph{uPU}: The method of~\cite{DBLP:conf/icml/PlessisNS15} using unbiased PU learning risk estimator. \item \emph{nnPU}: The method of~\cite{DBLP:conf/nips/KiryoNPS17} using non-negative unbiased PU learning risk estimator. It is an improved version of uPU which usually overfits because the value of uPU loss can become negative. \item \emph{PNU}: The method of~\cite{Sakai2018PNU_AUC} which explicitly optimizes AUC. \end{itemize} \subsection{Results on MNIST} The model for MNIST is a 3-layer multilayer perceptron (MLP) with ReLU activation function. MNIST has 10 classes originally, and we constructed the ${\mathcal P}$ and ${\mathcal N}$ classes from them as follows: MNIST was preprocessed in such a way that 0 constitute the positive class, while one of \{1, 2, 3, 4, 5, 6, 7, 8, 9\} constitutes the negative class separately in each experimental setting. Subsequently, we randomly sample part of ${\mathcal P}$ which is denoted by ${\mathcal P}^{\prime}$. We set ${\mathcal P} = {\mathcal P} \setminus {\mathcal P}^{\prime}$ and ${\mathcal U} = {\mathcal N} \cup {\mathcal P}^{\prime}$ to form a PU dataset. We compare Ramp~\cite{DBLP:conf/nips/PlessisNS14} which optimizes ramp loss calculated on positive and unlabeled data with the knowledge of true class-prior. The comparison results are reported in Table~\ref{exp:mnist-error}. It is noted that~{\textsc{MixPUL}}~achieves lowest misclassification rate in comparison with Ramp~\cite{DBLP:conf/nips/PlessisNS14} in most settings we studied. Specifically,~{\textsc{MixPUL}}~significantly reduces the classification error rate from 5.48 to 0.33 in 0 vs. 1 task and from 22.58 to 3.51 in 0 vs. 6 task. It indicates that the model initialization for~{\textsc{MixPUL}}~produces considerably accurate ``soft'' labels facilitating the consistency loss. In summary, the empirical studies demonstrate that~{\textsc{MixPUL}}~is insensitive to class-prior and consistently outperforms Ramp which is one of the representative approaches based on unbiased risk minimization. \begin{table}[tb] \centering \ra{1.1} \rowcolors{1}{white}{gray!15} \begin{tabular}{l C{2cm} |C{1cm} C{1cm} C{1cm} } \toprule \rule{0pt}{2.2ex} Setting & Method & 1,200 & 2,400 & 3,600 \\ \midrule \rule{0pt}{2.2ex} \cellcolor{white} & Ramp & 3.36 & 4.85 & 5.48 \\ \multirow{-2}{*}{0 vs. 1}\rule{0pt}{2.2ex} \cellcolor{white} &{\textsc{MixPUL}} & \bf 0.24 & \bf 0.33 & \bf 0.33 \\ \hline \rule{0pt}{2.2ex} \cellcolor{white} & Ramp & 5.15 & 6.96& 7.22 \\ \multirow{-2}{*}{0 vs. 2}\rule{0pt}{2.2ex} \cellcolor{white} &{\textsc{MixPUL}} &\bf 4.57 & \bf 2.83 & \bf 2.14 \\ \hline \rule{0pt}{2.2ex} \cellcolor{white} & Ramp & 3.49 & 4.72 & 5.02 \\ \multirow{-2}{*}{0 vs. 3}\rule{0pt}{2.2ex} \cellcolor{white} &{\textsc{MixPUL}} &\bf 3.02 & \bf 2.41 & \bf 2.46 \\ \hline \rule{0pt}{2.2ex} \cellcolor{white} & Ramp & 1.68& 2.05 & 2.21 \\ \multirow{-2}{*}{0 vs. 4}\rule{0pt}{2.2ex} \cellcolor{white} &{\textsc{MixPUL}} & \bf 0.76 & \bf 0.66 & \bf 0.46 \\ \hline \rule{0pt}{2.2ex} \cellcolor{white} & Ramp & 5.21 & 7.22 & \bf 7.46 \\ \multirow{-2}{*}{0 vs. 5}\rule{0pt}{2.2ex} \cellcolor{white} &{\textsc{MixPUL}} & \bf 1.60 & \bf 3.63 & 9.62 \\ \hline \rule{0pt}{2.2ex} \cellcolor{white} & Ramp & 11.47 & 19.87 & 22.58 \\ \multirow{-2}{*}{0 vs. 6} \rule{0pt}{2.2ex} \cellcolor{white} &{\textsc{MixPUL}} &\bf 8.57 & \bf 5.31 & \bf 3.51 \\ \hline \rule{0pt}{2.2ex} \cellcolor{white} & Ramp & 1.89 & 2.55 & 2.64 \\ \multirow{-2}{*}{0 vs. 7}\rule{0pt}{2.2ex} \cellcolor{white} &{\textsc{MixPUL}} & \bf 1.64 & \bf 1.20 & \bf 1.15 \\ \hline \rule{0pt}{2.2ex} \cellcolor{white} & Ramp & 3.98 & 4.81 & 4.75 \\ \multirow{-2}{*}{0 vs. 8}\rule{0pt}{2.2ex} \cellcolor{white} &{\textsc{MixPUL}} &\bf 3.58 & \bf 2.81 & \bf 2.41 \\ \hline \rule{0pt}{2.2ex} \cellcolor{white} & Ramp & 1.22& 1.60& \bf 1.73 \\ \multirow{-2}{*}{0 vs. 9}\rule{0pt}{2.2ex} \cellcolor{white} &{\textsc{MixPUL}} & \bf 1.21 & \bf 0.96 & 3.02 \\ \bottomrule \end{tabular} \caption{Misclassification rate (in percent) of~{\textsc{MixPUL}}~and Ramp on MNIST dataset. We set the amount of positive data $|{\mathcal P}|$ from $\{1200, 2400, 3600\}$. The best results are in bold.}\label{exp:mnist-error} \end{table} \subsection{Results on CIFAR-10} We compare our method with state-of-the-art PU learning algorithms on CIFAR-10 dataset. We use the same architecture for all methods as specified in~\cite{DBLP:conf/nips/KiryoNPS17}. CIFAR-10 has 10 classes originally, and we construct the \emph{positive} class and \emph{negative} class as follows. The \emph{positive} class is formed by ``airplane'', ``automobile'', ``ship'', and ``truck'', and the \emph{negative} class is formed by ``bird'', ``cat'', ``deer'', ``dog'', ``frog'', and ``horse''. The results are reported in Table~\ref{cifar10-comparison}. We find that \emph{uPU} is very prone to overfitting and we therefore use a small number of epoch (less than 10). When only 100 positive examples are available, both \emph{nnPU} and \emph{uPU} tend to treat all unlabeled data as negative, which prevent the model from training. Our consistency-regularized model achieve the lowest (best) classification error in 5 out of 6 settings. The comparison result is especially encouraging, considering that \emph{nnPU} and \emph{uPU} use the knowledge of class-prior. \begin{table}[htbp] \small \ra{1.3} \centering \begin{tabular}{l|c|c|c|c|c|c} Method & 100 & 500 & 1k & 2k & 4k & 10k \\ \hline nnPU & 40.00 & 15.55 & 13.32 & 11.32 & 9.90 & \bf8.87\\ \hline uPU & 40.00 & 26.01 & 19.95 & 14.38 & 12.08 & 9.90 \\ \hline {\textsc{MixPUL}} & \bf22.63 & \bf14.00 & \bf12.21 & \bf11.10 &\bf 9.77 & 8.88 \\ \end{tabular} \caption{Error rate on \emph{CIFAR-10} dataset with varying number of positively labeled data.} \label{cifar10-comparison} \end{table} \begin{table*}[!t] \centering \rowcolors{1}{white}{gray!15} \begin{tabular}{l C{1.5cm} |C{2cm} C{2cm} C{2cm} C{2cm} C{2cm} } \toprule \rule{0pt}{2.0ex}Dataset & Method & 0.01 & 0.05 & 0.1 & 0.2 & 0.4 \\ \midrule \rule{0pt}{2.0ex} \cellcolor{white} & Supervised & 0.50$\pm$0.00 & 0.69$\pm$0.10 & 0.89$\pm$0.02 & 0.92$\pm$0.01 & 0.96$\pm$0.00 \\ \rule{0pt}{2.0ex} \cellcolor{white} &WSVM & 0.56$\pm$0.20 & \bf0.96$\pm$0.01 & \bf0.98$\pm$0.00 & \bf0.99$\pm$0.00 & \bf0.99$\pm$0.00 \\ \rule{0pt}{2.0ex} \cellcolor{white} & uPU & 0.66$\pm$0.07 & 0.84$\pm$0.04 & 0.94$\pm$0.01 & 0.96$\pm$0.00 & 0.97$\pm$0.00 \\ \rule{0pt}{2.0ex} \cellcolor{white} & nnPU & 0.63$\pm$0.07 & 0.80$\pm$0.09 & 0.82$\pm$0.03 & 0.86$\pm$0.03 & 0.86$\pm$0.01 \\ \rule{0pt}{2.0ex} \cellcolor{white} & PNU & 0.71$\pm$0.04 & 0.92$\pm$0.01 & 0.94$\pm$0.01 & 0.95$\pm$0.01 & 0.97$\pm$0.00 \\ \multirow{-7}{*}{ethn}\rule{0pt}{2.0ex} \cellcolor{white} & {\textsc{MixPUL}} & \bf 0.73$\pm$0.04 & 0.92$\pm$0.01 & 0.97$\pm$0.00 & 0.98$\pm$0.00 & 0.94$\pm$0.00 \\ \hline \rule{0pt}{2.0ex} \cellcolor{white} & Supervised & 0.50$\pm$0.00 & 0.81$\pm$0.06 & 0.87$\pm$0.07 & \bf0.97$\pm$0.01 & \bf0.98$\pm$0.00 \\ \rule{0pt}{2.0ex} \cellcolor{white} &WSVM & 0.61$\pm$0.07 & 0.77$\pm$0.06 & 0.81$\pm$0.05 & 0.85$\pm$0.04 & 0.88$\pm$0.05 \\ \rule{0pt}{2.0ex} \cellcolor{white} & uPU & 0.72$\pm$0.08 & 0.85$\pm$0.06 & 0.89$\pm$0.04 & 0.95$\pm$0.02 & 0.96$\pm$0.02 \\ \rule{0pt}{2.0ex} \cellcolor{white} & nnPU & 0.62$\pm$0.09 & 0.78$\pm$0.03 & 0.82$\pm$0.06 & 0.84$\pm$0.02 & 0.88$\pm$0.04 \\ \rule{0pt}{2.0ex} \cellcolor{white} & PNU & \bf0.72$\pm$0.07 & 0.88$\pm$0.03 & 0.91$\pm$0.03 & 0.95$\pm$0.09 & 0.96$\pm$0.00 \\ \multirow{-7}{*}{krvskp}\rule{0pt}{2.0ex} \cellcolor{white} & {\textsc{MixPUL}} & 0.70$\pm$0.08 & \bf0.90$\pm$0.03 & \bf0.93$\pm$0.02 & 0.96$\pm$0.00 & 0.97$\pm$0.00 \\ \hline \rule{0pt}{2.0ex} \cellcolor{white} & Supervised & 0.50$\pm$0.00 & 0.50$\pm$0.00 & 0.69$\pm$0.02 & 0.72$\pm$0.01 & \bf0.71$\pm$0.00 \\ \rule{0pt}{2.0ex} \cellcolor{white} &WSVM & 0.35$\pm$0.04 & 0.68$\pm$0.05 & \bf0.73$\pm$0.01 & \bf0.73$\pm$0.02 & 0.71$\pm$0.02 \\ \rule{0pt}{2.0ex} \cellcolor{white} & uPU & 0.64$\pm$0.09 & \bf0.70$\pm$0.01 & 0.71$\pm$0.00 & 0.71$\pm$0.00 & \bf0.71$\pm$0.00 \\ \rule{0pt}{2.0ex} \cellcolor{white} & nnPU & 0.63$\pm$0.05 & 0.70$\pm$0.03 & 0.70$\pm$0.02 & 0.71$\pm$0.01 & 0.71$\pm$0.02 \\ \rule{0pt}{2.0ex} \cellcolor{white} & PNU & 0.63$\pm$0.08 & 0.69$\pm$0.00 & 0.70$\pm$0.02 & 0.70$\pm$0.00 & 0.70$\pm$0.00 \\ \multirow{-7}{*}{titanic}\rule{0pt}{2.0ex} \cellcolor{white} & {\textsc{MixPUL}} & \bf 0.67$\pm$0.01 & 0.68$\pm$0.01 & 0.70$\pm$0.01 & 0.71$\pm$0.01 & \bf0.71$\pm$0.00 \\ \hline \rule{0pt}{2.0ex} \cellcolor{white} & Supervised & 0.50$\pm$0.00 & 0.89$\pm$0.02 & 0.90$\pm$0.01 & 0.93$\pm$0.02 & 0.95$\pm$0.01\\ \rule{0pt}{2.0ex} \cellcolor{white} &WSVM & 0.36$\pm$0.01 & 0.58$\pm$0.00 & 0.72$\pm$0.00 & 0.79$\pm$0.00 & 0.85$\pm$0.00 \\ \rule{0pt}{2.0ex} \cellcolor{white} & uPU & 0.87$\pm$0.05 & 0.91$\pm$0.01 & 0.93$\pm$0.00 & 0.93$\pm$0.01 & 0.94$\pm$0.00 \\ \rule{0pt}{2.0ex} \cellcolor{white} & nnPU &0.77$\pm$0.07 & 0.87$\pm$0.01 & 0.90$\pm$0.00 & 0.91$\pm$0.01 & 0.92$\pm$0.00 \\ \rule{0pt}{2.0ex} \cellcolor{white} & PNU &0.76$\pm$0.07 & 0.87$\pm$0.01 & 0.91$\pm$0.01 & 0.93$\pm$0.00 & 0.94$\pm$0.00 \\ \multirow{-7}{*}{spambase}\rule{0pt}{2.0ex} \cellcolor{white} & {\textsc{MixPUL}} &\bf 0.89$\pm$0.01 & \bf0.92$\pm$0.01 & \bf0.94$\pm$0.01 & \bf0.94$\pm$0.01 & \bf0.96$\pm$0.00 \\ \bottomrule \end{tabular} \caption{Experimental comparisons on benchmark datasets with varying class-frequency. On each dataset, 10 test runs were conducted. The average AUC and standard deviation are presented. The true value of class-prior is used in uPU and nnPU. The best results in each setting are in bold.~{\textsc{MixPUL}}~(ours) achieves competitive performance.}\label{exp:uci-all} \end{table*} \subsection{Results on UCI Datasets} To simulate PU learning problems in the wild, we construct PU data with varying class-frequency $c$. More specifically, we run all competing methods by setting class-frequency $c$ to $c^\prime \in \{0.01, 0.05, 0.1, 0.2, 0.4\}$ through randomly downsampling positive examples and appending them into the unlabeled set ${\mathcal U}$. For each $c'$, we repeat the experiment $10$ times and report the average performance. The comparison results in terms of AUC are shown in Table~\ref{exp:uci-all}, where means and standard deviations of testing performance based on $10$ random samplings are reported. It is effortless to see that the supervised baseline performs dreadfully with a modest set of positive examples. When more and more positive examples are observed, it achieves competing results because sampled unlabeled examples are becoming more likely to be negative. This validates that the supervised baseline is considerably good and should be compared in PU learning literature. We implement WSVM using Gaussian kernel and it fits the data very well in most cases except when the number of positive examples is extremely limited. Since deep neural networks are used in nnPU, it is no surprise that its performance on small datasets (e.g., ethn, krvskp) is usually worse than other algorithms owing to the lack of labeled examples. It is interesting to observe that the AUC score of comparison methods is approaching 1.0 even when $c = 0.01$ on \emph{spambase}, which indicates that this dataset is relatively easier to deal with. It is noteworthy that~{\textsc{MixPUL}}~is able to achieve superior or comparable results with uPU and nnPU even though they use the true value of class-prior $\pi$ especially when $|{\mathcal P}|$ is small. In summary, our~{\textsc{MixPUL}}~can readily adapted across many practical tasks without the knowledge of class-prior and assumptions over the data distribution. \subsection{Ablation Studies and Discussion} In the following, we provide an analysis of the effects of different parts of objective function and RN mining methods. \begin{table}[htbp] \small \ra{1.3} \centering \begin{tabular}{l|c|c|c|c} Method & 5 & 25 & 50 & 100 \\ \hline Rand & \bf0.67$\pm$0.01 & \bf0.68$\pm$0.01 & \bf0.70$\pm$0.01 & \bf0.71$\pm$0.01\\ \hline Dist & 0.48$\pm$0.14 & 0.53$\pm$0.16 & 0.66$\pm$0.01 & 0.47$\pm$0.15 \\ \hline NTC & 0.56$\pm$0.11 & 0.68$\pm$0.02 &\bf0.70$\pm$0.01 & 0.69$\pm$0.00 \\ \end{tabular} \caption{A comparison between negative mining methods on \emph{titanic} dataset with different amount of positive data $|{\mathcal P}| \in \{5, 25, 50, 100\}$.}\label{rn-comparison} \end{table} \subsubsection{How Does the Type of RN Mining Affect Results?} We report numerical results of employing three different reliable negative mining methods by fixing other components of the networks in Table~\ref{rn-comparison}. Euclidean distance is used in \emph{Dist} method. For \emph{NTC} method, we train a random forest classifier. It is effortless to observe that \emph{Dist} has the worst performance. This indicates that it is unsafe to use distance-based classifiers for unknown data distribution. Therefore, we use \emph{Rand} in all experiments for its observed good performance. We also tried to train the networks without RN examples. Since only positive examples are fed, the networks suffer from overfitting after a few epochs. \subsubsection{How Much Does Unsupervised Mixup Matter By Itself?} We study the effect of mixup by training the networks with and without unsupervised interpolation-based consistency loss on one of the image datasets, \emph{ethn}. As shown in Figure~\ref{exp:mixup}, the vertical dashed line indicates the iteration where interpolation training begins. The red and blue lines respectively demonstrate the classification error with and without unsupervised mixup. If we apply the mixup operator on unlabeled data, the misclassification rate initially increases very fast because augmented data is generated which the networks have never seen. After a few iterations, the error rate decreases to less than 10\% which is far smaller than the number without using unsupervised mixup. The results demonstrate the effectiveness of mixup and provide another way of employing unlabeled data for PU learning. \begin{figure}[ht] \centering \begin{subfigure}[tb]{0.48\linewidth}\centering \includegraphics[width=1\linewidth]{figures/mixup_ablation} \caption{Ablations on mixup}\label{exp:mixup} \end{subfigure} \begin{subfigure}[tb]{0.48\linewidth}\centering \includegraphics[width=1\linewidth]{figures/pairwise_ranking_ablation} \caption{Ablations on margin loss}\label{exp:pairwise} \end{subfigure} \caption{Ablation studies on unsupervised mixup (left) and margin loss (right).} \end{figure} \subsubsection{How Does Margin Loss Affect Results?} In our objective function, we use margin loss between positive and unlabeled example pairs guiding the model to give higher prediction scores for observed positive examples than unlabeled ones. As shown in Figure~\ref{exp:pairwise}, it results in faster convergence by incorporating margin loss. We also observe that the model has a more stable performance when the mixup is applied as illustrated by the vertical dashed line. The results coincide with our theoretical analysis that the margin loss leads to AUC risk minimization. In a brief summary, we provide an analysis of the effects of mixup, margin loss, and the negative example mining methods for researchers and practitioners. We find that mixup is more effective on image datasets than other types of data and it also provides a new way of using unlabeled instances for PU learning. Further, by incorporating margin loss, it leads to faster convergence for the networks and makes the model performs more stably when applying mixup. Finally, randomly downsampling unlabeled data as negative is an effective RN mining method for PU learning. \section{Conclusion} In this work, we introduce~{\textsc{MixPUL}}~which applies interpolation-based consistency regularization to PU learning.~{\textsc{MixPUL}}~has two advantages over previous PU learning approaches. First, it does not require the knowledge of class-prior, which otherwise hinders the applicability of the algorithm. Second, through extensive experiments, we find that~{\textsc{MixPUL}}~exhibited significantly performance improvements over prior state of the art. Besides, we empirically observe that the proposed negative mining techniques are considerably effective, without which the model corrupts and is unable to incorporate consistency regularization. Specifically, different negative example mining techniques are further investigated and we find the randomized method work very well. We also conduct thorough ablation studies on the consistency regularization and the margin loss. We hope that the proposed consistency regularization will become a standard element in PU learning, and that it will make things easier and simpler for researchers and practitioners. \bibliographystyle{unsrt} \section{Introduction} \lipsum[2] \lipsum[3] \section{Headings: first level} \label{sec:headings} \lipsum[4] See Section \ref{sec:headings}. \subsection{Headings: second level} \lipsum[5] \begin{equation} \xi _{ij}(t)=P(x_{t}=i,x_{t+1}=j|y,v,w;\theta)= {\frac {\alpha _{i}(t)a^{w_t}_{ij}\beta _{j}(t+1)b^{v_{t+1}}_{j}(y_{t+1})}{\sum _{i=1}^{N} \sum _{j=1}^{N} \alpha _{i}(t)a^{w_t}_{ij}\beta _{j}(t+1)b^{v_{t+1}}_{j}(y_{t+1})}} \end{equation} \subsubsection{Headings: third level} \lipsum[6] \paragraph{Paragraph} \lipsum[7] \section{Examples of citations, figures, tables, references} \label{sec:others} \lipsum[8] \cite{kour2014real,kour2014fast} and see \cite{hadash2018estimate}. 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} \begin{center} \url{https://www.ctan.org/pkg/booktabs} \end{center} \subsection{Figures} \lipsum[10] See Figure \ref{fig:fig1}. Here is how you add footnotes. \footnote{Sample of the first footnote.} \lipsum[11] \begin{figure} \centering \fbox{\rule[-.5cm]{4cm}{4cm} \rule[-.5cm]{4cm}{0cm}} \caption{Sample figure caption.} \label{fig:fig1} \end{figure} \subsection{Tables} \lipsum[12] See awesome Table~\ref{tab:table}. \begin{table} \caption{Sample table title} \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} \label{tab:table} \end{table} \subsection{Lists} \begin{itemize} \item Lorem ipsum dolor sit amet \item consectetur adipiscing elit. \item Aliquam dignissim blandit est, in dictum tortor gravida eget. In ac rutrum magna. \end{itemize} \bibliographystyle{unsrt} \section{Introduction} \emph{Positive and Unlabeled learning} (PU learning) is emerging in real-world applications since labeling large amounts of data is often prohibitive due to time, financial, and expertise constraints. PU learning typically deals with binary classification and has been applied to novelty or outlier detection~\cite{DBLP:conf/kdd/ElkanN08}, software clone detection~\cite{wei2018ijcai}, and disease gene identification~\cite{yang2014ensemblepu}. Given a large number of application scenarios, PU learning has been well studied in recent decades. Previous literature can be divided into two categories based on how unlabeled data is handled. The first line of research is called problem transformation. Through identifying reliable negative examples from unlabeled data, PU learning is transformed into supervised learning~\cite{DBLP:conf/icml/LiuLYL02,li2003ijcai}. Some other work regards unlabeled data directly as negative and considers hidden positive examples among unlabeled data as mislabeled examples. The PU learning problem is transformed into label noise learning~\cite{DBLP:conf/icml/LeeL03,shi2018ijcai}. The second line of research is developing unbiased PU learning risk estimators. This type of research can be seen as cost-sensitive classification~\cite{DBLP:conf/kdd/ElkanN08,DBLP:conf/nips/PlessisNS14,DBLP:conf/icml/PlessisNS15,DBLP:conf/nips/KiryoNPS17}. These unbiased risk estimators typically rely on the knowledge of class-prior which is usually unavailable in real-world problems. Although several approaches have been proposed to estimate the class-prior from PU data~\cite{DBLP:conf/icml/MenonROW15,DBLP:conf/icml/RamaswamyST16,DBLP:journals/ml/PlessisNS17,DBLP:conf/aaai/BekkerD18}, inaccurate estimation usually results in severe performance degeneration as illustrated in Figure~\ref{img:estimation-error}. It is worth noting that although deep learning achieves excellent performance in semi-supervised learning tasks~\cite{DBLP:conf/nips/SajjadiJT16}, it has not been fully applied to PU learning. Moreover, in much recent work, many effective strategies have been proposed for the training of deep neural networks leveraging unlabeled data, such as \emph{consistency regularization}~\cite{DBLP:conf/nips/TarvainenV17,miyato2018vat} and \emph{mixup}~\cite{DBLP:conf/iclr/ZhangCDL18}. It is demonstrated that these approaches help enhance the performance for semi-supervised learning with a large margin on various problems In this paper, we introduce~{\textsc{MixPUL}}, a new consistency-based data augmentation algorithm. Unlike previous approaches,~{\textsc{MixPUL}}~does not require the knowledge of class-prior. We introduce a unified loss term for PU data that seamlessly improves AUC while encouraging consistency between datapoints. By using mixup, it interpolates pairs of datapoints and their corresponding class labels. The network is then regularized to minimize the distance between its output and the interpolated class labels. It is observed that mixup can move the decision boundary to low-density regions of the data distribution~\cite{DBLP:conf/ijcai/VermaLKBL19} and encourage the model to generalize better to unseen data. Due to the absence of negative samples for training, we propose to mine reliable negative examples from unlabeled data to facilitate supervised consistency loss. In extensive ablation studies, we show the effectiveness of consistency regularization and negative example mining techniques. In summary, our contributions are: \begin{itemize} \item We apply consistency regularization to PU learning to yield a simple yet effective approach which does not need the knowledge of class-prior compared with existing state of the art. \item We examine three reliable negative mining methods and show that the randomized technique works best. \item We conduct experiments showing that applying consistency regularization can yield substantial improvements over prior state of the art. For example, the proposed method improves classification error from 16.49 to 13.09 on average over the CIFAR-10 dataset. \end{itemize} The rest of this paper is arranged as follows. We start by a brief introduction to the problem setting and consistency regularization. Next, we present the proposed algorithm. After that, experimental results are reported followed by the conclusion of this work. \begin{figure}[tb] \centering \includegraphics[width=0.5\linewidth]{ill-estimation-error-nnpu.pdf} \caption{The performance comparison (AUC) using nnPU with true and estimated class-frequency is demonstrated. We vary the class-frequency $c = |{\mathcal P}| / (|{\mathcal P}| + \pi |{\mathcal U}|)$ to simulate PU problems in the wild where $\pi$ is class-prior.}\label{img:estimation-error} \end{figure} \section{Preliminaries} \subsection{Problem Setup} Given $N$ samples ${\mathcal D} = \{{\boldsymbol x}_i, s_i\}_{i = 1}^{N}$ where ${\boldsymbol x}_i \in \mathbb{R}^d$ and $s_i \in \{0, 1\}$. ${\boldsymbol x}_i$ is regarded as a positive example if $s_i = 1$, otherwise an unlabeled example. We denote the set of positive examples as ${\mathcal P}$ and unlabeled set as ${\mathcal U} = {\mathcal D} \setminus {\mathcal P}$. The positive set ${\mathcal P}$ of data is sampled independently from the underlying joint density $p({\boldsymbol x} | y = 1)$ and ${\mathcal U}$ is sampled from a mixture density $p({\boldsymbol x}) = \pi p({\boldsymbol x} | y = 1) +(1 - \pi) p({\boldsymbol x} | y = 0)$ where $\pi$ indicates the \emph{class-prior probability} and $y$ represents the true class label of instance ${\boldsymbol x}$. The same as conventional supervised learning, PU learning aims to learn a classifier $p(y = 1 | {\boldsymbol x})$ which distinguishes positive and negative data. \subsection{Interpolation Consistency Regularization} The mixup operator was first introduced by~\cite{DBLP:conf/iclr/ZhangCDL18} for supervised learning and can be defined as: \begin{equation*} \operatorname{Mix}_{\lambda}({\boldsymbol x}_a, {\boldsymbol x}_b)=\lambda \cdot {\boldsymbol x}_a+(1-\lambda) \cdot {\boldsymbol x}_b, \end{equation*} where ${\boldsymbol x}_a, {\boldsymbol x}_b$ are two labeled examples and the coefficient $\lambda$ is sampled from the Beta distribution. Later,~\cite{DBLP:journals/corr/abs-1905-02249} adapts mixup to semi-supervised learning and applies interpolation between unlabeled datapoints. Interpolation-based consistency trains a prediction model $f_{\theta}$ to provide consistent predictions at interpolations of unlabeled points: \begin{equation*} f_{\theta}\left(\operatorname{Mix}_{\lambda}\left({\boldsymbol x}_{j}, {\boldsymbol x}_{k}\right)\right) \approx \operatorname{Mix}_{\lambda}\left(f_{\theta^{\prime}}\left({\boldsymbol x}_{j}\right), f_{\theta^{\prime}}\left({\boldsymbol x}_{k}\right)\right), \end{equation*} where ${\boldsymbol x}_j, {\boldsymbol x}_k$ are a pair of unlabeled examples and $\theta^{\prime}$ is a moving average of the network parameter $\theta$. The interpolation-based consistency can be seen as encouraging the model to have strictly linear behavior ``between'' examples, by requiring that the model's output for a convex combination of two inputs is close to the convex combination of the output for each individual input. The mixup regularizer and consistency loss have not been previously investigated in PU learning and it is interesting to investigate its efficiency. \section{Method} \subsection{Consistency Regularization for PU Learning} During training phase of neural networks $f_\theta$, given a batch ${\mathcal X}_{{\mathcal P}} \subset {\mathcal P}$ of positively labeled examples with corresponding targets and an equally-sized batch ${\mathcal X}_{{\mathcal U}} \subset {\mathcal U}$ of unlabeled examples,~{\textsc{MixPUL}}~produces a processed batch of augmented unlabeled examples ${\mathcal X}_{{\mathcal U}}^{\prime}$ with ``soft'' labels using mixup. ${\mathcal X}_{{\mathcal U}}^{\prime}$ is then used in computing the unsupervised consistency loss term. For each pair of two unlabeled samples and their ``soft'' labels $({\boldsymbol x}_j, \hat{y}_j), ({\boldsymbol x}_k, \hat{y}_k)$ where $\hat{y}_j = f_{\theta^{\prime}}\left({\boldsymbol x}_{j}\right), \hat{y}_k = f_{\theta^{\prime}}\left({\boldsymbol x}_{k}\right)$, an augmented unlabeled datapoint $({\boldsymbol x}^\prime, \hat{y}^\prime)$ is obtained as follows using mixup operator: \begin{equation} {\boldsymbol x}^{\prime} = \lambda {\boldsymbol x}_j + (1 - \lambda) {\boldsymbol x}_k \end{equation} and \begin{equation}\label{equ:mixlabel} \hat{y}^{\prime} = \lambda \hat{y}_j + (1 - \lambda) \hat{y}_k, \end{equation} where \begin{equation} \lambda \sim \operatorname{Beta}(\alpha, \alpha) \end{equation} and $\alpha$ is a hyperparameter of the Beta distribution. In our implementations, we first collect unlabeled examples with their guessed labels into: \begin{equation} {\mathcal X}_{{\mathcal U}} = \{({\boldsymbol x}_1, \hat{y}_1), \dots, ({\boldsymbol x}_B, \hat{y}_B)\}. \end{equation} and after performing mixup we get: \begin{equation} {\mathcal X}_{{\mathcal U}}^{\prime} = \left\{\bigl(\mathrm{Mix}\left({\boldsymbol x}_i, {\boldsymbol x}_{r_i}\right), \mathrm{Mix}\left(\hat{y}_i, \hat{y}_{r_i}\right)\bigr)\right\}_{i = 1}^{B}, \end{equation} where $r$ is a random permutation of $[B]$. Notably, instead of predicting soft labels $\hat{y}_j$ and $\hat{y}_k$ in Equation (\ref{equ:mixlabel}) using network $f_{\theta}$, we maintain a moving average $\theta^{\prime}$ of parameter $\theta$ following~\cite{DBLP:conf/nips/TarvainenV17,DBLP:conf/ijcai/VermaLKBL19} and set $\hat{y}_j = f_{\theta^\prime}({\boldsymbol x}_j)$. Then, we perform ${\mathcal W} = \text{Shuffle}({\mathcal X}_{{\mathcal U}})$ which will serve as a data source for mixup. For each the $i$-th example and label pair $({\boldsymbol x}_i, \hat{y}_i) \in {\mathcal X}_{{\mathcal U}}$ and $({\boldsymbol x}_{r_i}, \hat{y}_{r_i}) \in {\mathcal W}$, we apply the mixup operator and add the result to the collection ${\mathcal X}_{{\mathcal U}}^{\prime}$. Note that the interpolation is only applied between unlabeled datapoints so far and on each mini-batch we sample a random $\lambda$ from $\mathrm{Beta}(\alpha, \alpha)$ for mixup. To summarize, by using mixup, ${\mathcal X}_{{\mathcal U}}$ is transformed into ${\mathcal X}_{{\mathcal U}}^{\prime}$, a collection of multiple augmentations of each unlabeled example with corresponding ``soft'' label. \subsection{Reliable Negative Mining} It is noteworthy that applying mixup requires reasonably good ``soft'' labels, which is realized by training networks on labeled data in semi-supervised learning. In PU learning, it is unrealistic to train the networks by feeding only positive data. We alleviate this problem by identifying a subset of reliable negative (RN) examples from the unlabeled set. In this work, three different types of methods are considered. \begin{itemize} \item \emph{Rand:} We construct a set of ``pseudo'' negative examples by randomly downsampling the unlabeled set. \item \emph{Dist:} Unlabeled instances with the farthest averaged distance from positive data are selected as negative. \item \emph{NTC:} An Non-Traditional Classifier (NTC) is trained to discriminate ${\mathcal P}$ and ${\mathcal U}$. Instances with the smallest prediction scores are selected as negative. \end{itemize} The positive set ${\mathcal P}$ and the selected reliable negative samples ${\mathcal N} \subset {\mathcal U}$ are used to compute supervised consistency loss. Even when combining a positive sample and a false negative sample the loss computed can still be useful as the positive sample contains the true label of the other one. It is noteworthy that~{\textsc{MixPUL}}~does not reduce cross-entropy loss in case of overfitting. By leveraging consistency training, it can better explore the data space even when labeled data is scarce. We compare three RN mining methods in the experiments. \subsection{Objective Function} We describe each part of~{\textsc{MixPUL}}'s objective function in the following. Given batch ${\mathcal X}_{{\mathcal P}}$, ${\mathcal X}_{{\mathcal N}}$, and ${\mathcal X}_{{\mathcal U}}$, we construct ${\mathcal X}_{{\mathcal P}{\mathcal N}}^{\prime}$ by applying mixup operator on ${\mathcal X}_{{\mathcal P}}$ and ${\mathcal X}_{{\mathcal N}}$. Similarly, ${\mathcal X}_{{\mathcal U}}^{\prime}$ is formed by mixing unlabeled data ${\mathcal X}_{{\mathcal U}}$. We then combine the consistency loss and the margin loss. More formally, the combined loss $\mathcal{L}$ for our proposed~{\textsc{MixPUL}}~is computed as Equation~(\ref{equ:obj}): \begin{equation}\label{equ:obj} \begin{aligned}\mathcal{L} &=\mathcal{L}_{\mathcal{PN}} + \beta \mathcal{L}_{\mathcal{U}} + \gamma \mathcal{L}_{\mathcal{PU}}. \end{aligned} \end{equation} The first two terms respectively represent the supervised and unsupervised interpolation-based consistency loss and can be written as: \begin{equation}\label{equ:sup-consistencyloss} \begin{aligned} \mathcal{L}_{\mathcal{PN}} &=\frac{1}{\left|\mathcal{X}_\mathcal{PN}^{\prime}\right|} \sum_{{\boldsymbol x}, \hat{y} \in \mathcal{X}_\mathcal{PN}^{\prime}}\left\|\hat{y} - f_{\theta}({\boldsymbol x})\right\|_{2}^{2} \end{aligned} \end{equation} \begin{equation}\label{equ:consistencyloss} \begin{aligned} \mathcal{L}_{\mathcal{U}} &=\frac{1}{\left|\mathcal{X}_\mathcal{U}^{\prime}\right|} \sum_{{\boldsymbol x}, \hat{y} \in \mathcal{X}_\mathcal{U}^{\prime}}\left\|\hat{y} - f_{\theta}({\boldsymbol x})\right\|_{2}^{2} \end{aligned} \end{equation} By imposing consistency loss, it regularizes the network to have strictly linear behavior. Using ``soft'' labels can also alleviate the problem of absence of negative data. Since the consistency terms function as regularizers, we introduces a risk function, i.e., margin loss, between pairs of positive and unlabeled samples, which takes the following form: \begin{equation}\label{equ:pairwiseloss} \begin{aligned} \mathcal{L}_{\mathcal{PU}} &=\frac{1}{\left|\mathcal{X}_{\mathcal{P}}\right| \cdot \left|\mathcal{X}_\mathcal{U}\right|} \sum_{\substack{{\boldsymbol x}_{p} \in \mathcal{X}_{\mathcal{P}}, {\boldsymbol x}_{u} \in {\mathcal X}_{{\mathcal U}}}} \left|f_{\theta}({\boldsymbol x}_u) - f_{\theta}({\boldsymbol x}_p) + \eta \right|_{+}, \end{aligned} \end{equation} where $|z|_{+}$ returns $z$ if $z > 0$, otherwise $0$. $\eta$ is the margin parameter. By imposing $\mathcal{L}_{\mathcal{PU}}$,~{\textsc{MixPUL}}~is desired to produce higher prediction score for positive samples than unlabeled samples. It is shown that $\mathcal{L}_{\mathcal{PU}}$ can be viewed as an estimation of its supervised counterpart. Finally, we use hyperparameters $\beta$ and $\gamma$ to trade-off these three terms. When optimizing Problem~(\ref{equ:obj}), we compute the gradient $\nabla_{\theta} {\mathcal L}$ and update $\theta$ using standard SGD or Adam. Then we update the exponential moving average $\theta^{\prime}$ of network parameter $\theta$ following~\cite{DBLP:conf/nips/TarvainenV17}. \subsection{Theoretical Interpretation of Equation~(\ref{equ:obj})} We further explain our objective function from the perspective of empirical risk minimization. If we regard the consistency loss $\mathcal{L}_{\mathcal{PN}}$ and $\mathcal{L}_{\mathcal{U}}$ in Equation~(\ref{equ:obj}) as regularizations, the last term $\mathcal{L}_{\mathcal{PU}}$ can be interpreted as a risk function. The consistency loss can move the decision boundary to low-density regions of the data distribution~\cite{DBLP:conf/ijcai/VermaLKBL19}. The pairwise ranking loss is designated for PU-AUC risk minimization. Inspired by~\cite{DBLP:conf/aaai/XieL18}, the risk function in AUC optimization from PU data is equivalent to the risk in supervised AUC optimization. Particularly, let $\ell_{01} (z)$ denote the zero-one loss which returns 1 if $z < 0$, 0.5 if $z = 0$, and 0 otherwise. Supposing that unlabeled data is sampled from a mixture of class distribution $P({\boldsymbol x} | y = 0)$ and $P({\boldsymbol x} | y = 1)$ completely at random, we show that PU-AUC risk $R_{\mathrm{PU}}$ is an equivalent estimation of PN-AUC risk $R_{\mathrm{PN}}$ as follows. \begin{equation* \begin{aligned} R_{\mathrm{PU}} =& \underset{\boldsymbol{x} \sim \mathcal{X}_{\mathrm{P}}}{\mathbb{E}}\;\underset{\boldsymbol{x}^{\prime} \sim \mathcal{X}_{\mathrm{U}}}{\mathbb{E}}\ell_{01} \bigl( f(\boldsymbol{x})-f(\boldsymbol{x}^{\prime})\bigr)\\ =& \underset{\boldsymbol{x} \in \mathcal{X}_{\mathrm{P}}}{\mathbb{E}} [\pi \underset{\overline{\boldsymbol{x}} \sim \mathcal{X}_{\mathrm{P}}}{\mathbb{E}}\ell_{01} \bigl( f(\boldsymbol{x})-f(\overline{\boldsymbol{x}})\bigr) \\& + (1 - \pi) \underset{\hat{\boldsymbol{x}} \sim \mathcal{X}_{\mathrm{N}}}{\mathbb{E}}\ell_{01} \bigl( f(\boldsymbol{x})-f(\hat{\boldsymbol{x}})\bigr) ]\\ =& \pi \underset{\boldsymbol{x} \sim \mathcal{X}_{\mathrm{P}}}{\mathbb{E}}\;\underset{\overline{\boldsymbol{x}} \sim \mathcal{X}_{\mathrm{P}}}{\mathbb{E}}\ell_{01} \bigl( f(\boldsymbol{x})-f(\overline{\boldsymbol{x}})\bigr)\\ &+ (1 - \pi) \underset{\boldsymbol{x} \sim \mathcal{X}_{\mathrm{P}}}{\mathbb{E}}\;\underset{\hat{\boldsymbol{x}} \sim \mathcal{X}_{\mathrm{N}}}{\mathbb{E}}\ell_{01} \bigl( f(\boldsymbol{x})-f(\hat{\boldsymbol{x}})\bigr) \end{aligned} \end{equation*} The above equation holds thanks to the linearity of expectation. Note that the first term at the right hand side of the equation is a constant which equals to $\frac{\pi}{2}$. Therefore, it can be omitted in the optimization. Surprisingly, the second term coincides with PN-AUC risk $R_{\mathrm{PN}}$. In other words, we get: \begin{equation*} R_{\mathrm{PU}}= (1 - \pi) R_{\mathrm{PN}} +\frac{\pi}{2} \end{equation*} It is effortless to see that $R_{\mathrm{PU}}$ is a linear transformation of $R_{\mathrm{PN}}$. During training, the zero-one loss is usually replaced with a surrogate loss for the convenience of optimization. In our implementation, we substitute it with margin loss defined in Equation~(\ref{equ:pairwiseloss}) which is enough for AUC risk optimization when it gets minimized. \section{Experiments} To validate the superiority of~{\textsc{MixPUL}}, we conduct experiments on the MNIST\footnote{http://yann.lecun.com/exdb/mnist/}, CIFAR-10\footnote{https://www.cs.toronto.edu/~kriz/cifar.html}, and UCI datasets~\footnote{https://archive.ics.uci.edu/ml/datasets.php}. The comprehensive statistics of used datasets are listed in Table~\ref{exp:dataset}. Notably, the class-ratio of each dataset is the percentage of positive examples among training data. \begin{table}[ht] \centering \begin{tabular}{ L{1.5cm} C{1cm} C{1cm} C{1.2cm} C{1.6cm} } \toprule Dataset & \#Train & \#Test & \#Feature & Class-ratio\\ \midrule ethn & 1,840 & 790 & 30 & 0.50 \\ krvskp & 2,237 & 959 & 36 & 0.49 \\ titanic & 1,540 & 661 & 3 & 0.32 \\ spambase & 3,220 & 1,381 & 57 & 0.40 \\ MNIST & 60,000 & 10,000 & 784 & 0.49 \\ CIFAR-10 & 50,000 & 10,000 & 3,072 & 0.40 \\ \bottomrule \end{tabular} \caption{Dataset statistics}\label{exp:dataset} \end{table} \subsection{Implementation Details} Unless otherwise noted, in all experiments we use the multilayer perceptron. We simply evaluate models using an exponential moving average of their parameters with a decay rate of 0.999. We find in practice that most of~{\textsc{MixPUL}}'s hyperparameters can be fixed and do not need to be tuned on a per-experiment or per-dataset basis. Specifically, for all experiments, we respectively set the hyperparameters $\beta$ and $\gamma$ the objective function of~{\textsc{MixPUL}}~to $1$ and $1$ for simplicity. Further, we only change and $\alpha$ on a per-dataset basis; we found that $\alpha = 1$ are good starting points for tuning. We used the SGD with nesterov momentum optimizer for all of our experiments. For the experiments in Table 1 and Table 2, we run the experiments for 200 epochs. The initial learning rate was set to $10^{-5}$ on CIFAR-10 and $10^{-3}$ for other datasets. The momentum parameter was set to 0.9. We used a $L_2$ regularization coefficient $10^{-4}$ and a batch-size of 128 in our experiments. All the experiments were done with Pytorch\footnote{https://pytorch.org/}. \subsection{Competing Methods} The following methods are compared: \begin{itemize} \item \emph{Supervised}: This method trains a supervised classifier with lightGBM~\cite{DBLP:conf/nips/KeMFWCMYL17}. It treats unlabeled data as negative and uses hyperopt~\cite{komer2014hyperopt} for hyperparameter optimization. \item \emph{WSVM}: The method of~\cite{DBLP:conf/kdd/ElkanN08}. This method treats each unlabeled instance as a combination of positive and negative examples. \item \emph{Ramp}: The method of~\cite{DBLP:conf/nips/PlessisNS14} through optimizing ramp loss. This method is used for comparison with~{\textsc{MixPUL}}~on MNIST dataset. \item \emph{uPU}: The method of~\cite{DBLP:conf/icml/PlessisNS15} using unbiased PU learning risk estimator. \item \emph{nnPU}: The method of~\cite{DBLP:conf/nips/KiryoNPS17} using non-negative unbiased PU learning risk estimator. It is an improved version of uPU which usually overfits because the value of uPU loss can become negative. \item \emph{PNU}: The method of~\cite{Sakai2018PNU_AUC} which explicitly optimizes AUC. \end{itemize} \subsection{Results on MNIST} The model for MNIST is a 3-layer multilayer perceptron (MLP) with ReLU activation function. MNIST has 10 classes originally, and we constructed the ${\mathcal P}$ and ${\mathcal N}$ classes from them as follows: MNIST was preprocessed in such a way that 0 constitute the positive class, while one of \{1, 2, 3, 4, 5, 6, 7, 8, 9\} constitutes the negative class separately in each experimental setting. Subsequently, we randomly sample part of ${\mathcal P}$ which is denoted by ${\mathcal P}^{\prime}$. We set ${\mathcal P} = {\mathcal P} \setminus {\mathcal P}^{\prime}$ and ${\mathcal U} = {\mathcal N} \cup {\mathcal P}^{\prime}$ to form a PU dataset. We compare Ramp~\cite{DBLP:conf/nips/PlessisNS14} which optimizes ramp loss calculated on positive and unlabeled data with the knowledge of true class-prior. The comparison results are reported in Table~\ref{exp:mnist-error}. It is noted that~{\textsc{MixPUL}}~achieves lowest misclassification rate in comparison with Ramp~\cite{DBLP:conf/nips/PlessisNS14} in most settings we studied. Specifically,~{\textsc{MixPUL}}~significantly reduces the classification error rate from 5.48 to 0.33 in 0 vs. 1 task and from 22.58 to 3.51 in 0 vs. 6 task. It indicates that the model initialization for~{\textsc{MixPUL}}~produces considerably accurate ``soft'' labels facilitating the consistency loss. In summary, the empirical studies demonstrate that~{\textsc{MixPUL}}~is insensitive to class-prior and consistently outperforms Ramp which is one of the representative approaches based on unbiased risk minimization. \begin{table}[tb] \centering \ra{1.1} \rowcolors{1}{white}{gray!15} \begin{tabular}{l C{2cm} |C{1cm} C{1cm} C{1cm} } \toprule \rule{0pt}{2.2ex} Setting & Method & 1,200 & 2,400 & 3,600 \\ \midrule \rule{0pt}{2.2ex} \cellcolor{white} & Ramp & 3.36 & 4.85 & 5.48 \\ \multirow{-2}{*}{0 vs. 1}\rule{0pt}{2.2ex} \cellcolor{white} &{\textsc{MixPUL}} & \bf 0.24 & \bf 0.33 & \bf 0.33 \\ \hline \rule{0pt}{2.2ex} \cellcolor{white} & Ramp & 5.15 & 6.96& 7.22 \\ \multirow{-2}{*}{0 vs. 2}\rule{0pt}{2.2ex} \cellcolor{white} &{\textsc{MixPUL}} &\bf 4.57 & \bf 2.83 & \bf 2.14 \\ \hline \rule{0pt}{2.2ex} \cellcolor{white} & Ramp & 3.49 & 4.72 & 5.02 \\ \multirow{-2}{*}{0 vs. 3}\rule{0pt}{2.2ex} \cellcolor{white} &{\textsc{MixPUL}} &\bf 3.02 & \bf 2.41 & \bf 2.46 \\ \hline \rule{0pt}{2.2ex} \cellcolor{white} & Ramp & 1.68& 2.05 & 2.21 \\ \multirow{-2}{*}{0 vs. 4}\rule{0pt}{2.2ex} \cellcolor{white} &{\textsc{MixPUL}} & \bf 0.76 & \bf 0.66 & \bf 0.46 \\ \hline \rule{0pt}{2.2ex} \cellcolor{white} & Ramp & 5.21 & 7.22 & \bf 7.46 \\ \multirow{-2}{*}{0 vs. 5}\rule{0pt}{2.2ex} \cellcolor{white} &{\textsc{MixPUL}} & \bf 1.60 & \bf 3.63 & 9.62 \\ \hline \rule{0pt}{2.2ex} \cellcolor{white} & Ramp & 11.47 & 19.87 & 22.58 \\ \multirow{-2}{*}{0 vs. 6} \rule{0pt}{2.2ex} \cellcolor{white} &{\textsc{MixPUL}} &\bf 8.57 & \bf 5.31 & \bf 3.51 \\ \hline \rule{0pt}{2.2ex} \cellcolor{white} & Ramp & 1.89 & 2.55 & 2.64 \\ \multirow{-2}{*}{0 vs. 7}\rule{0pt}{2.2ex} \cellcolor{white} &{\textsc{MixPUL}} & \bf 1.64 & \bf 1.20 & \bf 1.15 \\ \hline \rule{0pt}{2.2ex} \cellcolor{white} & Ramp & 3.98 & 4.81 & 4.75 \\ \multirow{-2}{*}{0 vs. 8}\rule{0pt}{2.2ex} \cellcolor{white} &{\textsc{MixPUL}} &\bf 3.58 & \bf 2.81 & \bf 2.41 \\ \hline \rule{0pt}{2.2ex} \cellcolor{white} & Ramp & 1.22& 1.60& \bf 1.73 \\ \multirow{-2}{*}{0 vs. 9}\rule{0pt}{2.2ex} \cellcolor{white} &{\textsc{MixPUL}} & \bf 1.21 & \bf 0.96 & 3.02 \\ \bottomrule \end{tabular} \caption{Misclassification rate (in percent) of~{\textsc{MixPUL}}~and Ramp on MNIST dataset. We set the amount of positive data $|{\mathcal P}|$ from $\{1200, 2400, 3600\}$. The best results are in bold.}\label{exp:mnist-error} \end{table} \subsection{Results on CIFAR-10} We compare our method with state-of-the-art PU learning algorithms on CIFAR-10 dataset. We use the same architecture for all methods as specified in~\cite{DBLP:conf/nips/KiryoNPS17}. CIFAR-10 has 10 classes originally, and we construct the \emph{positive} class and \emph{negative} class as follows. The \emph{positive} class is formed by ``airplane'', ``automobile'', ``ship'', and ``truck'', and the \emph{negative} class is formed by ``bird'', ``cat'', ``deer'', ``dog'', ``frog'', and ``horse''. The results are reported in Table~\ref{cifar10-comparison}. We find that \emph{uPU} is very prone to overfitting and we therefore use a small number of epoch (less than 10). When only 100 positive examples are available, both \emph{nnPU} and \emph{uPU} tend to treat all unlabeled data as negative, which prevent the model from training. Our consistency-regularized model achieve the lowest (best) classification error in 5 out of 6 settings. The comparison result is especially encouraging, considering that \emph{nnPU} and \emph{uPU} use the knowledge of class-prior. \begin{table}[htbp] \small \ra{1.3} \centering \begin{tabular}{l|c|c|c|c|c|c} Method & 100 & 500 & 1k & 2k & 4k & 10k \\ \hline nnPU & 40.00 & 15.55 & 13.32 & 11.32 & 9.90 & \bf8.87\\ \hline uPU & 40.00 & 26.01 & 19.95 & 14.38 & 12.08 & 9.90 \\ \hline {\textsc{MixPUL}} & \bf22.63 & \bf14.00 & \bf12.21 & \bf11.10 &\bf 9.77 & 8.88 \\ \end{tabular} \caption{Error rate on \emph{CIFAR-10} dataset with varying number of positively labeled data.} \label{cifar10-comparison} \end{table} \begin{table*}[!t] \centering \rowcolors{1}{white}{gray!15} \begin{tabular}{l C{1.5cm} |C{2cm} C{2cm} C{2cm} C{2cm} C{2cm} } \toprule \rule{0pt}{2.0ex}Dataset & Method & 0.01 & 0.05 & 0.1 & 0.2 & 0.4 \\ \midrule \rule{0pt}{2.0ex} \cellcolor{white} & Supervised & 0.50$\pm$0.00 & 0.69$\pm$0.10 & 0.89$\pm$0.02 & 0.92$\pm$0.01 & 0.96$\pm$0.00 \\ \rule{0pt}{2.0ex} \cellcolor{white} &WSVM & 0.56$\pm$0.20 & \bf0.96$\pm$0.01 & \bf0.98$\pm$0.00 & \bf0.99$\pm$0.00 & \bf0.99$\pm$0.00 \\ \rule{0pt}{2.0ex} \cellcolor{white} & uPU & 0.66$\pm$0.07 & 0.84$\pm$0.04 & 0.94$\pm$0.01 & 0.96$\pm$0.00 & 0.97$\pm$0.00 \\ \rule{0pt}{2.0ex} \cellcolor{white} & nnPU & 0.63$\pm$0.07 & 0.80$\pm$0.09 & 0.82$\pm$0.03 & 0.86$\pm$0.03 & 0.86$\pm$0.01 \\ \rule{0pt}{2.0ex} \cellcolor{white} & PNU & 0.71$\pm$0.04 & 0.92$\pm$0.01 & 0.94$\pm$0.01 & 0.95$\pm$0.01 & 0.97$\pm$0.00 \\ \multirow{-7}{*}{ethn}\rule{0pt}{2.0ex} \cellcolor{white} & {\textsc{MixPUL}} & \bf 0.73$\pm$0.04 & 0.92$\pm$0.01 & 0.97$\pm$0.00 & 0.98$\pm$0.00 & 0.94$\pm$0.00 \\ \hline \rule{0pt}{2.0ex} \cellcolor{white} & Supervised & 0.50$\pm$0.00 & 0.81$\pm$0.06 & 0.87$\pm$0.07 & \bf0.97$\pm$0.01 & \bf0.98$\pm$0.00 \\ \rule{0pt}{2.0ex} \cellcolor{white} &WSVM & 0.61$\pm$0.07 & 0.77$\pm$0.06 & 0.81$\pm$0.05 & 0.85$\pm$0.04 & 0.88$\pm$0.05 \\ \rule{0pt}{2.0ex} \cellcolor{white} & uPU & 0.72$\pm$0.08 & 0.85$\pm$0.06 & 0.89$\pm$0.04 & 0.95$\pm$0.02 & 0.96$\pm$0.02 \\ \rule{0pt}{2.0ex} \cellcolor{white} & nnPU & 0.62$\pm$0.09 & 0.78$\pm$0.03 & 0.82$\pm$0.06 & 0.84$\pm$0.02 & 0.88$\pm$0.04 \\ \rule{0pt}{2.0ex} \cellcolor{white} & PNU & \bf0.72$\pm$0.07 & 0.88$\pm$0.03 & 0.91$\pm$0.03 & 0.95$\pm$0.09 & 0.96$\pm$0.00 \\ \multirow{-7}{*}{krvskp}\rule{0pt}{2.0ex} \cellcolor{white} & {\textsc{MixPUL}} & 0.70$\pm$0.08 & \bf0.90$\pm$0.03 & \bf0.93$\pm$0.02 & 0.96$\pm$0.00 & 0.97$\pm$0.00 \\ \hline \rule{0pt}{2.0ex} \cellcolor{white} & Supervised & 0.50$\pm$0.00 & 0.50$\pm$0.00 & 0.69$\pm$0.02 & 0.72$\pm$0.01 & \bf0.71$\pm$0.00 \\ \rule{0pt}{2.0ex} \cellcolor{white} &WSVM & 0.35$\pm$0.04 & 0.68$\pm$0.05 & \bf0.73$\pm$0.01 & \bf0.73$\pm$0.02 & 0.71$\pm$0.02 \\ \rule{0pt}{2.0ex} \cellcolor{white} & uPU & 0.64$\pm$0.09 & \bf0.70$\pm$0.01 & 0.71$\pm$0.00 & 0.71$\pm$0.00 & \bf0.71$\pm$0.00 \\ \rule{0pt}{2.0ex} \cellcolor{white} & nnPU & 0.63$\pm$0.05 & 0.70$\pm$0.03 & 0.70$\pm$0.02 & 0.71$\pm$0.01 & 0.71$\pm$0.02 \\ \rule{0pt}{2.0ex} \cellcolor{white} & PNU & 0.63$\pm$0.08 & 0.69$\pm$0.00 & 0.70$\pm$0.02 & 0.70$\pm$0.00 & 0.70$\pm$0.00 \\ \multirow{-7}{*}{titanic}\rule{0pt}{2.0ex} \cellcolor{white} & {\textsc{MixPUL}} & \bf 0.67$\pm$0.01 & 0.68$\pm$0.01 & 0.70$\pm$0.01 & 0.71$\pm$0.01 & \bf0.71$\pm$0.00 \\ \hline \rule{0pt}{2.0ex} \cellcolor{white} & Supervised & 0.50$\pm$0.00 & 0.89$\pm$0.02 & 0.90$\pm$0.01 & 0.93$\pm$0.02 & 0.95$\pm$0.01\\ \rule{0pt}{2.0ex} \cellcolor{white} &WSVM & 0.36$\pm$0.01 & 0.58$\pm$0.00 & 0.72$\pm$0.00 & 0.79$\pm$0.00 & 0.85$\pm$0.00 \\ \rule{0pt}{2.0ex} \cellcolor{white} & uPU & 0.87$\pm$0.05 & 0.91$\pm$0.01 & 0.93$\pm$0.00 & 0.93$\pm$0.01 & 0.94$\pm$0.00 \\ \rule{0pt}{2.0ex} \cellcolor{white} & nnPU &0.77$\pm$0.07 & 0.87$\pm$0.01 & 0.90$\pm$0.00 & 0.91$\pm$0.01 & 0.92$\pm$0.00 \\ \rule{0pt}{2.0ex} \cellcolor{white} & PNU &0.76$\pm$0.07 & 0.87$\pm$0.01 & 0.91$\pm$0.01 & 0.93$\pm$0.00 & 0.94$\pm$0.00 \\ \multirow{-7}{*}{spambase}\rule{0pt}{2.0ex} \cellcolor{white} & {\textsc{MixPUL}} &\bf 0.89$\pm$0.01 & \bf0.92$\pm$0.01 & \bf0.94$\pm$0.01 & \bf0.94$\pm$0.01 & \bf0.96$\pm$0.00 \\ \bottomrule \end{tabular} \caption{Experimental comparisons on benchmark datasets with varying class-frequency. On each dataset, 10 test runs were conducted. The average AUC and standard deviation are presented. The true value of class-prior is used in uPU and nnPU. The best results in each setting are in bold.~{\textsc{MixPUL}}~(ours) achieves competitive performance.}\label{exp:uci-all} \end{table*} \subsection{Results on UCI Datasets} To simulate PU learning problems in the wild, we construct PU data with varying class-frequency $c$. More specifically, we run all competing methods by setting class-frequency $c$ to $c^\prime \in \{0.01, 0.05, 0.1, 0.2, 0.4\}$ through randomly downsampling positive examples and appending them into the unlabeled set ${\mathcal U}$. For each $c'$, we repeat the experiment $10$ times and report the average performance. The comparison results in terms of AUC are shown in Table~\ref{exp:uci-all}, where means and standard deviations of testing performance based on $10$ random samplings are reported. It is effortless to see that the supervised baseline performs dreadfully with a modest set of positive examples. When more and more positive examples are observed, it achieves competing results because sampled unlabeled examples are becoming more likely to be negative. This validates that the supervised baseline is considerably good and should be compared in PU learning literature. We implement WSVM using Gaussian kernel and it fits the data very well in most cases except when the number of positive examples is extremely limited. Since deep neural networks are used in nnPU, it is no surprise that its performance on small datasets (e.g., ethn, krvskp) is usually worse than other algorithms owing to the lack of labeled examples. It is interesting to observe that the AUC score of comparison methods is approaching 1.0 even when $c = 0.01$ on \emph{spambase}, which indicates that this dataset is relatively easier to deal with. It is noteworthy that~{\textsc{MixPUL}}~is able to achieve superior or comparable results with uPU and nnPU even though they use the true value of class-prior $\pi$ especially when $|{\mathcal P}|$ is small. In summary, our~{\textsc{MixPUL}}~can readily adapted across many practical tasks without the knowledge of class-prior and assumptions over the data distribution. \subsection{Ablation Studies and Discussion} In the following, we provide an analysis of the effects of different parts of objective function and RN mining methods. \begin{table}[htbp] \small \ra{1.3} \centering \begin{tabular}{l|c|c|c|c} Method & 5 & 25 & 50 & 100 \\ \hline Rand & \bf0.67$\pm$0.01 & \bf0.68$\pm$0.01 & \bf0.70$\pm$0.01 & \bf0.71$\pm$0.01\\ \hline Dist & 0.48$\pm$0.14 & 0.53$\pm$0.16 & 0.66$\pm$0.01 & 0.47$\pm$0.15 \\ \hline NTC & 0.56$\pm$0.11 & 0.68$\pm$0.02 &\bf0.70$\pm$0.01 & 0.69$\pm$0.00 \\ \end{tabular} \caption{A comparison between negative mining methods on \emph{titanic} dataset with different amount of positive data $|{\mathcal P}| \in \{5, 25, 50, 100\}$.}\label{rn-comparison} \end{table} \subsubsection{How Does the Type of RN Mining Affect Results?} We report numerical results of employing three different reliable negative mining methods by fixing other components of the networks in Table~\ref{rn-comparison}. Euclidean distance is used in \emph{Dist} method. For \emph{NTC} method, we train a random forest classifier. It is effortless to observe that \emph{Dist} has the worst performance. This indicates that it is unsafe to use distance-based classifiers for unknown data distribution. Therefore, we use \emph{Rand} in all experiments for its observed good performance. We also tried to train the networks without RN examples. Since only positive examples are fed, the networks suffer from overfitting after a few epochs. \subsubsection{How Much Does Unsupervised Mixup Matter By Itself?} We study the effect of mixup by training the networks with and without unsupervised interpolation-based consistency loss on one of the image datasets, \emph{ethn}. As shown in Figure~\ref{exp:mixup}, the vertical dashed line indicates the iteration where interpolation training begins. The red and blue lines respectively demonstrate the classification error with and without unsupervised mixup. If we apply the mixup operator on unlabeled data, the misclassification rate initially increases very fast because augmented data is generated which the networks have never seen. After a few iterations, the error rate decreases to less than 10\% which is far smaller than the number without using unsupervised mixup. The results demonstrate the effectiveness of mixup and provide another way of employing unlabeled data for PU learning. \begin{figure}[ht] \centering \begin{subfigure}[tb]{0.48\linewidth}\centering \includegraphics[width=1\linewidth]{figures/mixup_ablation} \caption{Ablations on mixup}\label{exp:mixup} \end{subfigure} \begin{subfigure}[tb]{0.48\linewidth}\centering \includegraphics[width=1\linewidth]{figures/pairwise_ranking_ablation} \caption{Ablations on margin loss}\label{exp:pairwise} \end{subfigure} \caption{Ablation studies on unsupervised mixup (left) and margin loss (right).} \end{figure} \subsubsection{How Does Margin Loss Affect Results?} In our objective function, we use margin loss between positive and unlabeled example pairs guiding the model to give higher prediction scores for observed positive examples than unlabeled ones. As shown in Figure~\ref{exp:pairwise}, it results in faster convergence by incorporating margin loss. We also observe that the model has a more stable performance when the mixup is applied as illustrated by the vertical dashed line. The results coincide with our theoretical analysis that the margin loss leads to AUC risk minimization. In a brief summary, we provide an analysis of the effects of mixup, margin loss, and the negative example mining methods for researchers and practitioners. We find that mixup is more effective on image datasets than other types of data and it also provides a new way of using unlabeled instances for PU learning. Further, by incorporating margin loss, it leads to faster convergence for the networks and makes the model performs more stably when applying mixup. Finally, randomly downsampling unlabeled data as negative is an effective RN mining method for PU learning. \section{Conclusion} In this work, we introduce~{\textsc{MixPUL}}~which applies interpolation-based consistency regularization to PU learning.~{\textsc{MixPUL}}~has two advantages over previous PU learning approaches. First, it does not require the knowledge of class-prior, which otherwise hinders the applicability of the algorithm. Second, through extensive experiments, we find that~{\textsc{MixPUL}}~exhibited significantly performance improvements over prior state of the art. Besides, we empirically observe that the proposed negative mining techniques are considerably effective, without which the model corrupts and is unable to incorporate consistency regularization. Specifically, different negative example mining techniques are further investigated and we find the randomized method work very well. We also conduct thorough ablation studies on the consistency regularization and the margin loss. We hope that the proposed consistency regularization will become a standard element in PU learning, and that it will make things easier and simpler for researchers and practitioners. \bibliographystyle{unsrt} \section{Introduction} \lipsum[2] \lipsum[3] \section{Headings: first level} \label{sec:headings} \lipsum[4] See Section \ref{sec:headings}. \subsection{Headings: second level} \lipsum[5] \begin{equation} \xi _{ij}(t)=P(x_{t}=i,x_{t+1}=j|y,v,w;\theta)= {\frac {\alpha _{i}(t)a^{w_t}_{ij}\beta _{j}(t+1)b^{v_{t+1}}_{j}(y_{t+1})}{\sum _{i=1}^{N} \sum _{j=1}^{N} \alpha _{i}(t)a^{w_t}_{ij}\beta _{j}(t+1)b^{v_{t+1}}_{j}(y_{t+1})}} \end{equation} \subsubsection{Headings: third level} \lipsum[6] \paragraph{Paragraph} \lipsum[7] \section{Examples of citations, figures, tables, references} \label{sec:others} \lipsum[8] \cite{kour2014real,kour2014fast} and see \cite{hadash2018estimate}. 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} \begin{center} \url{https://www.ctan.org/pkg/booktabs} \end{center} \subsection{Figures} \lipsum[10] See Figure \ref{fig:fig1}. Here is how you add footnotes. \footnote{Sample of the first footnote.} \lipsum[11] \begin{figure} \centering \fbox{\rule[-.5cm]{4cm}{4cm} \rule[-.5cm]{4cm}{0cm}} \caption{Sample figure caption.} \label{fig:fig1} \end{figure} \subsection{Tables} \lipsum[12] See awesome Table~\ref{tab:table}. \begin{table} \caption{Sample table title} \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} \label{tab:table} \end{table} \subsection{Lists} \begin{itemize} \item Lorem ipsum dolor sit amet \item consectetur adipiscing elit. \item Aliquam dignissim blandit est, in dictum tortor gravida eget. In ac rutrum magna. \end{itemize} \bibliographystyle{unsrt}
{'timestamp': '2020-04-21T02:29:31', 'yymm': '2004', 'arxiv_id': '2004.09388', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09388'}
arxiv
\section{Introduction} Vehicle re-identification aims to match vehicle appearances across multiple cameras. As the widely deployment of cameras throughout the cities’ roads, the task has more and more applications in smart cities, and also attracts more and more interest in the computer vision community [1, 2, 3]. Vehicle re-identification benefits from the progresses of person re-identification [4, 5, 6], network architectures [7, 8, 9], training loss [10, 11], data augmentation [12, 13]. But vehicle re-identification still has many challenges, including intra-class variations for vehicle-model, viewpoints, occlusion, motion blur [14]. From our observations, vehicle re-identification task suffers from the similar car shape and background. Images captured by camera share the same background, and orientation is a key-component of car shape. Thus, It is reasonable to take orientation and camera into account as well as vehicle IDs. Based on the idea, we propose an mechanism named VOC-ReID to address the bias incurred by background and car shape. Our major contributions are threefold: \begin{itemize} \item We argue that the similarity of background can be interpreted as camera re-identification and similarity of shape interpreted as orientation re-identification. \item To reduce the bias of background and shape, we propose VOC-ReID approach which takes the triplet vehicle-orientation- camera as a whole. To our best knowledge, we are the first to joint vehicle, orientation and camera information in vehicle re-identification task. \item Our approach achieves the second place in vehicle re-identification track at the NVIDIA AI City Challenge 2020 without using any extra data and annotations. It also out-performances the state-of-the-art methods on VeRi776 dataset [2]. \end{itemize} \begin{figure*}[t] \begin{center} \includegraphics[width=1\linewidth]{images/architect.png} \end{center} \caption{the overall design of the training framework: RECT-Net, which stands for ResNet backbone, GeM pooling, Circle loss [8], and Triplet loss.} \label{fig:architect} \end{figure*} \section{Related Works} Recently, deep learning based vehicle Re-ID approaches outperform all previous baselines using handcrafted features. To learn a discriminative representation, a large-scale annotated data is needed. Liu et al. [2, 15] introduces a high-quality multi-view (VeRi776) dataset [2], which is the first large-scale benchmark for vehicle ReID. An effective strategy to learn the discriminative representation is metric learning. Because the success of triplet embedding in person ReID field [10], Bai et al. [16] introduces Group-Sensitive triplet embedding to better model the intra-class variance. And Kumar et al. [14] provides an extensive evaluation of triplet loss applied to vehicle re-identification and study the sampling approaches for mining informative samples. On the other hand, some methods focus on exploiting viewpoint-invariant features, e.g. 2D key-points features. The approach by Tang et al. [18] that embeds key-points, heatmaps and segments from pose estimation into the multi-task learning pipeline for vehicle ReID, which guides the network to pay attention to viewpoint-related information. At the same time, [17, 18] use the graphic engine to generate the synthetic data with 2D key-points, colors and models, etc.. Similarly, Zhou et al. [19] uses a generative adversarial network to generate synthesize vehicle images with diverse orientation and appearance variations. However, these works did not take into account the bias of similar shapes and backgrounds. \section{Proposed Approach} In section 3.1, we introduce our baseline architecture using bag of tricks and data augmentation, which is a basic unit in section 3.2. Then the triplet re-identification system, abbreviated as VOC-ReID, adopting three units is described in section 3.2. In section 3.3, we introduce the training and post-processing tricks. \subsection{Training Network} Baseline architecture is shown in Figure \ref{fig:architect}. In the following paragraph, we use an abbreviation RECT-Net to represent it, which stands for the combination of ResNet [7, 8, 9], GeM pooling [23], Circle loss [11], and Triplet loss [10]. Data augmentation is also introduced in this section, including weakly supervised detection [12, 13], random erasing [24], color jittering and other methods. {\bf ResNet backbone.} We use ResNet [7] with IBN [9] structure as feature extractor, which shows potentials in resisting viewpoint and illumination changes. {\bf GeM: Generalized-mean Pooling.} Global average pooling is widely-used in classification tasks, but it is not a good choice for fine-grained instance retrieval tasks, just like vehicle re-id. In [23], generalized-mean (GeM) pooling is proposed as: \begin{equation} f^{(g)} = \left[f_1^{(g)}\dots f_k^{(g)}\dots f_K^{(g)}\right]^T, f_k^{(g)}=\left[\frac{1}{|X|_k }\sum_{x\in X}x^p\right] \end{equation} Average pooling and max pooling are all special cases of GeM pooling, it degrades to max pooling when $p\rightarrow \infty$ and degrades to average pooling when $p=1$. GeM pooling get superior performance than global average pooling in our vehicle re-id experiments. {\bf Loss: Circle Loss and Triplet Loss.} We train our networks with two types of losses: Circle loss [11] and Triplet loss [10]. The Circle loss has a unified formula for two elemental deep feature learning approaches, i.e., learning with class-level labels and pair-wise labels [11]. The hyper-parameters of Circle loss are decided after several experiments. The scale factor is 64 and the relaxation factor is 0.35. Triplet loss is widely used in re-id tasks. In [10], the batch-hard triplet loss selects only the most difficult positive and negative samples. The hyper-parameter of batch-hard triplet loss, the margin, is 0.3. At last, we train our networks with the fusion of Circle loss and Triplet loss, with the coefficients of 1:1. {\bf Data Augmentation: Weakly Supervised Detection.} Data augmentation is widely used to improve the models’ accuracy and avoid overfitting. One important data augmentation works in our approach is weakly supervised detection augmentation. Inspired by [12, 13], we train an initial vehicle ReID model to get heatmap response of each image and setting a threshold to get the bounding box larger than it. Compared with supervised detection methods, it produces a more tightly cropping of vehicle, focusing on the attentional areas of Re-ID model. After weakly supervised detection, we get a cropped copy of both train and test set. Train set is used alongside with original images. So after applying weakly supervised data augmentation, our dataset get doubled. Other commonly used data augmentation methods are applied in our training stage, such as random erasing [24], and color jitter, etc. \subsection{VOC-ReID} Similar background and shape pose sever bias on final similarity matrix. Thus, similarity contributed by fine-grained information would be dominated by background and shape similarity. To reduce the bias so that the model can focus on fine-grained details, we propose the triplet vehicle-orientation-camera re-identification, abbreviated as VOC-ReID. As illustrated in Figure \ref{fig:voc}, the VOC-ReID system extracts the vehicle feature distance matrix, orientation feature, distance matrix, camera feature distance matrix separately, and then fuses them to one distance matrix. Compared with learning vehicle IDs alone, vehicle-orientation-camera triplet can boost the performance significantly. \begin{figure}[t] \begin{center} \includegraphics[width=1\linewidth]{images/voc.png} \end{center} \caption{the overall framework of the proposed VOC-ReID system. It includes three parts: Vehicle RECT-Net, output the vehicle similarity; Orientation RECT-Net, output the orientation similarity; Camera RECT-Net, output the camera similarity. At last, we use a straight-forward distance fusion method to fuse these 3 outputs together to get the last output distance matrix.} \label{fig:voc} \end{figure} {\bf Vehicle ReID.} In vehicle ReID part, vehicle ID is used as the ground-truth to optimize the distances between vehicles. The purpose of Vehicle ReID is to get a compact embedding $f_{v}(x_i)$. Cosine distance between image $x_i$ and $x_j$ can be computed by the following equation: \begin{equation} {D_v (x_i, x_j)}=\frac{f_v(x_i) \cdot f_v(x_j)}{|f_v(x_i)| \cdot |f_v(x_j)|} \end{equation} Although our baseline architecture RECT-Net show superior performance on both person and vehicle Re-ID datasets, it still can’t handle some typical failure cases, shown in Figure \ref{fig:failure}. Those failure cases all have similar orientation or background. That phenomenon encourages us to design another two networks to learn the orientation similarity and background similarity. \begin{figure}[t] \begin{center} \includegraphics[width=1\linewidth]{images/failure.png} \end{center} \caption{Some false predicts by Vehicle RECT-Net (Red rectangle means the false predicts). As row a and b show: Vehicle RECT-Net usually predicts the vehicle with the similar orientation as the same vehicle ID. As row c and d show: Vehicle RECT-Net usually predicts the vehicle with the similar background as the same vehicle ID. } \label{fig:failure} \end{figure} {\bf Orientation ReID.} In this section, we reform the learning of shape similarity as an orientation Re-ID problem. It’s hard to define shape similarity directly. A precise sign of shape is vehicle key-points [25], but it’s confusing to define pose similarity. So, finally we choose orientation as a rough but stable representation of shape. After replacing vehicle IDs to orientation ID, we can practice an orientation ReID process, similar to orientation estimation. However, rather than outputting a regression result or a classified direction, orientation ReID outputs an embedding that can be used to calculate orientation similarity. In this work, we use a completely same architecture RECT-Net to learn orientation similarity. To train the Orientation RECT-Net, we need to get data with orientation labels. Fortunately, synthetic data VehicleX [8] has orientation label available, avoiding manually labeling work. In more detail, we quantize the angle (0 - 360) into 36 bins, each bin is treated as an ID. After preparing the training data set, we can train the Orientation RECT-Net on VehicleX dataset and calculate orientation similarity on CityFlow. There is domain gap between CityFlow and VehicleX, so the predicted orientation accuracy can’t be guaranteed. However, we don’t need a precise prediction of orientation, a rough orientation similarity is qualified to reduce similarity bias caused by shape. We get the orientation feature $f_o(x_i)$ from RECT-Net, and then orientation distance between the vehicle image $x_i$ and $x_j$ can be computed: \begin{equation} D_o (x_i, x_j)=\frac{f_o(x_i) \cdot f_o(x_j)}{|f_o(x_i)| \cdot |f_o(x_j)|} \end{equation} {\bf Camera ReID.} In this section we reform the learning of background similarity as a camera ReID problem. According to prior knowledge, images captured by the same camera share similar background, as well as image style and illumination condition. Thus, camera ID is a reliable label to indicate background variances. Nearly every Re-ID dataset provide a camera ID as well as vehicle or person ID, but few works have utilized it properly. Let’s define two vehicle images as $(x_i, x_j), x_i\in (c_a), x_j\in (c_b), a, b \in[0, N]$, $c_a$ means the camera $a$, then the similarity of background can be roughly represented by camera. As the training set already has the camera ID label, we can simply use the same network architecture of Vehicle RECT-Net to train the Camera ReID. Then we can extract the camera-aware features $f_c(x_i)$, and the camera-aware distance between the vehicle image and can be computed: \begin{equation} D_c (x_i, x_j)=\frac{f_c(x_i) \cdot f_c(x_j)}{|f_c(x_i)| \cdot |f_c(x_j)|} \end{equation} Some previous work also try to explore the usage of camera ID, such as He et al. [26] use the camera ID information as a prior information, they assume that if two vehicle images are from the same camera, they should not be the same vehicle, that means: \begin{equation} D(x_i, x_j)= \begin{cases} 0, \quad &c_a =c_b\\ 1, \quad &c_a \neq c_b\\ \end{cases} \end{equation} Such rule is a hard discrimination, it may cause other problem and the threshold varies among datasets, which means it should be carefully adjusted. Our approach considers camera information as a complement to the overall information, and it is more reasonable. As far as we know, it is the first time to utilize the camera ID information in training and infer procedure. {\bf VOC Fusion.} As the figure 4 shows, in the test phase, according to the equations (1) (2) (3), the VOC-ReID system will output the vehicle ID distance matrix, orientation distance matrix, camera distance matrix, we need to fuse these three distance matrix to be one distance matrix. The fusion distance matrix can be expressed as following: \begin{equation} D(x_i, x_j) = D_v(x_i, x_j) - \lambda _1 D_o(x_i, x_j) - \lambda _2 D_c(x_i, x_j) \end{equation} As analyzed in the section 3.2.1, it should decrease the influence of the similar orientation and background, and the three distances matrix are all cosine distance, so we can directly minus the orientation distance and camera distance. In experiment, we set $\lambda _1 = \lambda _2 = 0.1$. \subsection{Training and Testing Tricks} {\bf Cosine learning rate decay. } In training phase, we adopt cosine annealing scheduler to decay learning rate. According to the experiments conducted by He et al. [27], multi-step scheduler inferior performance compared with cosine annealing. Cosine decay starts to decay the learning since the beginning but remains large until step decay reduces the learning rate by 10x, which can potentially improve the training progress. {\bf Image to track.} In the test phase, the traditional solution is to compute the distance between query images and gallery images. As the images in one track are the same vehicle, and one track covers multiple similar images but may have different perspective, so we can replace the features of each gallery image with the average features of the track, which can be regarded as an improvement from image-to-image to image-to-track way. {\bf Re-rank.} When get the fusion distance matrix, then we adopt the re-ranking method [28] to update the final result, which will significantly improve the mAP. \section{Experiments} \subsection{Implementation Details} All input images are resized to 320x320 and then applied with a series of data augmentation methods in training, including random horizontal flip, random crop, color jitter and random erase. We also try other data augmentation methods like random patch, augmix [29], random rotate/scale and random blur, but all of them turn out not working well on this task. To meet the requirement of pair-wise loss, data is sampled by m-per-class sampler with parameter P and K, which denote numbers of classes and numbers of instances per class in a mini-batch. In our experiments they are set to P=4, K=16. In train process, ResNet50-IBN-a is used as backbone for both vehicle and orientation/camera ReID. All models are trained on a single GTX-2080-Ti GPU in total 12 epochs, with feature layers frozen in the first epoch, which works as a warm-up strategy. Cosine annealing scheduler is adopted to decay initial learning rate from 3.5e-4 to7.7e-7. \subsection{Dataset} There are totally 666 IDs and 56277 images in CityFlow. 36935 images with 333 IDs are used for training and the others for testing. A new rule in AI City Challenge 2020 that prohibits using extra data, such as VeRi776 [2] and VehicleID[30]. To overcome the shortness of lacking data, the official committees provide a synthetic vehicle ReID dataset named VehicleX [17]. It contains 1362 IDs and 192150 images generated by Unity engine, with high orientation and light variance. We only use the trainset of CityFlow and the whole synthetic dataset VehicleX. \subsection{Ablation Study} In this section, we split the trainset of CityFlow into two parts, the first 95 IDs are used as validation set while the rest for training. {\bf Influences of Losses.} Cross Entropy loss combined with Triplet loss are widely used as baseline in person and vehicle re-identification. Recent years tremendous loss functions emerge in face recognition and metric learning domains, lots of them stand the test of time and finally prove to be quite solid. In our experiments, We compare Cross Entropy (CE) with other popular classification learning losses, such as Arcface, Cosface and Circle loss, in Table \ref{tab:loss}. It shows that Circle loss alongside with Triplet loss achieves the best result with large margin just as the author claims. \begin{table} \begin{center} \begin{tabular}{|c|cc|} \hline loss & mAP & Rank1\\ \hline\hline CrossEntropy + Triplet & 21.6\% & 42.1\% \\ Arcface + Triplet & 26.2\% &46.7\%\\ Cosface + Triplet & 26.8\% &48.3\%\\ Circle + Triplet & 29.7\% &50.8\%\\ \hline \end{tabular} \end{center} \caption{Different losses on CityFlow validation set.} \label{tab:loss} \end{table} {\bf Influences of Data.} PAMTRI [18] and VehicleX have fully explored the proper usage of synthetic data in Vehicle ReID. In Table \ref{tab:data}., Real denotes real dataset namely trainminusval set of CityFlow, VehicleX denotes synthetic dataset VehicleX. Aug denotes weakly supervised detection augmentation described in section 3.1. As we can see, by adding synthetic dataset VehicleX, our method achieves a much better performance. On the other hand, weakly supervised data augmentation brings almost 5\% gains because of relatively loose cropping in CityFlow. The scale factor of vehicle and background would obviously deteriorate the performance. \begin{table} \begin{center} \begin{tabular}{|c|cc|} \hline Data & mAP & Rank1\\ \hline\hline Real & 29.7\% & 50.8\% \\ Real + VehicleX & 39.5\% &64.0\%\\ Real + Aug + VehicleX & 44.4\% &65.3\%\\ \hline \end{tabular} \end{center} \caption{Different losses on CityFlow validation set.} \label{tab:data} \end{table} {\bf Influences of VOC fusion.} To explore the effectiveness of VOC-ReID mechanism, we apply orientation and camera similarity penalty respectively. In Table \ref{tab:voc}. RSA denotes Real data, Synthetic data and weakly supervised augmentation, orientation denotes orientation aware ReID and camera denotes camera aware ReID. After applying orientation and camera similarity penalty, rank1 increases 10\%, from 65.3\% to 75.5\%. \begin{table} \begin{center} \begin{tabular}{|l|c c c| } \hline Method & \multicolumn{3}{|c|}{Performance} \\ \hline\hline Vehilce ReID & $\checkmark$ & $\checkmark$ &$\checkmark$ \\ Orientation ReID & &$\checkmark$ &$\checkmark$\\ Camera ReID & & &$\checkmark$\\ \hline mAP & 44.4\% & 47.0\% & 50.8\%\\ rank1 &65.3\% &70.5\% &75.5\% \\ \hline \end{tabular} \end{center} \caption{Influences of VOC fusion on CityFlow validation set.} \label{tab:voc} \end{table} \subsection{Performance on AICity 2020 Challenge} \begin{figure}[htb] \begin{center} \includegraphics[width=1\linewidth]{images/rectify.png} \end{center} \caption{Failure cases that rectified by VOC-ReID. Each group indicates a comparison between before and after applying orientation/camera aware ReID. The first row is the result without orientation/camera ReID while the second row indicates the result with orientation and camera ReID} \label{fig:rectify} \end{figure} In the CVPR 2020 AI City Challenge Image-based Vehicle ReID Track (Track2), our submission ranks the second place on final leaderboard, without using any extra data or annotations. Performance of top 10 teams are shown in Table \ref{tab:team}. Then final result ensembles five models, there are three models for vehicle ReID, one for orientation aware ReID and one for camera aware ReID. The three vehicle ReID models are trained on the same dataset with different backbones, including resnet50-ibn-a, resnet101-ibn-a and resnext101-ibn-a. Simply ensemble models with different backbones does not benefit a lot, it approximately improves 2\% on mAP at the cost of tripling training processes and model sizes, which totally not worth it. Figure . shows some failure cases that rectified by applying orientation and camera aware ReID. Observing from Figure 4, we can see a lot of failure cases have the same orientations and captured from the same cameras, which contribute to the final similarity. \begin{table} \begin{center} \begin{tabular}{|l|c c|} \hline Rank & Team Name & mAP \\ \hline\hline 1 & Baidu-UTS &84.1\% \\ 2 &\textbf{RuiYanAI(Ours)} &\textbf{78.1}\% \\ 3 & DMT &73.1\%\\ 4 & IOSB-VeRi &68.9\%\\ 5 & BestImage &66.8\%\\ 6 & BeBetter &66.6\%\\ 7 & UMD &66.6\%\\ 8 & Ainnovation &65.6\%\\ 9 & NMB &62.0\%\\ 10 & Shahe &61.9\%\\ \hline \end{tabular} \end{center} \caption{Leaderboard of AI City 2020 Track2} \label{tab:team} \end{table} \subsection{Performance on VeRi776} We also test our method on VeRi776 dataset and compare with state-of-the art methods in Table \ref{veri}. Our baseline model outperformances other methods, and applying orientation/camera aware penalty can further boost the performance. We notice that the hyper-parameter P and K in M-Per-Classs sampler largely affect results, on the other hand larger resolution benefits results. \begin{table} \begin{center} \begin{tabular}{|l|c c|} \hline Method & mAP & Rank1 \\ \hline\hline StrongBaseline [4] &67.6\% &90.2\% \\ DMML [5] &70.1\% &90.2\% \\ PAMTRI(ALL) [3] &71.8\% &92.8\% \\ RECT-Net(P=4, K=16, size=256) &78.6\% &95.9\% \\ RECT-Net(P=4, K=16, size=320) &81.6\% &96.8\%\\ +Orientation ReID &82.8\% &97.6\% \\ \hline \end{tabular} \end{center} \caption{Comparison with state-of-the art methods on VeRi776} \label{tab:veri} \end{table} \section{Conclusion} In this paper, we propose a vehicle ReID approach VOC-ReID, which is a framework that joint the vehicle, orientation and camera information together. Previous works either focus on one aspect or spatial-temporary constraints, or joint the view-point invariant feature (2D/3D keypoints, type, color) with the vehicle information to match the vehicle identities. However, we notice that the similarity of vehicle shape and background are key factors that affecting the final result. Therefore, We argue that the similarity of background can be interpreted as camera re-identification and similarity of shape interpreted as orientation re-identification, then we propose VOC-ReID approach which takes the triplet vehicle-orientation- camera as a whole to reduce the bias caused by the similar vehicle shape and background.. Finally, extensive experiments are conducted on CityFlow and VeRi776 to evaluate the VOC-ReID mechanism against the-state-of-the-art methods. Our proposed framework achieves the top performance in VeRi776, and achieve 2nd place in AI City 2020 Track 2, and ablation studies show that each proposed component helps to enhance performance. We believe that the proposed method can generalized to person re-identification task. In the future works, we are going to ensemble the triplet vehicle-orientation-camera in a unified network and explore its effectiveness in person re-identification. \subsection*{Reference} \noindent[1] H. Liu, Y. Tian, Y. Wang, L. Pang, and T. Huang. Deep relative distance learning: Tell the difference between similar vehicles. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 2167-2175, 2016. \noindent[2] X. Liu, W. Liu, H. Ma, and H. Fu. Large-scale vehicle reidentification in urban surveillance videos. In Multimedia and Expo (ICME), 2016 IEEE International Conference on, pages 1–6, 2016. \noindent[3] Z. Tang, M. Naphade, M.-Y. Liu, X. Yang, S. Birchfield, S. Wang, R. Kumar, D. C. Anastasiu, and J.-N. Hwang. Cityflow: A city-scale benchmark for multi-target multicamera vehicle tracking and re-identification. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, 2019. \noindent[4]Y. Sun, L. Zheng, Y. Yang, Q. Tian, and S. Wang. Beyond part models: Person retrieval with refined part pooling. In Proceedings of the European Conference on Computer Vision, pages 480–496, 2018. \noindent[5]L. Zheng, H. Zhang, S. Sun, M. Chandraker, Y. Yang, and Q. Tian. Person re-identification in the wild. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 1367-1376, 2017. \noindent[6]Z. Zheng, X. Yang, Z. Yu, L. Zheng, Y. Yang, and J. Kautz. Joint discriminative and generative learning for person re-identification. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 2138-2147, 2019. \noindent[7]K. He, X. Zhang, S. Ren and J. Sun. Deep residual leanring for image recognition. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages770-778, 2016. \noindent[8]S. Xie, R, Girshick, P. Dollar, Z. Tu, and K. He. Aggregated Residual Transformations for Deep Neural Networks. arXiv 1161.05431, 2016. \noindent[9]X. Pan, P. Luo, J. Shi, X. Tang. Two at Once: Enhancing Learning and Generation Capacities via IBN-Net. In Proceedings of the European Conference on Computer Vision, 2018. \noindent[10]A. Hermans, L. Beyer, and B. Leibe. In defense of the triplet loss for person re-identification. arXiv:1703.07737, 2017. \noindent[11]Y. Sun, C. Cheng, Y. Zhang, C. Zhang, L. Zheng, Z. Wang, Y. Wei. Circle Loss: A Unified Perspective of Pair Similarity Optimization. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, 2020 \noindent[12]T. Hu, H. Qi, Q. Huang, Y. Lu. See Better Before Looking Closer: Weakly Supervised Data Augmentation Network for Fine-Grained Visual Classification. arXiv 1901.09891v2, 2019. \noindent[13]Y. Zhu, Y. Zhou, Q. Ye, Q. Qiu, and J. Jiao. Soft Proposal Networks for Weakly Supervised Object Localization. In Proceedings of the IEEE International Conference on Computer Vision, 2017 \noindent[14]R. Kumar, E. Weill, F. Aghdasi, P. Sriram. A Strong and efficient baseline for vehicle re-identification using deep triplet embedding. Journal of Artificial Intelligence and Soft Computing Research, Pages 27-45, 2020. \noindent[15]X. Liu, W. Liu, T. Mei, and H. Ma. PROVID: Progressive and multimodal vehicle reidentification for large-scale urban surveillance. TMM, 20(3):645–658, 2017. \noindent[16]Y. Bai, Y. Lou, F. Gao, S. Wang, Y. Wu, and L.Y. Duan. Group sensitive triplet embedding for vehicle re-identification. TMM, 20(9):2385–2399, 2018. \noindent[17]Y. Yao, L. Zheng, X. Yang, M. Naphade, and T. Gedeon. Simulating Content Consistent Vehicle Datasets with Attribute Descent. arXiv preprint arXiv:1912.08855. 2019 \noindent[18]T. Zheng, M. Naphade, S. Birchfifield, J. Tremblay, W. Hodge, R. Kumar, S. Wang and X. Yang. Pamtri: Pose-aware multi-task learning for vehicle re-identification using highly randomized synthetic data. In Proceedings of the IEEE International Conference on Computer Vision:211--220. 2019. \noindent[19]Y. Zhou and L. Shao. Aware attentive multi-view inference for vehicle re-identification. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 6489–6498, 2018. \noindent[20]H. Luo, Y. Gu, X. Liao, S. Lai, W. Jiang. Bag of Tricks and A Strong Baseline for Deep Person Re-identification. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition Workshops, 2019. \noindent[21]H. Lawen, Avi Ben-Cohen, M. Protter, I. Friedman, Lihi Zelnik-Manor. Attention Network Robustification for Person ReID. arXiv 1910.07038v2, 2019. \noindent[22]M. Ye, J. Shen, G. Jin, T. Xiang, L. Shao and S. C.H.Hoi. Deep Learning for Person Re-identification: A Survey and Outlook. arXiv 2001.04193v1, 2020. \noindent[23]F. Radenovic, G. Tolias, and O. Chum. Fine-tuning cnn image retrieval with no human annotation. IEEE Transaction on Pattern Analysis and Machine Intelligence, vol. 41, no. 7, pages1655-1668, 2018. \noindent[24]Z. Zhong, L. Zheng, G. Kang, S. Li and Y. Yang. Random erasing data augmentation. arXiv 1708.04896, 2017. \noindent[25]Z. Wang, L. Tang, X. Liu, Z. Yao, S. Yi, J. Shao, J. Yan, S. Wang, H. Li, and X. Wang. Orientation invariant feature embedding and spatial temporal regularization for vehicle re-identification. In Proceedings of the IEEE International Conference on Computer Vision, pages 379–387, 2017. \noindent[26]Z. He, Y. Lei, S. Bai, W. Wu. Multi-Camera Vehicle Tracking with Powerful Visual Features and Spatial-Temporal Cue. In IEEE Conference on Computer Vision and Pattern Recognition (CVPR) Workshops, June, 2019 \noindent[27]T. He, Z. Zhang, H. Zhang, Z.Zhang, J. Xie, M. Li. Bag of Tricks for Image Classification with Convolutional Neural Networks. arXiv preprint arXiv:1812.01187. 2019 \noindent[28]Z. Zhong, L. Zheng, D. Cao, and S. Li. Reranking person re-identification with k-reciprocal encoding. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 1318–1327, 2017. \noindent[29]H. Dan, M. Norman, C. D., Z. Barret, G. Justin and L. Balaji. AugMix: A Simple Data Processing Method to Improve Robustness and Uncertainty. In Proceedings of the International Conference on Learning Representations (ICLR), 2020. \noindent[30]H. Liu, Y. Tian, Y. Wang, L. Pang, and T. Huang. Deep Relative Distance Learning: Tell the Difference Between Similar Vehicles. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 2167--2175, 2016. \end{document}
{'timestamp': '2020-05-18T02:09:11', 'yymm': '2004', 'arxiv_id': '2004.09164', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09164'}
arxiv
\section{Introduction} \label{sec:introduction} The variational autoencoder (VAE) \cite{KingmaW13} is a generative model that combines neural latent variables and amortized variational inference, which is efficient in estimating and sampling from the data distribution. It infers a posterior distribution for each instance with a shared inference network and optimizes the evidence lower bound (ELBO) instead of the intractable marginal log-likelihood. Given its potential to learn representations from massive text data, there has been much interest in using VAE for text modeling \cite{ZhaoZE17,XuD18,HeSNB19}. Prior work has observed that the optimization of VAE suffers from the \textit{posterior collapse} problem, i.e., the posterior becomes nearly identical to the prior and the decoder degenerate into a standard language model \cite{BowmanVVDJB16,ZhaoZE17}. A widely mentioned explanation is that a strong decoder makes the collapsed posterior a good local optimum of ELBO, and existing solutions include weakened decoders \cite{YangHSB17,SemeniutaSB17}, modified regularization terms \cite{HigginsMPBGBML17,WangW19}, alternative posterior families \cite{RezendeM15,DavidsonFCKT18}, richer prior distributions \cite{TomczakW18}, improved optimization strategies \cite{HeSNB19}, and narrowed amortization gaps \cite{KimWMSR18}. In this paper, we provide a novel perspective for the posterior collapse problem. By comparing the optimization dynamics of VAE with deterministic autoencoders (DAE), we observe the incompatibility between a poorly optimized encoder and a decoder with too strong expressiveness. From the perspective of differential geometry, we show that this issue indicates poor \textit{chart maps} from the data manifold to the \textit{parameterizations}, which makes it difficult to learn a \textit{transition map} between them. Since the posterior network is a part of the transition map, we argue that the posterior collapse would be mitigated with better parameterizations. To this end, we propose the Coupled-VAE approach, which couples the VAE model with a deterministic network with the same structure. For better encoder parameterization, we share the encoder weights between the coupled networks. For better decoder parameterization, we propose a signal matching loss that pushes the stochastic decoding signals to the deterministic ones. Notably, our approach is model-agnostic since it does not make any assumption on the regularization term, the posterior family, the decoder architecture, or the optimization strategy. Experiments on PTB, Yelp, and Yahoo show that our method consistently improves the performance of various VAE models in terms of probability estimation and the richness of the latent space. The generalization to conditional modeling, i.e., Coupled-\textbf{C}VAE, largely improves the diversity of dialogue generation on the Switchboard dataset. Our contributions are as follows: \begin{itemize} \item We observe the encoder-decoder incompatibility in VAE and connect it to the posterior collapse problem. \item We propose the Coupled-VAE, which helps the encoder and the decoder to learn better parameterizations of the data manifold with a coupled deterministic network, via encoder weight sharing and decoder signal matching. \item Experiments on PTB, Yelp, and Yahoo show that our approach improves the performance of various VAE models in terms of probability estimation and richness of the latent space. We also generalize Coupled-VAE to conditional modeling and propose Coupled-\textbf{C}VAE, which largely improves the diversity of dialogue generation on the Switchboard dataset. \end{itemize} \section{Background} \label{sec:background} \subsection{Variational Inference for Text Modeling} The generative process of VAE is first to sample a latent code $\bz$ from the prior distribution $\mathcal{P}(\bz)$ and then to sample the data $x$ from $P(x|\bz;\theta)$ \cite{KingmaB14}. Since the exact marginalization of the log-likelihood is intractable, a variational family of posterior distributions $\mathcal{Q}(\bz|x; \phi)$ is adopted to derive the evidence lower bound (ELBO), i.e., \begin{equation} \label{eq:vae-elbo} \begin{split} \log P(x;\theta) &\geq \mathbb{E}_{\bz \sim \mathcal{Q}(\bz|x;\phi)}[\log P(x|\bz;\theta)] \\ &\ \ \ \ \ - \mathrm{KL}[\mathcal{Q}(\bz|x; \phi) \parallel \mathcal{P}(\bz)] \end{split} \end{equation} For training, as shown in Figure~\ref{subfig:vae}, the encoded text $\bm{e}$ is transformed into its posterior via a posterior network. A latent code is sampled and mapped to the decoding signal $\bm{h}$. Finally, the decoder infers the input with the decoding signal. The objective can be viewed as a reconstruction loss $\mathcal{L}_{\itm{rec}}$ plus a regularization loss $\mathcal{L}_{\itm{reg}}$ (whose form varies), i.e., \begin{equation} \label{eq:vae-general-loss} \mathcal{L} = \mathcal{L}_{\itm{rec}} + \mathcal{L}_{\itm{reg}} \end{equation} However, the optimization of the VAE objective is challenging. We usually observe a very small $\mathcal{L}_{\itm{reg}}$ and a $\mathcal{L}_{\itm{rec}}$ similar to a standard language model, i.e., the well-known \textit{posterior collapse} problem. \begin{figure}[t] \centering \subfigure[Variational autoencoder]{ \includegraphics[width=0.5\linewidth]{VAE-Text.pdf} \label{subfig:vae} } \subfigure[Deterministic autoencoder]{ \includegraphics[width=0.5\linewidth]{DAE.pdf} \label{subfig:dae} } \caption{VAE and DAE for text modeling.} \end{figure} \subsection{Deterministic Autoencoders} An older family of autoencoders is the deterministic autoencoder (DAE) \cite{rumelhart1986learning,Ballard87}. Figure~\ref{subfig:dae} shows an overview of DAE for text modeling, which is composed of a text encoder, an optional MLP, and a text decoder. The reconstruction loss of DAE is usually much lower than that of VAE after convergence. \section{Encoder-Decoder Incompatibility in VAE for Text Modeling} \label{sec:analysis} To understand the posterior collapse problem, we take a deeper look into the training dynamics of VAE. We investigate the following questions. How much backpropagated gradient does the encoder receive from reconstruction? How much does it receive from regularization? How much information does the decoder receive from the encoded text? \subsection{Tracking Training Dynamics} \label{subsec:tracking} \begin{figure*}[t] \centering \subfigure[Gradient norm of the reconstruction loss w.r.t. the encoded text]{ \includegraphics[width=0.3\linewidth]{drecde-yelp.pdf} \label{subfig:curve-derecde} } \hspace{0.02\linewidth} \subfigure[Gradient norm of the regularization loss w.r.t. the encoded text]{ \includegraphics[width=0.3\linewidth]{dregde-yelp.pdf} \label{subfig:cuurve-dregde} } \hspace{0.02\linewidth} \subfigure[Gradient norm of the decoding signal w.r.t. the encoded text]{ \includegraphics[width=0.3\linewidth]{dhde-yelp.pdf} \label{subfig:cuurve-dhde} } \caption{\label{fig:gradient-norms-curve} Training dynamics of DAE, VAE, and the proposed Coupled-VAE on the Yelp test set. Please find the analysis in Section~\ref{sec:analysis} and Section~\ref{subsec:analysis-gradients}. Best viewed in color (yet the models are distinguished by line markers).} \end{figure*} To answer the first question, we study the gradient norm of the reconstruction loss w.r.t. the encoded text, i.e., $\left\| \partial \mathcal{L}_{\itm{rec}} / \partial \bm{e} \right\|_{2}$, which shows the magnitude of gradients received by the encoder parameters. From Figure~\ref{subfig:curve-derecde}, we observe that it constantly increases in DAE, while in VAE it increases marginally in the early stage and then decreases continuously. It shows that the reconstruction loss actively optimizes the DAE encoder, while the VAE encoder lacks backpropagated gradients after the early stage of training. We seek the answer to the second question by studying the gradient norm of the regularization loss w.r.t. the encoded text, i.e., $\left\| \partial \mathcal{L}_{\itm{reg}} / \partial \bm{e} \right\|_{2}$. In a \textit{totally} collapsed posterior, i.e., $\mathcal{Q}(\bz|x; \phi) = \mathcal{P}(\bz)$ for each $x$, $\left\| \partial \mathcal{L}_{\itm{reg}} / \partial \bm{e} \right\|_{2}$ would be zero. Thus, $\left\| \partial \mathcal{L}_{\itm{reg}} / \partial \bm{e} \right\|_{2}$ can show how far the posterior of each instance is from the aggregate posterior or the prior. Figure~\ref{subfig:cuurve-dregde} shows a constant decrease of the gradient norm in VAE from the 2.5K step until convergence, which shows that the posterior collapse is aggravated as the KL weight increases. For the third question, we compute the normalized gradient norm of the decoding signal w.r.t. the encoded text, i.e., $\left\| \partial \bm{h} / \partial \bm{e} \right\|_{F} / \left\| \bm{h} \right\|_{2}$. As this term shows how relatively the decoding signal changes with the perturbation of the encoded text, it reflects the amount of information passed from the encoder to the decoder. Figure~\ref{subfig:cuurve-dhde} shows that for DAE, it constantly increases. For VAE, it at first increases even faster than DAE, slows down, and finally decreases until convergence, indicating that the VAE decoder, to some extent, ignores the encoder in the late stage of training. \begin{figure*}[t] \centering \subfigure{ \includegraphics[width=0.27\linewidth]{Manifold.pdf} } \hspace{0.03\linewidth} \subfigure{ \includegraphics[width=0.55\linewidth]{Couple-VAE-Model.pdf} } \caption{\label{fig:Coupled-VAE} Left: DAE and VAE interpreted as manifold parameterizations and a transition map. Right: A graphical overview of the proposed Coupled-VAE. The upper path is deterministic, and the lower path is stochastic.} \end{figure*} \subsection{Encoder-Decoder Incompatibility} \label{subsec:incompatibility} Based on the training dynamics in Section~\ref{subsec:tracking} and the observations in previous work \cite{BowmanVVDJB16,ZhaoZE17}, text VAE has three features, listed as follows. First, the encoder is poorly optimized, as shown by the low $\left\| \partial \mathcal{L}_{\itm{rec}} / \partial \bm{e} \right\|_{2}$. Second, the decoder degenerates into a powerful language model. Third, $\bm{h}$ contains less information from $\bm{e}$ in VAE than in DAE, which is indicated by the lower $\left\| \partial \bm{h} / \partial \bm{e} \right\|_{F} / \left\| \bm{h} \right\|_{2}$. We call these features as \textit{encoder-decoder incompatibility}. To bridge the incompatibility and posterior collapse, we start with the \textit{manifold hypothesis} which states that real-world data concentrates near a manifold with a lower dimensionality than the ambient space \cite{NarayananM10,BengioCV13}. In our case, we denote the manifold of text data as $\mathcal{X} \subset \bigcup_{l \in \mathbb{N}} \mathcal{V}^{l}$ where $\mathcal{V}$ is the vocabulary. In the language of differential geometry, the encoded text $\bm{e} \in \mathcal{E} \subset \mathbb{R}^{d}$ and the decoding signal $\bm{h} \in \mathcal{H} \subset \mathbb{R}^{d}$ can be viewed as the \textit{parameterizations} (or \textit{coordinates}) of $x \in \mathcal{X}$ under two different \textit{charts} (or \textit{coordinate systems}). Formally, we denote the chart maps as $\varphi_{e}: \mathcal{X} \rightarrow \mathcal{E}$ and $\varphi_{h}: \mathcal{X} \rightarrow \mathcal{H}$, which satisfy $\bm{e} = \varphi_{e}(x)$ and $\bm{h} = \varphi_{h}(x)$ for any $x \in \mathcal{X}$. Given the two charts, the map from $\mathcal{E}$ to $\mathcal{H}$ is called the \textit{transition map} $\varphi_{h} \circ \varphi_{e}^{-1}: \mathcal{E} \rightarrow \mathcal{H}$ between the two charts. In DAE, the two chart maps and the transition map between them are learned simultaneously via the single reconstruction loss, which we rewrite as \begin{equation} \label{eq:diff-geom-rec-loss} \mathcal{L}_{\itm{rec}} = \mathbb{E}_{x \in \mathcal{X}}[\mathcal{L}(x, \varphi_{h}^{-1}(\varphi_{h} \circ \varphi_{e}^{-1}(\varphi_{e}(x))))] \end{equation} where $\varphi_{e}$, $\varphi_{h} \circ \varphi_{e}^{-1}$, and $\varphi_{h}^{-1}$ are modeled as the encoder, the MLP, and the decoder (strictly speaking, in text modeling, the range of $\varphi_{h}^{-1}$ is not $\mathcal{X}$ but distributions on $\mathcal{X}$), as illustrated in Figure~\ref{fig:Coupled-VAE}. In VAE, as discussed before, both $\varphi_{e}$ and $\varphi_{h}$ inadequately parameterize the data manifold. We argue that the inadequate parameterizations make it harder to find a smooth transition map in VAE than in DAE, as shown by the lower $\left\| \partial \bm{h} / \partial \bm{e} \right\|_{F} / \left\| \bm{h} \right\|_{2}$. Since the posterior network is a part of the transition map, it consequently seeks to map each instance to the prior (discussed in Section~\ref{subsec:tracking}) rather than learning the transition map. \section{Coupling Variational and Deterministic Networks} \label{sec:methodology} Based on the above analysis, we argue that posterior collapse could be alleviated by learning chart maps (i.e., $\varphi_{e}$ and $\varphi_{h}$) that better parameterize the data manifold. Inspired by the chart maps in DAE, we propose to couple the VAE model with a deterministic network, outlined in Figure~\ref{fig:Coupled-VAE}. Modules with a subscript $c$ are deterministic networks that share the \textit{structure} with those in the stochastic network. Sampling is disabled in the deterministic network, e.g., in the case of Gaussian posterior, we use the predicted mean vector for later computation. Please find details for other posterior families in Appendix~\ref{app:deterministic-details}. Similar to DAE, the coupled deterministic network is optimized solely by the coupled reconstruction loss $\mathcal{L}_{\itm{rec}}^{c}$, which is the same autoregressive cross-entropy loss as $\mathcal{L}_{\itm{rec}}$. To learn a well-optimized $\varphi_{e}$, we share the encoder between the stochastic and the deterministic networks, which leverages the rich gradients backpropagated from $\mathcal{L}_{\itm{rec}}^{c}$. To learn better $\varphi_{h}$, we propose to guide $\varphi_{h}$ with a well-learned chart map, i.e., the one characterized by $\mathrm{Decoder}^c$. Thus, we introduce a signal matching loss $\mathcal{L}_{\itm{match}}$ that pushes the $\bm{h}$ to $\bm{h}^{c}$. The objective of our approach is \begin{equation} \label{eq:Coupled-VAE} \mathcal{L} = \mathcal{L}_{\itm{rec}} + \mathcal{L}_{\itm{reg}} + \lambda_{r} \mathcal{L}_{\itm{rec}}^{c} + \lambda_{m} \mathcal{L}_{\itm{match}} \end{equation} where $\lambda_{r}$ and $\lambda_{m}$ are hyperparameters\footnote{To avoid heavy hyperparameter tuning, we set $\lambda_{r}=1.0$ unless otherwise specified.}, $\mathcal{L}_{\itm{rec}}^{c}$ is the coupled reconstruction loss, and the signal matching loss $\mathcal{L}_{\itm{match}}$ is essentially a distance function between $\bm{h}$ and $\bm{h}^{c}$. We evaluate both the Euclidean distance and the Rational Quadratic kernel\footnote{To avoid heavy hyperparameter tuning, we use the Rational Quadratic kernel unless otherwise specified.}, i.e., \begin{equation} \label{eq:l-couple} \mathcal{L}_{\itm{match}} = \left\{ \begin{array}{rcl} \left\| \bm{h} - \mathrm{Detach(}\bm{h}^{c}\mathrm{)} \right\|^{2} \hfill \ \ \ \textrm{Eucl} \\ \sum_{s}\frac{- s \cdot C}{s \cdot C + \left\| \bm{h} - \mathrm{Detach(}\bm{h}^{c}\mathrm{)} \right\|^{2}} \hfill \ \ \ \textrm{RQ} \end{array} \right. \end{equation} where $s \in \{0.1, 0.2, 0.5, 1, 2, 5, 10\}$, $C$ is a hyper-parameter, and $\mathrm{Detach}$ prevents gradients to be propagated into $\bm{h}^{c}$ since we would like $\bm{h}^{c}$ to guide $\bm{h}$ but not the opposite. One would question the necessity of sharing the structure of the posterior network by resorting to universal approximation \cite{HornikSW89}. Specifically, a common question is: why not using an MLP as $\textrm{Posterior}_{c}$? We argue that each structure has a favored distribution of $\mathcal{H}$ in $\mathbb{R}^{d}$, so structure sharing facilitates the optimization when we are learning by gradient descent. For example, the latent space learned by planar flows \cite{RezendeM15} has compression and expansion, and vMF-VAE \cite{XuD18}, which is supported on a sphere, may significantly influence the distribution of $\mathcal{H}$ in its ambient space $\mathbb{R}^{d}$. \begin{table*}[t] \centering \small \begin{tabular}{@{}llrlrlr@{}} \toprule \multirow{2}*{} & \multicolumn{2}{c}{PTB} & \multicolumn{2}{c}{Yelp} & \multicolumn{2}{c}{Yahoo}\\ \cmidrule(lr){2-3} \cmidrule(lr){4-5} \cmidrule(l){6-7} ~ & NLL (KL) & PPL & NLL (KL) & PPL & NLL (KL) & PPL \\ \midrule GRU-LM* & 105.8 (-) & 125.3 & 196.3 (-) & 57.3 & 347.9 (-) & 78.0 \\ \midrule VAE & 103.6 (8.6) & 112.9 & 193.7 (7.2) & 54.3 & 344.5 (12.4) & 74.7 \\ Coupled-VAE & \bf 103.1 (9.5) & \bf 110.5 & \bf 191.2 (8.0) & \bf 51.6 & \bf 342.4 (12.8) & \bf 72.8 \\ \midrule $\beta(0.8)$-VAE & 103.8 (11.0) & 113.9 & 193.8 (10.2) & 54.5 & 344.9 (16.1) & 75.1 \\ Coupled-$\beta(0.8)$-VAE & \bf 103.3 (12.1) & \bf 111.5 & \bf 191.5 (12.2) & \bf 51.9 & \bf 342.8 (17.0) & \bf 73.2 \\ \midrule $\beta(1.2)$-VAE & 103.7 (7.8) & 113.3 & 193.7 (6.0) & 54.3 & 345.3 (10.5) & 75.5 \\ Coupled-$\beta(1.2)$-VAE & \bf 102.9 (8.6) & \bf 109.6 & \bf 191.2 (6.9) & \bf 51.6 & \bf 342.3 (11.3) & \bf 72.7 \\ \midrule vMF-VAE & 103.6 (2.0) & 113.2 & 195.4 (0.0) & 56.3 & 344.5 (2.5) & 74.7 \\ Coupled-vMF-VAE & \bf 103.0 (3.0) & \bf 110.1 & \bf 191.2 (2.8) & \bf 51.6 & \bf 342.2 (4.0) & \bf 72.5 \\ \midrule CNN-VAE & 118.5 (29.6) & 222.6 & 194.2 (12.8) & 54.8 & 344.3 (19.7) & 74.5 \\ Coupled-CNN-VAE & \bf 118.2 (30.2) & \bf 219.7 & \bf 193.9 (13.7) & \bf 54.6 & \bf 343.3 (22.4) & \bf 73.6 \\ \midrule WAE & 103.7 (11.0) & 113.3 & 193.7 (10.7) & 54.3 & 344.7 (16.6) & 74.9 \\ Coupled-WAE & \bf 103.2 (12.5) & \bf 110.9 & \bf 191.3 (12.5) & \bf 51.7 & \bf 343.3 (18.2) & \bf 73.6 \\ \midrule VAE-NF & 103.3 (5.5) & 111.3 & 193.9 (5.3) & 54.5 & 344.3 (8.1) & 74.5 \\ Coupled-VAE-NF & \bf 102.6 (5.7) & \bf 108.1 & \bf 191.8 (5.6) & \bf 52.2 & \bf 342.6 (8.8) & \bf 73.0 \\ \midrule WAE-NF & 103.4 (6.7) & 111.9 & 194.1 (7.0) & 54.7 & 344.3 (10.6) & 74.5 \\ Coupled-WAE-NF & \bf 102.7 (7.4) & \bf 108.4 & \bf 192.1 (7.4) & \bf 52.5 & \bf 342.7 (11.0) & \bf 73.1 \\ \midrule CycAnn-VAE & 104.2 (1.6) & 116.3 & 192.5 (1.2) & 53.0 & 345.4 (3.9) & 75.5 \\ Coupled-CycAnn-VAE & \bf 103.7 (2.4) & \bf 113.3 & \bf 190.8 (2.0) & \bf 51.1 & \bf 342.4 (4.4) & \bf 72.7 \\ \midrule PreFB-VAE & 103.4 (14.6) & 111.9 & 190.4 (14.1) & 50.7 & 341.4 (17.6) & 71.8 \\ Coupled-PreFB-VAE & \bf 103.3 (15.6) & \bf 111.4 & \bf 189.9 (14.4) & \bf 50.3 & \bf 341.3 (17.9) & \bf 71.7 \\ \midrule SA-VAE$^{\dag}$ & 100.7 (7.7) & 98.7 & 183.5 (3.8) & 44.0 & 327.5 (7.2)$^\ddag$ & 60.4$^\ddag$ \\ \midrule Lagging-VAE$^{\dag}$ & 98.8 (6.0) & 90.7 & 182.5 (1.2) & 43.1 & 326.7 (6.0) & 59.7 \\ Coupled-Lagging-VAE$^{\dag}$ & \bf 98.7 (11.0) & \bf 90.4 & \bf 182.3 (3.8) & \bf 42.9 & \bf 326.2 (7.4) & \bf 59.3 \\ \bottomrule \end{tabular} \caption{\label{tab:lm-results} Language modeling results. NLL is estimated with importance sampling. PPL is based on the estimated NLL. KL and MI are approximated by their Monte Carlo estimates. \textit{Coupled-} stands for ``with the coupled deterministic network''. The better results in each block are shown in \textbf{bold}. *The exact NLL is reported. $^\dag$Modifying open-source implementation which does not follow our setup and evaluation. $^\ddag$Previously reported.} \end{table*} \section{Experiments} \label{sec:experiments} \subsection{Datasets} We conduct the experiments on three commonly used datasets for text modeling, i.e., the Penn Treebank (PTB) \cite{MarcusSM94}, Yelp \cite{XuCQH16}, and Yahoo. The training/validation/test splits are 42K/3370/3761 for PTB, 63K/7773/8671 for Yelp, and 100K/10K/10K for Yahoo. The vocabulary size for PTB/Yelp/Yahoo is 10K/15K/20K. We discard the sentiment labels in Yelp. \subsection{Baselines} We evaluate the proposed Coupled-VAE approach by applying it to various VAE models, which include VAE \cite{KingmaW13}, $\beta$-VAE \cite{HigginsMPBGBML17}, vMF-VAE \cite{XuD18,DavidsonFCKT18} with learnable $\kappa$, CNN-VAE \cite{YangHSB17}, WAE \cite{TolstikhinBGS18}, VAE with normalizing flows (VAE-NF) \cite{RezendeM15}, WAE with normalizing flows (WAE-NF), VAE with cyclic annealing schedule (CycAnn-VAE) \cite{FuLLGCC19}, VAE with encoder pretraining and the free bits objective (PreFB-VAE) \cite{LiHNBY19}, and Lagging-VAE \cite{HeSNB19}. We also show the result of GRU-LM \cite{ChoMGBBSB14} and SA-VAE \cite{KimWMSR18}. We do not apply our method to SA-VAE since it does not follow amortized variational inference. Please find more details in Appendix~\ref{app:setup} and previous footnotes. \begin{table*}[t] \centering \small \begin{tabular}{@{}lrrrrrr@{}} \toprule \multirow{2}*{} & \multicolumn{2}{c}{PTB} & \multicolumn{2}{c}{Yelp} & \multicolumn{2}{c}{Yahoo}\\ \cmidrule(lr){2-3} \cmidrule(lr){4-5} \cmidrule(l){6-7} ~ & MI \ \ & BLEU-1/2 & MI \ \ & BLEU-1/2 & MI \ \ & BLEU-1/2 \\ \midrule VAE & 10.48 & 23.2 / 4.4 & 8.28 & 28.7 / 5.3 & 15.43 & 21.2 / 3.6 \\ Coupled-VAE & \bf 11.99 & \bf 23.4 / 4.5 & \bf 9.65 & \bf 30.4 / 5.8 & \bf 16.44 & \bf 23.1 / 4.1 \\ \midrule $\beta(0.8)$-VAE & 15.43 & \bf 24.5 / 4.9 & 13.52 & 30.6 / 6.0 & 24.16 & 24.0 / 4.3 \\ Coupled-$\beta(0.8)$-VAE & \bf 18.13 & 24.3 / 4.8 & \bf 17.69 & \bf 32.6 / 6.6 & \bf 28.03 & \bf 26.4 / 4.9 \\ \midrule $\beta(1.2)$-VAE & 9.16 &22.8 / \textbf{4.3}& 6.60 & 28.0 / 5.0 & 11.83 & 18.2 / 2.9 \\ Coupled-$\beta(1.2)$-VAE & \bf 10.28 &\textbf{22.9} / 4.2& \bf 7.90 & \bf 29.8 / 5.6 & \bf 13.51 & \bf 22.4 / 3.8 \\ \midrule vMF-VAE & 1.74 & 15.2 / 2.0 & 0.03 & 22.4 / 2.8 & 2.06 & 8.5 / 1.1 \\ Coupled-vMF-VAE & \bf 2.37 & \bf 16.1 / 2.3 & \bf 2.60 & \bf 25.1 / 4.0 & \bf 3.37 & \bf 10.3 / 1.4 \\ \midrule CNN-VAE & 78.49 & \bf 32.0 / 7.8 & 17.26 & 32.9 / 7.1 & 30.18 & 24.9 / 5.3 \\ Coupled-CNN-VAE & \bf 80.54 & 31.8 / 7.7 & \bf 19.15 & \bf 33.4 / 7.3 & \bf 37.62 & \bf 26.9 / 5.9 \\ \midrule WAE & 15.09 & \bf 24.8 / 5.1 & 15.08 & 30.7 / 6.1 & 24.73 & 24.2 / 4.5 \\ Coupled-WAE & \bf 18.51 & 24.7 / \bf 5.1 & \bf 18.56 & \bf 32.5 / 6.6 & \bf 30.08 & \bf 27.7 / 5.3 \\ \midrule VAE-NF & 5.63 & 19.2 / \bf 3.3 & 5.64 & 25.6 / 4.5 & 8.02 & 13.7 / 2.1 \\ Coupled-VAE-NF & \bf 5.86 & \bf 19.4 / 3.3 & \bf 6.06 & \bf 26.3 / 4.6 & \bf 9.14 & \bf 15.3 / 2.5 \\ \midrule WAE-NF & 7.18 & 19.7 / 3.5 & 7.95 & 26.0 / 4.6 & 11.43 & 13.8 / 2.2 \\ Coupled-WAE-NF & \bf 8.10 & \bf 20.7 / 3.7 & \bf 8.53 & \bf 27.2 / 5.0 & \bf 12.56 & \bf 14.9 / 2.5 \\ \midrule CycAnn-VAE & 1.55 & 16.3 / 2.3 & 1.18 & 22.6 / 3.2 & 3.09 & 8.3 / 1.1 \\ Coupled-CycAnn-VAE & \bf 2.27 & \bf 16.7 / 2.6 & \bf 2.01 & \bf 23.1 / 3.4 & \bf 3.89 & \bf 10.9 / 1.5 \\ \midrule PreFB-VAE & 20.6 & 25.5 / 5.7 & 20.3 & 33.1 / 6.8 & 26.2 & 27.2 / 5.2 \\ Coupled-PreFB-VAE & \bf 23.2 & \bf 25.8 / 5.8 & \bf 21.0 & \bf 33.3 / 6.8 & \bf 27.0 & \bf 27.2 / 5.3 \\ \midrule Lagging-VAE$^{\dag}$ & 2.90 & \multicolumn{1}{c}{-} & 0.96 & \multicolumn{1}{c}{-} & 3.04 & \multicolumn{1}{c}{-} \\ Coupled-Lagging-VAE$^{\dag}$ & \bf 3.29 & \multicolumn{1}{c}{-} & \bf 2.36 & \multicolumn{1}{c}{-} & \bf 3.06 & \multicolumn{1}{c}{-} \\ \bottomrule \end{tabular} \caption{\label{tab:info-results} Mutual information (MI) and reconstruction. $^{\dag}$Modifying the open-source implementation.} \end{table*} \subsection{Language Modeling Results} \label{subsec:language-modeling} We report negative log-likelihood (NLL), KL divergence, and perplexity as the metrics for language modeling. NLL is estimated with importance sampling, KL is approximated by its Monte Carlo estimate, and perplexity is computed based on NLL. Please find the metric details in Appendix~\ref{app:lm-metrics}. Table~\ref{tab:lm-results} displays the language modeling results. For all models, our proposed approach achieves smaller negative log-likelihood and lower perplexity, which shows the effectiveness of our method to improve the probability estimation capability of various VAE models. Larger KL divergence is also observed, showing that our approach helps address the posterior collapse problem. \subsection{Mutual Information and Reconstruction} Language modeling results only evaluate the probability estimation ability of VAE. We are also interested in how rich the latent space is. We report the mutual information (MI) between the text $x$ and the latent code $\bz$ under $\mathcal{Q}(\bz|x)$, which is approximated with Monte Carlo estimation. Better reconstruction from the encoded text is another way to show the richness of the latent space. For each text $x$, we sample ten latent codes from $\mathcal{Q}(\bz|x)$ and decode them with greedy search. We report the BLEU-1 and BLEU-2 scores between the reconstruction and the input. Please find the metric details in Appendix~\ref{app:info-metrics}. In Table~\ref{tab:info-results}, we observe that our approach improves MI on all datasets, showing that our approach helps learn a richer latent space. BLEU-1 and BLEU-2 are consistently improved on Yelp and Yahoo, but not on PTB. Given that text samples in PTB are significantly shorter than those in Yelp and Yahoo, we conjecture that it is easier for the decoder to reconstruct on PTB by exploiting its autoregressive expressiveness, even without a rich latent space. \begin{table*}[t] \centering \small \begin{tabular}{@{}llllccrlccr@{}} \toprule ~ & ~ & ~ & \multicolumn{4}{c}{PTB} & \multicolumn{4}{c}{Yelp}\\ \cmidrule(lr){4-7} \cmidrule(l){8-11} Dist & $\lambda_{m}$ & $\lambda_{r}$ & NLL (KL) & PPL & MI & BLEU-1/2 & NLL (KL) & PPL & MI & BLEU-1/2 \\ \midrule \multirow{3}*{RQ} & $0.1$* & \multirow{3}*{$1.0$} & \bf 103.1 (9.5) & \bf 110.5 & 11.99 & 23.4 / 4.5 & 191.2 (8.0) & 51.6 & 9.65 & 30.4 / 5.8 \\ ~ &$1.0$ & & 103.3 (10.7) & 111.4 & 14.32 & 24.0 / 4.8 & \bf 191.1 (8.1) & \bf 51.5 & 9.92 & 30.5 / 5.8 \\ ~ &$5.0$ & & 103.7 (16.1) & 113.2 & \bf 32.78 & \bf 26.5 / 5.8 & 191.5 (12.8) & 51.9 & \bf 19.77 & \bf 32.8 / 6.5 \\ \midrule \multirow{4}*{RQ} & \multirow{4}*{$0.1$} & $0.0$ & 104.1 (7.3) & 115.3 & 8.60 & 21.0 / 3.7 & 191.7 (5.8) & 52.1 & 6.40 & 27.7 / 5.0 \\ & & $0.5$ & 103.4 (9.2) & 111.8 & 11.58 & 23.1 / 4.3 & 191.3 (7.8) & 51.7 & 9.32 & 29.8 / 5.7 \\ & & $1.0$* & \bf 103.1 (9.5) & \bf 110.5 & \bf 11.99 & \bf 23.4 / 4.5 & \bf 191.2 (8.0) & \bf 51.6 & \bf 9.65 & \bf 30.4 / 5.8 \\ & & $5.0$ & \bf 103.1 (9.1) & 110.6 & 11.15 & 22.9 / 4.4 & 192.9 (8.0) & 53.4 & 9.53 & 30.0 / 5.8 \\ \midrule \multirow{3}*{Eucl} & $0.1$ & \multirow{3}*{$1.0$} & \bf 103.3 (10.1) & \bf 111.5 & 13.25 & 23.4 / 4.7 & \bf 191.2 (9.2) & \bf 51.6 & 11.69 & 31.1 / 6.0 \\ ~ &$1.0$ & & 103.9 (17.4) & 114.5 & 30.52 & 27.7 / 6.1 & 192.1 (14.3) & 52.5 & 23.14 & 33.8 / 6.9 \\ ~ &$5.0$ & & 108.9 (33.3) & 144.0 & \bf 98.02 & \bf 32.0 / 8.5 & 194.4 (25.0) & 55.1 & \bf 61.62 & \bf 36.8 / 8.2 \\ \midrule & VAE & & 103.6 (8.6) & 112.9 & 10.48 & 23.2 / 4.4 & 193.7 (7.2) & 54.3 & 8.28 & 28.7 / 5.3 \\ \bottomrule \end{tabular} \caption{\label{tab:matching-weight} Hyperparameter analysis. The best results in each block are shown in \textbf{bold}. *Reported in Table~\ref{tab:lm-results} and \ref{tab:info-results}.} \end{table*} \subsection{Hyperparameter Analysis: Distance Function, $\lambda_{r}$, and $\lambda_{m}$} \label{subsec:hyperparameter-analysis} We investigate the effect of key hyperparameters. Results are shown in Table~\ref{tab:matching-weight}. Note that the lowest NLL does not guarantee the best other metrics, which shows the necessity to use multiple metrics for a more comprehensive evaluation. For the distance function, we observe that the Euclidean distance (denoted as Eucl in Table~\ref{tab:matching-weight}) is more sensitive to $\lambda_{m}$ than the Rational Quadratic kernel (denoted as RQ in Table~\ref{tab:matching-weight}). The first and the third block in Table~\ref{tab:matching-weight} show that, with larger $\lambda_{m}$, the model achieves higher KL divergence, MI, and reconstruction metrics. Our interpretation is that by pushing the stochastic decoding signals closer to the deterministic ones, we get latent codes with richer text information. We leave the analysis of $\lambda_{m}=0.0$ in Section~\ref{subsec:role-matching}. The second block in Table~\ref{tab:matching-weight} shows the role of $\lambda_{r}$, which we interpret as follows. When $\lambda_{r}$ is too small (e.g., $0.5$), the learned parameterizations are still inadequate for a smooth transition map; when $\lambda_{r}$ is too large (e.g., $5.0$), it distracts the optimization too far away from the original objective (i.e., $\mathcal{L}_{\itm{rec}} + \mathcal{L}_{\itm{reg}}$). Note that $\lambda_{r}=0.0$ is equivalent to removing the coupled reconstruction loss $\mathcal{L}_{\itm{rec}}^{c}$ in Eq.~(\ref{eq:Coupled-VAE})). \subsection{The Heterogeneous Effect of Signal Matching on Probability Estimation} \label{subsec:role-matching} \begin{table}[t] \centering \small \begin{tabular}{@{}l@{}cccc@{}} \toprule \multirow{2}*{} & \multicolumn{2}{c}{PTB} & \multicolumn{2}{c}{Yelp} \\ \cmidrule(r){2-3} \cmidrule(l){4-5} ~ & NLL & PPL & NLL & PPL \\ \midrule Coupled-VAE* & 103.1 & 110.5 & 191.2 & 51.6 \\ Coupled-VAE ($\lambda_{m}$=$0$) & \bf 103.1 & \bf 110.3 & \bf 190.7 & \bf 51.1 \\ \midrule Coupled-VAE-NF* & \bf 102.6 & \bf 108.1 & \bf 191.8 & \bf 52.2 \\ Coupled-VAE-NF ($\lambda_{m}$=$0$) & 102.8 & 109.1 & 192.7 & 53.2 \\ \midrule Coupled-vMF-VAE* & \bf 103.0 & \bf 110.1 & \bf 191.2 & \bf 51.6 \\ Coupled-vMF-VAE ($\lambda_{m}$=$0$) \ & 104.4 & 117.1 & 193.5 & 54.1 \\ \bottomrule \end{tabular} \caption{\label{tab:ablation} The effect of signal matching on probability estimation. * Reported in Table~\ref{tab:lm-results}.} \end{table} In Section~\ref{subsec:hyperparameter-analysis} we observe richer latent space (i.e., larger MI and BLEU scores) with larger $\lambda_{m}$. However, a richer latent space does not guarantee a better probability estimation result. Thus, in this part, we delve deeper into whether the decoder signal matching mechanism helps improve probability estimation. We study three models of different posterior families (i.e., Coupled-VAE, Coupled-VAE-NF, and Coupled-vMF-VAE). Results are shown in Table~\ref{tab:ablation}, where we do not report the KL, MI, and BLEU scores because they have been shown to be improved with larger $\lambda_{m}$ in Table~\ref{tab:matching-weight}. We observe that the effects of signal matching on probability estimation vary in different posterior families. \subsection{Is the Incompatibility Mitigated?} \label{subsec:analysis-gradients} \begin{table*}[t] \centering \small \begin{tabular}{@{}l|l|ccccc@{}} \toprule \multicolumn{2}{c}{} & $\left\| \partial \mathcal{L}_{\itm{rec}} / \partial \bm{e} \right\|_{2}$ & $\left\| \partial \mathcal{L}_{\itm{rec}}^{c} / \partial \bm{e} \right\|_{2}$ & $\left\| (\partial \mathcal{L}_{\itm{rec}} + \mathcal{L}_{\itm{rec}}^{c}) / \partial \bm{e} \right\|_{2}$ & $\left\| \partial \mathcal{L}_{\itm{reg}} / \partial \bm{e} \right\|_{2}$ & $\left\| \partial \bm{h} / \partial \bm{e} \right\|_{F} / \left\| \bm{h} \right\|_{2}$ \\ \midrule \multirow{4}*{PTB} & DAE & 1719.8& - & - & - & 3.14 \\ \cmidrule(){2-7} ~ & VAE & 112.5 & - & - & 19.4 & 2.05 \\ ~ & Coupled-VAE & \bf 148.5 & 2109.6 & 2320.2 & \bf 27.7 & \bf 2.12 \\ \midrule \multirow{4}*{Yelp} & DAE & 2443.6& - & - & - & 2.55 \\ \cmidrule(){2-7} ~ & VAE & 59.7 & - & - & 18.8 & 1.62 \\ ~ & Coupled-VAE & \bf 84.8 & 3640.8 & 3764.7 & \bf 25.0 & \bf 2.25 \\ \midrule \multirow{4}*{Yahoo}& DAE & 4104.6& - & - & - & 3.39 \\ \cmidrule(){2-7} ~ & VAE & 257.9 & - & - & 52.8 & 2.92 \\ ~ & Coupled-VAE & \bf 335.3 & 5105.0 & 5615.0 & \bf 65.0 & \bf 3.91 \\ \bottomrule \end{tabular} \caption{\label{tab:gradient-results} Gradient norms defined in Section~\ref{subsec:tracking} on each test set. $\lambda_{m}=0.1$.} \end{table*} We study the three gradient norms defined in Section~\ref{sec:analysis} on the test sets, displayed in Table~\ref{tab:gradient-results} (for Coupled-VAE, $\lambda_{m}=0.1$). Notably, $\left\| \partial \mathcal{L}_{\itm{rec}}^{c} / \partial \bm{e} \right\|_{2}$ in Coupled-VAE is even larger than $\left\| \partial \mathcal{L}_{\itm{rec}} / \partial \bm{e} \right\|_{2}$ in DAE. It has two indications. First, the encoder indeed encodes rich information of the text. Second, compared with DAE, Coupled-VAE better generalizes to the test sets, which we conjecture is due to the regularization on the posterior. Coupled-VAE also has a larger $\left\| \partial \mathcal{L}_{\itm{reg}} / \partial \bm{e} \right\|_{2}$ compared with VAE, which based on the argument in Section~\ref{subsec:tracking} indicates that, in Coupled-VAE, the posterior of each instance is not similar to the prior. We also observe larger $\left\| \partial \bm{h} / \partial \bm{e} \right\|_{F} / \left\| \bm{h} \right\|_{2}$ in Coupled-VAE, which indicates a better transition map between the two parameterizations in Coupled-VAE than in VAE. To show how Coupled-VAE ameliorates the training dynamics, we also track the gradient norms of Coupled-VAE ($\lambda_{m}=10.0$ for a clearer comparison), plotted along with VAE and DAE in Figure~\ref{fig:gradient-norms-curve}. The curve for Coupled-VAE in Figure~\ref{subfig:curve-derecde} stands for $\left\| \partial (\mathcal{L}_{\itm{rec}} + \mathcal{L}_{\itm{rec}}^{c}) / \partial \bm{e} \right\|_{2}$. We observe that Coupled-VAE receives constantly increasing backpropagated gradients from the reconstruction. In contrast to VAE, the $\left\| \partial \mathcal{L}_{\itm{reg}} / \partial \bm{e} \right\|_{2}$ in Coupled-VAE does not decrease significantly as the KL weight increases. The decrease of $\left\| \partial \bm{h} / \partial \bm{e} \right\|_{F} / \left\| \bm{h} \right\|_{2}$, which VAE suffers from, is not observed in Coupled-VAE. Plots on more datasets are in Appendix~\ref{app:tracking-norms}. \subsection{Sample Diversity} \label{subsec:diversity-sample} We evaluate the diversity of the samples from the prior distribution. We sample 3200 texts from the prior distribution and report the Dist-1 and Dist-2 metrics \cite{LiGBGD16}, which are the ratios of distinct unigrams and bigrams over all generated unigrams and bigrams. Distinct-1 and Distinct-2 in Table~\ref{tab:sampled-outputs} show that texts sampled from Coupled-VAE ($\lambda_{m}=10.0$) are more diverse than those from VAE. Given limited space, we put several samples in Appendix~\ref{app:diversity-sample} for qualitative analysis. \begin{table}[t] \centering \small \begin{tabular}{@{}l@{}cccccc@{}} \toprule \multirow{2}*{} & \multicolumn{2}{c}{PTB} & \multicolumn{2}{c}{Yelp} & \multicolumn{2}{c}{Yahoo}\\ \cmidrule(lr){2-3} \cmidrule(lr){4-5} \cmidrule(l){6-7} ~ & D-1 & D-2 & D-1 & D-2 & D-1 & D-2 \\ \midrule VAE & 4.61 & 16.36 & 0.62 & 2.48 & 0.44 & 2.11 \\ Coupled-VAE \ \ \ & \bf 5.51 & \bf 24.46 & \bf 1.15 & \bf 5.93 & \bf 0.75 & \bf 3.97 \\ \bottomrule \end{tabular} \caption{\label{tab:sampled-outputs} Diversity of samples from the prior distribution. \textit{D-} stands for \textit{Distinct-}, normalized to $[0, 100]$.} \end{table} \subsection{Interpolation} \label{subsec:interpolation} A property of VAE is to match the interpolation in the latent space with the smooth transition in the data space \cite{BowmanVVDJB16}. In Table~\ref{tab:interpolation}, we show the interpolation of VAE and Coupled-VAE on PTB. It shows that compared with VAE, Coupled-VAE has smoother transitions of subjects (\textit{both sides} $\rightarrow$ \textit{it}) and verbs (\textit{are expected} $\rightarrow$ \textit{have been} $\rightarrow$ \textit{has been} $\rightarrow$ \textit{has}), indicating that the linguistic information is more smoothly encoded in the latent space of Coupled-VAE. \begin{table*}[t] \begin{center} \small \begin{tabular}{@{}ll@{}} \toprule \multicolumn{1}{c}{VAE} & \multicolumn{1}{c}{Coupled-VAE ($\lambda_{m}=10.0$)} \\ \midrule \multicolumn{2}{c}{Text A (sampled from PTB): now those routes are n't expected to begin until jan} \\ \midrule \multicolumn{1}{@{}p{7.8cm}@{}}{they are n't expected to be completed} & \multicolumn{1}{@{}p{7.8cm}@{}}{both sides are expected to be delivered at their contract} \\ \multicolumn{1}{@{}p{7.8cm}@{}}{the new york stock exchange is scheduled to resume today} & \multicolumn{1}{@{}p{7.8cm}@{}}{both sides are expected to be delivered at least} \\ \multicolumn{1}{@{}p{7.8cm}@{}}{the new york stock exchange is scheduled to resume} & \multicolumn{1}{@{}p{7.8cm}@{}}{both sides have been able to produce up with the current level} \\ \multicolumn{1}{@{}p{7.8cm}@{}}{it is n't clear that it will be sold through its own account} & \multicolumn{1}{@{}p{7.8cm}@{}}{it also has been used for comment} \\ \multicolumn{1}{@{}p{7.8cm}@{}}{it is n't a major source of credit} & \multicolumn{1}{@{}p{7.8cm}@{}}{it also has been working for the first time} \\ \multicolumn{1}{@{}p{7.8cm}@{}}{it also has a major chunk of its assets} & \multicolumn{1}{@{}p{7.8cm}@{}}{it also has a new drug for two years} \\ \multicolumn{1}{@{}p{7.8cm}@{}}{it also has a major pharmaceutical company} & \multicolumn{1}{@{}p{7.8cm}@{}}{it also has a \$ N million defense initiative} \\ \midrule \multicolumn{2}{c}{Text B (sampled from PTB): it also has a \_unk\_ facility in california} \\ \bottomrule \end{tabular} \caption{\label{tab:interpolation} Latent space interpolation.} \end{center} \end{table*} \subsection{Generalization to Conditional Language Modeling: Coupled-CVAE} \label{subsec:cvae} \begin{figure}[t] \centering \includegraphics[width=\linewidth]{Couple-CVAE.pdf} \caption{A graphical overview of the generalization to Coupled-\textbf{C}VAE. $u$ is the condition, encoded as $\bm{e}_{u}$. The difference from Coupled-VAE is shown in red.} \label{fig:Coupled-cvae} \end{figure} \begin{table}[t] \centering \small \begin{tabular}{@{}l@{}l@{}rrr@{}} \toprule ~ & NLL (KL) \ \ \ & \ PPL & D-1 & D-2 \\ \midrule GRU Encoder-Decoder* & \bf 53.9 (-) & \bf 41.6 & 0.33 & 0.80 \\ \midrule CVAE & 54.0 (3.8) & 41.8 & 0.61 & 2.60 \\ Coupled-CVAE ($\lambda_{m}$=$0.1$) \ \ & 54.1 (4.6) & 42.2 & 0.71 & 3.18 \\ Coupled-CVAE ($\lambda_{m}$=$0.5$) \ \ & 54.2 (5.3) & 42.5 & 0.78 & 3.63 \\ Coupled-CVAE ($\lambda_{m}$=$1.0$) \ \ & 54.3 (6.1) & 42.7 & 0.86 & 4.10 \\ Coupled-CVAE ($\lambda_{m}$=$2.0$) \ \ & 54.6 (7.8) & 43.6 & \bf 0.99 & \bf 5.16 \\ \bottomrule \end{tabular} \caption{\label{tab:cvae-results} Dialogue generation. D-1 and D-2 are normalized to $[0, 100]$. *The exact NLL is reported.} \end{table} To generalize our approach to conditional language modeling, we propose Coupled-\textbf{C}VAE. A graphical overview is displayed in Figure~\ref{fig:Coupled-cvae}. Specifically, the (coupled) posterior network and the (coupled) decoder are additionally conditioned. The objective of Coupled-CVAE is identical to Eq.~(\ref{eq:Coupled-VAE}). We compare Couple-CVAE with GRU encoder-decoder \cite{ChoMGBBSB14} and CVAE \cite{ZhaoZE17} for dialogue generation. We use the Switchboard dataset \cite{Godfrey93}, whose training/validation/test splits are 203K/5K/5K, and the vocabulary size is 13K. For probability estimation, we report the NLL, KL, and PPL based on the gold responses. Since the key motivation of using CVAE in \citet{ZhaoZE17} is the diversity of responses, we sample one response for each post and report the Distinct-1 and Distinct-2 metrics over all test samples. Please find more details of this part in Appendix~\ref{app:coupled-cvae}. Table~\ref{tab:cvae-results} shows that Coupled-CVAE greatly increases the diversity of dialogue modeling, while it only slightly harms the probability estimation capability. It indicates that Coupled-CVAE better captures the one-to-many nature of conversations than CVAE and GRU encoder-decoder. We also observe that the diversity is improved with increasing $\lambda_{m}$, which shows that $\lambda_{m}$ can control diversity via specifying the richness of the latent space. \section{Relation to Related Work} \citet{BowmanVVDJB16} identify the posterior collapse problem of text VAE and propose KL annealing and word drop to handle the problem. \citet{ZhaoZE17} propose the bag-of-words loss to mitigate this issue. Later work on this problem focuses on less powerful decoders \cite{YangHSB17,SemeniutaSB17}, modified regularization objective \cite{HigginsMPBGBML17,BahuleyanMZV19,WangW19}, alternative posterior families \cite{RezendeM15,XuD18,DavidsonFCKT18,XiaoDirichlet18}, richer prior distributions \cite{TomczakW18}, improved optimization \cite{HeSNB19} or KL annealing strategy \cite{FuLLGCC19}, the use of skip connections \cite{DiengKRB19}, hierarchical or autoregressive posterior distributions \cite{ParkCK18,DuLHXBW18}, and narrowing the amortization gap \cite{HjelmSCJCC16,KimWMSR18,MarinoYM18}. We provide the encoder-decoder incompatibility as a new perspective on the posterior collapse problem. Empirically, our approach can be combined with the above ones to alleviate the problem further. A model to be noted is $\beta$-VAE \cite{HigginsMPBGBML17}, in which the reconstruction and regularization are modeled as a hyperparameterized trade-off, i.e., the improvement of one term compromises the other. Different from $\beta$-VAE, we adopt the idea of multi-task learning, i.e., the \textit{coupled reconstruction} task helps improve the encoder chart map and the \textit{signal matching} task helps improve the decoder chart map. Both our analysis in Section~\ref{subsec:incompatibility} and the empirical results show that the modeling of posterior distribution can be improved (but not necessarily compromised) with the additional tasks. \citet{Ghosh19deterministic} propose to substitute stochasticity with explicit and implicit regularizations, which is easier to train and empirically improves the quality of generated outputs. Different from their work, we still strictly follow the generative nature (i.e., data density estimation) of VAE, and the deterministic network in our approach serves as an auxiliary to aid the optimization. Encoder pretraining \cite{LiHNBY19} initializes the text encoder and the posterior network with an autoencoding objective. \citet{LiHNBY19} shows that encoder pretraining itself does not improve the performance of VAE, which indicates that initialization is not strong enough as an inductive bias to learn a meaningful latent space. Given the discrete nature of text data, we highlight the two-level representation learning for text modeling: 1) the encoder and decoder parameterizations via autoencoding and 2) a transition map between the parameterizations. Notably, the transition map has large freedom. In our case, the transition map decides the amount and type of information encoded in the variational posterior, and there are other possible instances of the transition map, e.g., flow-based models \cite{DinhKB14}. \section{Conclusions} In this paper, we observe the encode-decoder incompatibility of VAE for text modeling. We bridge the incompatibility and the posterior collapse problem by viewing the encoder and the decoder as two inadequately learned chart maps from the data manifold to the parameterizations, and the posterior network as a part of the transition map between them. We couple the VAE model with a deterministic network and improve the parameterizations via encoder weight sharing and decoder signal matching. Our approach is model-agnostic and can be applied to a wide range of models in the VAE family. Experiments on benchmark datasets, i.e., PTB, Yelp, and Yahoo, show that our approach improves various VAE models in terms of probability estimation and the richness of the latent space. We also generalize Coupled-VAE to conditional language modeling and propose Coupled-CVAE. Results on Switchboard show that Coupled-CVAE largely improves diversity in dialogue generation. \section*{Acknowledgments} We would like to thank the anonymous reviewers for their thorough and helpful comments. \clearpage
{'timestamp': '2020-04-21T02:24:47', 'yymm': '2004', 'arxiv_id': '2004.09189', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09189'}
arxiv
\section{Introduction} Neural Ordinary Differential equations (neural ODEs) are proposed in~(\cite{chen2018neural}) and model the evolution of hidden representation with ordinary differential equation (ODE). The right-hand side of this ODE is represented with some neural network. If one considers classical Euler scheme to integrate this ODE, then ResNet-like architecture~(\cite{he2016deep}) will be obtained. Thus, Neural ODEs are continuous analogue of ResNets. One of the motivation to introduce such models was assumption on smooth evolution of the hidden representation that can be violated with ResNet architecture. Also, in contrast to ResNet models, Neural ODEs share parameters of the ODE right-hand side between steps to integrate this ODE. Thus, Neural ODEs are more memory efficient. Different normalization techniques were proposed to improve the quality of deep neural networks. Batch normalization~(\cite{ioffe2015batch}) is a useful technique when training a deep neural network model. However, it requires computing and storing moving statistics for each time point. It becomes problematic when a number of time steps required for different inputs vary as in recurrent neural networks~(\cite{hochreiter1997long,cooijmans2016recurrent,ba2016layer}), or the time is continuous as in neural ODEs. We apply different normalization techniques (\cite{salimans2016weight, miyato2018spectral,ba2016layer}) to Neural ODE models and report results for the CIFAR-10 classification task. The considered normalization approaches are compared in terms of test accuracy and ability to generalize if a more powerful ODE solver is used in the inference. \section{Background} The main ingredient of the neural ODE architecture is the ODE block. The forward pass through the ODE block is equivalent to the solve the following initial value problem (IVP) \begin{equation} \begin{cases} \dfrac{\mathrm{d} {\bm{z}}}{\mathrm{d} t} = f({\bm{z}}(t), t, {\bm{\theta}}), \quad t \in [t_0, t_1] \\ {\bm{z}}(t_0) = {\bm{z}}_0, \label{eq:fwd_1} \end{cases} \end{equation} where ${\bm{z}}_0$ denotes the input features, which are considered as initial value. To solve IVP, we numerically integrate system~(\ref{eq:fwd_1}) using ODE solver. Depending on the solver type different number of RHS evaluations of (1) are performed. Initial value problem~(\ref{eq:fwd_1}) replaces Euler discretization for the same right-hand side that arises in ResNet-like architectures. One part of the standard ResNet-like architecture is the so-called ResNet block, which consists of convolutions, batch normalizations, and ReLU layers. In practice, batch normalization is often used to regularize model, make it more robust to training hyperparameters and reduce internal covariate shift~(\cite{shimodaira2000improving}). Also, it is shown that batch normalization yields smoother loss surface and makes neural network training faster and more robust~(\cite{santurkar2018does}). In the context of neural ODEs training, previous studies applied layer normalization~(\cite{chen2018neural}) and batch normalization~(\cite{gholami2019anode}) but did not investigate the influence of these layers on the model performance. In this study, we focus on the role of normalization techniques in neural ODEs. We assume that proper normalization applied to the layers in ODE blocks leads to the higher test accuracy and smoother dynamic. According to~\cite{luo2018differentiable}, different problems and neural network architectures require different types of normalization. In our empirical study, we investigate the following normalization techniques to solve the image classification problem with neural ODE models. \begin{itemize}[leftmargin=*] \item \emph{Batch normalization} (BN;~\cite{ioffe2015batch}) is the most popular choice for the image classification problem, we discuss its benefits in the above paragraph. \item \emph{Layer normalization}~(LN; \cite{ba2016layer}) and \emph{weight normalization}~(WN; \cite{salimans2016weight}) were introduced for RNNs. We consider these normalizations as a ppropriate candidates for incorporating in neural ODEs since they showed its effectiveness for RNNs that also exploit the idea of weights sharing through time. \item \emph{Spectral normalization}~(SN; \cite{miyato2018spectral}) was proposed for generative adversarial networks. It is natural to consider SN for neural ODEs since if the Jacobian norm is bounded by~$1$, one may expect better properties of the gradient propagation in the backward pass. \item We also trained neural ODEs without any normalization (NF). \end{itemize} To perform back-propagation, we use ANODE~(\cite{gholami2019anode}) approach. This is a memory-efficient procedure to compute gradients in neural ODEs with several ODE blocks. This method exploits checkpointing technique at the cost of extra computations. \section{Numerical Experiments} This section presents numerical results of applying different normalization techniques to neural ODEs in the CIFAR-10 classification task. Firstly, we compare test accuracy for neural ODE based models with different types of normalizations. Secondly, we present an \emph{$(\mathcal{S}, n)$-criterion} to estimate quality of the trained neural ODE-like model. The source code is available at GitHub repository\footnote{\url{https://github.com/juliagusak/neural-ode-norm}}. In our experiments we consider neural ODE based models, which are build by stacking standard layers and ODE blocks. After replacing ResNet block with ODE block in ResNet4 model, we get \begin{center} conv $\to$ \emph{norm} $\to$ activation $\to$ ODE block $\to$ avgpool $\to$ fc \end{center} an architecture, which we call \emph{ODENet4}. For this model we test different normalization techniques for \emph{norm} layer and inside the ODE block. Similarly, by replacing in ResNet10 architecture ResNet blocks, which do not change spacial size, with ODE blocks, we get the following model: \begin{center} conv $\to$ \emph{norm} $\to$ activation $\to$ ResNet block $\to$ ODE block $\to$ ResNet block $\to$ ODE block $\to$ avgpool $\to$ fc, \end{center} which we call \emph{ODENet10}. In contract to ODENet4, this model admits different normalizations in place of the \emph{norm} layer, inside ResNet blocks and ODE blocks. We use ANODE to train considered models since it is more robust than the adjoint method (more details see in~\cite{gholami2019anode}). In both forward and backward passes through ODE blocks we solve corresponding ODEs using Euler scheme. For the training schedule, we follow the settings from ANODE~(\cite{gholami2019anode}). In contract to ANODEDEV2~(\cite{zhang2019anodev2}), we include activations and normalization layers to the model. We train considered models for 350 epochs with an initial learning rate equal to 0.1. The learning rate is multiplied by $0.1$ at epoch 150 and 300. Data augmentation is implemented. The batch size used for training is 512. For all experiments with different normalization techniques, we use the same settings. \subsection{Accuracy} In our experiments, we assume that normalizations for all ResNet blocks are the same, as well as for all ODE blocks. Along with these two normalizations, we vary a normalization technique after the first convolutional layer. We report test accuracy for different normalization schedules for ODENet10. Table~\ref{tab:resnet10_acc} presents test accuracy given by ODENet10 model. The best model achieves 93\% accuracy. It uses batch normalization after the first convolutional layer and in the ResNet blocks, and layer normalization in the ODE blocks. Also, we observe that the elimination of batch normalization after the first convolutional layer and from the ResNet blocks leads to decreasing accuracy to 91.2\%. Such quality is even worse than the quality obtained with the model without any normalizations (92\%). \begin{table}[!h] \centering \begin{tabular}{c|ccccc} ODE blocks & BN & WN & SN & NF & LN \\ \hline Accuracy@1 & $0.762$ & $0.925$ & $0.926$ & $0.927$ & $\bm{0.930}$ \end{tabular} \caption{ Comparison of normalization techniques for ODENet10 architecture on CIFAR-10. BN~-- batch normalization, LN~-- layer normalization, WN~-- weight normalization, SN~-- spectral normalization, NF~-- the absence of any normalization. To perform back-propagation, we exploit ANODE with a non-adaptive ODE solver. Namely, we use Euler scheme with $N_t = 8$, where $N_t$ is a number of time steps used to solve IVP~(\ref{eq:fwd_1}). The first row corresponds to the normalization in the ODE blocks. We use BN after the first convolutional layer and inside ResNet blocks, respectively. Standard ResNet10 architecture (only ResNet blocks are used) gives $\bm{0.931}$ test accuracy. } \label{tab:resnet10_acc} \end{table} \subsection{$(\mathcal{S}, n)$-criterion of dynamics smoothness in the trained model} Since in neural ODEs like models, we train not only parameters of standard layers, but also parameters in the right-hand side of the system~(\ref{eq:fwd_1}), the test accuracy is not the only important measure. Another significant criterion is the smoothness of the hidden representation dynamic that is controlled by the trained parameters of the right-hand side~(\ref{eq:fwd_1}). To implicitly estimate this smoothness, we propose an \emph{($\mathcal{S}, n$)-criterion} that indicates whether more powerful solver induces performance improvement of the trained neural ODE model during evaluation. Here, $\mathcal{S}$ denotes a solver name (Euler, RK2, RK4, etc) and $n$ denotes a number of the right-hand side evaluations necessary for integration of system~(\ref{eq:fwd_1}), which corresponds to the forward pass through the ODE block. By more powerful solver we mean ODE solver that requires more right-hand side evaluations to solve~(\ref{eq:fwd_1}) than ODE solver used in training for the same purpose. For example, assume one trains the model with Euler scheme and $n = 2$. Then, we say that ODE block in trained model corresponds to smooth denamics if using Euler scheme with $n > 2$ during evaluation yields higher accuracy. Otherwise, we say that $(\mathcal{S}, n)$-criterion shows the absence of learned smooth dynamics. Worth noting that the $(\mathcal{S}, n)$-criterion has limitation. Namely, it requires the solution of IVP~(\ref{eq:fwd_1}) to be a Lipchitz function of the right-hand side~(\ref{eq:fwd_1}) parameters and inputs~(\cite{coddington1955theory}). Otherwise, we can not rely on this criterion since the closeness in the right-hand side parameters does not induce the closeness of features that are inputs to the next layers of the model. In our experiments we consider ODENet4 architecture with four different settings of the Euler scheme: $n = 2, 8, 16, 32$. For each setting we have trained 10 types of architectures that differ from each other by the type of normalization we apply to the first convolutionl layer and convolutional layers in the ODE block. For example, the model named ``ODENet4 BN-LN (Euler, 2)'' means the following: we have used ODENet4 architecture, where after conv layer follows a BN layer, after each convolutional layer in the right-hand side~(\ref{eq:fwd_1}) follows an LN layer, and Euler scheme with 2 steps is used to propagate through the ODE block. For a fixed model trained with (Euler, $n_0$) solver we check the fulfillment of $(\mathcal{S}, n)$-criterion by evaluating its accuracy with more powerful solver. In this case, we consider the following more powerful solvers: (Euler, $n$), (RK2, $n$) and (RK4, $n$), where $n > n_0$. In Figure~\ref{fig:resnet4_acc}, we show how test accuracy given by ODENet4 model with different normalizations changes with varying ODE solvers to integrate IVP~(\ref{eq:fwd_1}) in ODE blocks. Different line types correspond to different solver type (Euler, RK2, RK4), $x$-axis depicts the number of the right-hand side evaluations, while $y$-axis stands for the test accuracy. These models were trained with Euler scheme and after that we use Euler, RK2 and RK4 schemes to compute test accuracy. Every row from top to bottom corresponds to $n=2,16,32$ used in Euler scheme. \begin{figure}[!h] \centering \includegraphics[width=\linewidth]{sn_crit_plot_legend.png} \caption{Illustration of how the choice of ODE solver and normalizations during training implicitly affects the smoothness of learned dynamics. Each subplot corresponds to the model trained with a fixed ODE solver and normalization scheme. Models within one row have the same type of training solver ((Euler, $n$), $n = 2, 16, 32$ from top to bottom). Models within one column have the same normalization technique. For example, subplot in the third row and the second column corresponds to the ODENet4 model trained with (Euler, 32) solver with BN after the first convolutional layer and LN after convolutional layers inside ODE block. Lines of different style corresponds to different types of test solvers. If model accuracy does not drop when the more powerful ODE solver is used, we conclude that, according to ($\mathcal{S}, n$)-criterion, the model provides a smooth dynamics. For example, the model (Euler, 32) BN-LN trains a smooth dynamics, while (Euler, 2) BN-LN fails to do that. Also, we can observe that to learn the smooth dynamics during training, for some normalization schemes less powerful solvers are required. If we compare BN-LN and BN-WN models, we can see that the first one learns smooth dynamics when Euler with $n = 16$ is used, but the latter one does that only for $n = 32$. } \label{fig:resnet4_acc} \end{figure} \section{Discussion and Further research} We have empirically investigated the effect of normalization techniques to ODE based models. For different models, we have compared test accuracy as well as the ability to learn parameters that yield smooth dynamics of hidden representations. We have observed that both normalization and type of training solver affect the performance of the final model. Worth noting that pre-trained models, which are close in terms of test accuracy, can significantly differ when it comes to the smoothness of the hidden representations dynamics. In our further research, we plan to investigate how different tasks benefit from the presence of smoothness in hidden representations. Also, we will work on a more rigorous theoretical criterion that can be used to compare ODE based models, considering both neural networks and ODEs metrics. \section*{Acknowledgement} Sections 2 and 3 were supported by Ministry of Education and Science of the Russian Federation grant 14.756.31.0001. High-performance computations presented in the paper were carried out on Skoltech HPC cluster Zhores.
{'timestamp': '2020-04-29T02:03:27', 'yymm': '2004', 'arxiv_id': '2004.09222', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09222'}
arxiv
\section{INTRODUCTION} Fruit production that requires selective harvesting is heavily reliant on human labour \cite{xiong2018design}. This is applicable to crops such as strawberries, sweet peppers, tomatoes, cucumbers, etc. Labour represents the largest cost and also a large operational uncertainty for fruit growers \cite{yamamoto2014development}. Therefore, several attempts have been made to develop a robotic solution for selective harvesting of fruits. Some fruits, such as strawberries and tomatoes, tend to grow in clusters. This makes it difficult to identify and pick individual ripe fruit without damaging or accidentally picking unripe fruit \cite{xiong2019jfr, yamamoto2014development}. Harvesting fruits that grow in clusters or are surrounded by obstacles, such as branches and/or leaves, while leaving the other fruits to remain undamaged on the plant, is one of the primary challenges for fruit harvesting systems \cite{xiong2019jfr, yaguchi2016development}. The surrounding fruits, leaves, stems and other obstacles are often difficult to separate from the target, both in terms of detection and in manipulation. In agricultural robotics field, many researchers try to avoid obstacles in both vision and manipulation. To avoid occlusions in sweet pepper picking, a “3D‐move‐to‐see” method was proposed to find the best view with fewer occlusions \cite{lehnert20183d}. To avoid obstacles, a method for cucumber picking was developed that uses a search algorithm to explore the search space for a feasible trajectory, in which each step of the trajectory is checked by a collision detector \cite{van2002autonomous}. Most of the methods found in the literature are passive obstacle avoidance methods, in which the aim is to avoid existing obstacles without changing the environment. However, obstacles are not always avoidable, especially when picking small‐size fruits in clusters, where the obstacles may be extremely close to the targets. Our previous work presented a gripper for strawberry harvesting that can open fingers to enclose a target from below \cite{xiong2018design}. Without moving the obstacles out of the way, obstacles may prevent the gripper from capturing the target and may also be swallowed with the target if they are located close to the target. Similar problems occur when approaching the fruit from other angles. To solve this issue, in a later work \cite{xiong2019jfr}, we proposed to use a single linear push operation to push aside the obstacles below the target based on the obstacle sensing from a 3D camera. We found that pushing obstacles aside, rather than simply avoiding them makes it possible to pick fruit that would otherwise be inaccessible to the robot. However, a single linear push may be insufficient for dense obstacles from multi-direction with respect to the target, since the linear push moves towards only one direction. Also, the obstacles may be adjacent together that can not be separated during the single push. Furthermore, the gripper may not be able to swallow the whole target but push it up due to the static contact force between the target and obstacles. In addition to that, one frequent failure is the gripper may capture obstacles above the target when it moves up to detach the fruit, which has not been addressed in the previous work. In the field of robotic manipulation, most studies focus on obstacle avoidance. Nevertheless, we found some research working on obstacle separation for simple situations. For a warehouse picking application on desk environment, two linear pushing policies were proposed to separate rigid obstacles during the way of the gripper reaching a target bin \cite{danielczuk2018linear}. Another work used Learning from Demonstration (LfD) algorithm for the same application that involves a pushing action \cite{laskey2016robot}. For a similar situation, researchers proposed to use physical engine to calculate the dynamics to predict the object locations for motion planning, which also involves pushing motions \cite{kitaev2015physics, moll2017randomized, dogar2013physics}. Reinforcement learning was also used to train a robot to rearrange objects on a desk using pushing method to make them sparse for individual grasping \cite{zeng2018learning}. However, all these methods were tested at simple environment where some rigid objects were placed on a 2D desk surface. In the agricultural environment, for example strawberry plants, fruits are located in 3D within diverse and unconstrained environments. The flexible peduncles, deformable fruits and many other crop variations make the dynamics difficult to calculate and predict. Moreover, the operation speed of these methods seem very slow, which may not be suitable for fruit harvesting. This paper provides the improvements to our previously proposed obstacle separation method \cite{xiong2019jfr}. We extend the pushing policies by adding a zig-zag push and a novel drag operation. We also propose an image processing pipeline to implement the method on a harvesting robot. The proposed method might be also applicable to harvest other fruits, such as tomatoes and cucumbers. \section{Methods} \subsection{Region of Interest} \label{RoI} \begin{figure} [ht] \centering \includegraphics[width=\linewidth]{Figure2_2.pdf} \caption{Region of interest area around the target to determine the presence of obstacles.} \label{fig:fig2} \end{figure} The obstacle separation trajectory is generated according to the visual perception of the obstacle information around the target. We select a region of interest (RoI) area around the target to determine the presence of the obstacles. The RoI comprises a volume of 3D point cloud that contains the target fruit and potentially one or more obstacles. As shown in Fig. \ref{fig:fig2}, the RoI area can be divided into four horizontal layers: a top layer 1, an upper-central layer 2, a lower-central layer 3 and a bottom layer 4. As the top view is shown in Fig. \ref{fig:fig2}, each layer of the RoI is further segmented into nine cuboid blocks. On each layer, the blocks are arranged in a 3x3 grid that has its center at the horizontal midpoint of the target strawberry such that the central block $\textit{\textbf{C}}_{\mathrm{C}}$ encompasses the position of the target strawberry in the \textit{xy} plane. To generate the separation paths, each block is assigned a horizontal vector representative of the direction from the block to the central block $\textit{\textbf{C}}_{\mathrm{C}}$. The direction of the vector is determined by the position of the block so that all vectors are directed from the center of the corresponding block towards the center of the central block $\textit{\textbf{C}}_{\mathrm{C}}$. We use the number of points $N$ in the block of point cloud to determine whether there are obstacles present in the block or not. The gripper is instructed to operate in three distinct stages. As the gripper is picking from below, during the first stage, the gripper moves obstacles horizontally within layer 4. During the second stage, the device moves up to swallow the target and separates the obstacles within layer 2 and layer 3. During the third stage, the gripper drags the target into a picking position with fewer obstacles if the central block $\textit{\textbf{C}}_{\mathrm{C}}$ in layer 1 is occupied. The detailed separation policies will be elaborated in the below sections. \subsection{Horizontal Push} The first stage is to separate the obstacles horizontally under the target in layer 4. Compared to our previous method \cite{xiong2019jfr}, we add a zig-zag pushing policy in addition to the single push. A single push means that the gripper linearly pushes the obstacles aside once, starting from the region with fewer obstacles. A zig-zag push is a motion where the gripper uses a zig-zag movement that contains several linear motions to push the obstacles side to side. This motion can not only move the obstacles out of the way, but also break the static contact force, such as shaking to insert a key. However, a single push is generally faster than the zig-zag push and can reduce the likelihood of the damage to the fruit. Therefore, we only use the zig-zag push in more complex situation, depending on the number and distribution of the obstacles in layer 4. \subsubsection{Single Push} \begin{figure} [ht] \centering \includegraphics[width=3in]{Figure3.jpg} \caption{Singe push to move the obstacles under the target in layer 4} \label{fig:fig3} \end{figure} As shown in Fig. \ref{fig:fig3}(a), if an obstacle is located below the target (layer 4), the gripper may capture the obstacles if it moves up straightly to enclose the target. In this case, the gripper can use a single push operation to push aside the obstacle (to the right in the figure) before swallowing the target (Fig. \ref{fig:fig3}(b) and (c)). \begin{figure} [ht] \centering \includegraphics[width=\linewidth]{Figure4_3.pdf} \caption{Diagram of the calculation of horizontal push: (a) single push, where the red arrow is the pushing direction; (b) zig-zag push, where the red arrow shows the overall direction and the blue arrows are the zig-zag paths.} \label{fig:fig4_3} \end{figure} Since the gripper size is limited, a single push operation makes it easier to move a few number of adjacent obstacles out of the way, but hard to separate sparsely distributed obstacles. Therefore, ignoring the central block, we use the number of blocks $n_{h}$ within the largest group of adjacent unoccupied blocks (without obstacles) to determine whether to use a single push or zig-zag operation. As shown in Fig. \ref{fig:fig4_3}(a), ignoring the central block, filled arrows in the blocks mean the blocks are occupied with obstacles, while the blank arrows represent unoccupied blocks. In this case, the $n_{h}$ is 5 and greater than a predetermined threshold $t_{h}$ (using 4 in this paper), so a single push operation is appropriate to push the obstacles aside. As the pushing operation is moving towards the obstacles, the direction of the single push operation for the gripper is calculated based on the positions of the occupied blocks according to the following equation: \begin{equation} \textit{\textbf{D}}_{\mathrm{single}}= -r\Sigma_{1}^n\textit{\textbf{O}}_{i}/|\Sigma_{1}^n\textit{\textbf{O}}_{i}|, \quad n_{h}>=t_{h}\\ \label{eq:eq1} \end{equation} where, $\textit{\textbf{O}}_{i}$ is the vector of the $i^{th}$ occupied block within the largest group of adjacent occupied blocks and $n$ is the total number of blocks within the largest group of adjacent occupied blocks. The parameter $r$ is used to scale the $\textit{\textbf{D}}_{\mathrm{single}}$ norm, which should guarantee that the gripper pushes from the outside of the blocks (50 mm is used for the current system). The red arrow in Fig. \ref{fig:fig4_3}(a) shows the calculated pushing direction for the single push operation. It can be seen that the gripper moves from the center of the unoccupied blocks to the center of the occupied blocks, such that the gripper has the highest possibility to move all the obstacles out of the way. \subsubsection{Zig-zag Push} Ignoring the central block, if the number $n_{h}$ of the largest group of adjacent unoccupied blocks comprises fewer than the threshold number $t_{h}$ of blocks, the method determines that a horizontal zig-zag push operation is appropriate. Fig. \ref{fig:fig4_3}(b) shows a case where a zig-zag operation is selected to push the obstacles side to side. The red arrow is the overall direction of the operation, while the blue arrows are the zig-zag paths. Since the zig-zag operation involves three directions of movement (forward, left and right), the gripper can push the three directions of obstacles out of the way. Therefore, it makes sense that the gripper moves from the entrance which contains fewer obstacles. Hence, different from the single push, the overall direction of the zig-zag push operation is calculated based on the positions of the unoccupied blocks according to the following equation: \begin{equation} \textit{\textbf{D}}_{\mathrm{zigzag}}= r\Sigma_{1}^m\textit{\textbf{U}}_{j}/|\Sigma_{1}^m\textit{\textbf{U}}_{j}|, \quad n_{h}<t_{h}\\ \label{eq:eq2} \end{equation} where, $\textit{\textbf{U}}_{j}$ is the vector of the $j^{th}$ unoccupied block within the largest group of adjacent unoccupied blocks and $m$ is the total number of blocks within the largest group of adjacent unoccupied blocks. The norm of $\textit{\textbf{D}}_{\mathrm{zigzag}}$ is scaled using the same parameter $r$ as Eq. \ref{eq:eq1}. During a horizontal zig-zag push operation, the device moves in the $xy$ plane, wherein the resultant vector of the zig-zag motion is equal to $\textit{\textbf{D}}_{\mathrm{zigzag}}$ and the amplitude $a_{h}$ and number of pushes $n_{hp}$ of the zig-zag motion are determined according to the specific picking scenario. For example, the effectiveness of the values may be affected by the peduncle length, fruit weight or the damping ratio of the fruit, which are difficult to calculate. Based on some tests in the farm, in the current system, we tune the $a_{h}$ and $n_{hp}$ to fix values of 20 mm and 5, respectively. \subsection{In-hand Drag Operation Above The Target} \begin{figure} [ht] \centering \includegraphics[width=\linewidth]{Figure5.jpg} \caption{Drag operation to avoid capture the obstacles: an upward drag step moves the target to an area that contains fewer obstacles ((a) and (b)); an upward push-back step pushes the upper obstacles aside (c) before closing the fingers (d).} \label{fig:fig5} \end{figure} If an obstacle is located above the target (layer 1), such as the case shown in Fig. \ref{fig:fig5}(a), the gripper may swallow or damage the obstacles when moving upward to capture the target strawberry. Furthermore, the obstacles may stop the fingers closing thus resulting in cutting failure of the target peduncle. To solve this problem, we propose an in-hand drag operation, which is opposite to the push operation as used in other layers. The drag operation allows the gripper to pick the target fruit without capturing unwanted obstacles. The operation comprises an upward drag step to move the target to an area that contains fewer obstacles (Fig. \ref{fig:fig5}(b)) and an upward push-back step that pushes the upper obstacles aside (Fig. \ref{fig:fig5}(c)) before closing the fingers. The push-back step is necessary because when at the drag position (Fig. \ref{fig:fig5}(b)), the peduncle is inclined such that the fruit is difficult to fall due to the static force and easily damaged when the gripper moves up further towards a cutting position. \begin{figure} [ht] \centering \includegraphics[width=\linewidth]{Figure5_2.pdf} \caption{Diagram of the calculation of the drag operation: (a) a top view shows the calculation of the drag direction $\textit{\textbf{D}}_{\mathrm{drag}}$ in $xy$ plane; (b) a left side view shows the drag and push-back paths (blue arrows).} \label{fig:fig5_2} \end{figure} The drag operation is performed only when there are obstacles in the central block $\textit{\textbf{C}}_{\mathrm{C}}$ of the top layer. If the $\textit{\textbf{C}}_{\mathrm{C}}$ is unoccupied, the gripper moves directly upwards to pick the target strawberry. Fig. \ref{fig:fig5_2} shows the diagram of the calculation method of the drag operation with corresponding to the example in Fig. \ref{fig:fig5}. As shown in Fig. \ref{fig:fig5_2}(a), to avoid the collision between the gripper and the table, the three blocks $\textit{\textbf{L}}_{\mathrm{R}}$, $\textit{\textbf{C}}_{\mathrm{R}}$, $\textit{\textbf{R}}_{\mathrm{R}}$ that are close to the table are skipped for the calculation of the drag direction. Then the drag direction $\textit{\textbf{D}}_{\mathrm{drag}}$ in the $xy$ plane can be determined according to the following equation: \begin{equation} \label{eq:eq5} \textit{\textbf{D}}_{\mathrm{drag}}=l\Sigma_{1}^m\textit{\textbf{U}}_{j}/|\Sigma_{1}^m\textit{\textbf{U}}_{j}| \end{equation} where, $\textit{\textbf{U}}_{j}$ is the vector of the $j^{th}$ unoccupied block within the largest group of adjacent unoccupied blocks. The blocks used for calculation are $\textit{\textbf{L}}_{\mathrm{C}}$, $\textit{\textbf{L}}_{\mathrm{F}}$, $\textit{\textbf{C}}_{\mathrm{F}}$, $\textit{\textbf{R}}_{\mathrm{F}}$, $\textit{\textbf{R}}_{\mathrm{C}}$. The parameter $m$ is the total number of blocks within the largest group of adjacent unoccupied blocks. The norm of $\textit{\textbf{D}}_{\mathrm{drag}}$ is scaled to $l$ (50 mm is used in the current system). If all blocks are occupied by obstacles, the drag direction is aligned to $\textit{\textbf{C}}_{\mathrm{F}}$, where there are fewer obstacles in general. Fig. \ref{fig:fig5_2}(b) shows the drag and push-back steps, wherein the drag and push-back operations moves up the same height in the vertical direction. \section{EXPERIMENTS} \subsection{Image Processing} \begin{figure*} [b!] \centering \includegraphics[width=\linewidth]{Figure7.jpg} \caption{The workflow of the fruit detection and obstacle determination: (a) original point cloud captured by an RGB-D camera; (b) 3D HSI color thresholding to remove the adjacent noise points from the background; (c) using deep learning to detect the ripe strawberries in an RGB image; (d) fruit localization and obstacle determination in 3D point cloud.} \label{fig:fig7} \end{figure*} The image processing includes the detection and localization of ripe strawberries and also the determination of obstacles within the RoI for each target. An RGB-D camera (D435; Intel, USA) was used for image acquisition. The image processing pipeline contains three steps: 1) 3D color thresholding to remove noise points from the background, 2) object detection and localization using deep learning based on our previous work \cite{ge2019access} and 3) obstacle calculation. Fig. \ref{fig:fig7}(a) shows the original point cloud, where some pieces of points from the table (silver) and irrigation tubes (black) are around the strawberries. In fact, the table and irrigation tubes are behind the berries at a distance of about 150 mm. The inaccurate depth sensing results in some of the points connecting to the front berries, which may be regarded as obstacles. To avoid this influence, the first step is to remove the adjacent noise points (silver and black) by using hue, saturation and intensity (HSI) color thresholding, as the result is shown in Fig. \ref{fig:fig7}(b). This step is performed in point cloud using the \textit{jsk\_pcl\_ros} ROS package. The second step is the detection and localization of the ripe strawberries. As shown in Fig. \ref{fig:fig7}(c), we use an instance segmentation convolutional neural network Mask R-CNN to segment the objects in pixel level such that the 3D location of the ripe strawberries can be obtained by matching with depth images \cite{ge2019access}. The detection system outputs the 3D bounding boxes of the target strawberries and the thresholded point cloud for further obstacle calculation, as shown in Fig. \ref{fig:fig7}(d). The obstacles around the target is determined based on the method described in Section \ref{RoI}. To calculate the number of points in each block, we crop the bounding box of each RoI block in point cloud using the \textit{CropBox} function in the Point Cloud Library (PCL). Fig. \ref{fig:fig7}(d) shows the obstacle bounding boxes (white) around a target, where only blocks occupied with obstacles are displayed. \subsection{Field Test Setup} \begin{figure} [ht] \centering \includegraphics[width=2.3in]{Figure6_2.png} \caption{The newly developed U-shaped strawberry-harvesting robot on a farm: inner view of the picking system (NORONN, \url{www.noronn.com}).} \label{fig:fig6} \end{figure} We conducted two sets of experiments in two places: a greenhouse at the Boxford Suffolk Farms (England) and a university experimental tunnel at the Norwegian University of Life Sciences (Norway). The tests were carried out on strawberry cultivars of ``Malling Centenary" in England and ``Murano" in Norway. Generally, ``Malling Centenary" is easier for obstacle separation because most of the berries have long and independent peduncles, while ``Murano" berries have more clusters with short peduncles growing on one stem. The different biological characteristics may result in different performance of the robot. The field tests were performed on our newly developed U-shaped strawberry-harvesting robot with a newly developed SCARA-like arm, as shown in Fig. \ref{fig:fig6}. \begin{figure*} [b!] \centering \includegraphics[width=\linewidth]{Figure8_3.pdf} \caption{Examples of the obstacle separation in the field test: each row of images represents a picking case, where the first (left) image shows the detection and localization of target and obstacles and the last image (right) displays the 3D path of the gripper.} \label{fig:fig8} \end{figure*} \subsection{Results} \subsubsection{Application examples} Fig. \ref{fig:fig8} demonstrates two examples of using the proposed obstacle separation method in different situations. In Fig. \ref{fig:fig8}(a), a green obstacle is located above the target, which may be mis-captured when the gripper is open to capture the target. Fig. \ref{fig:fig8}(a-1) shows that there are no obstacles in layer 2, 3 and 4, but in layer 1, the central block $\textit{\textbf{C}}_{\mathrm{C}}$ and three other blocks $\textit{\textbf{L}}_{\mathrm{C}}$, $\textit{\textbf{L}}_{\mathrm{F}}$ and $\textit{\textbf{C}}_{\mathrm{F}}$ are occupied with obstacles, so based on Eq. \ref{eq:eq5}, a drag operation is required. As there are no obstacles in layer 2, 3 and 4, the gripper moves up directly to enclose the target, as shown in Fig. \ref{fig:fig8}(a-2) and (a-3). After holding the target, the gripper drags the target to the front-right region while moving upward where it contains fewer obstacles (Fig. \ref{fig:fig8}(a-4)). At this position, if the gripper continues to move up, it might be difficult for the target to fall down towards a cutting position because the peduncle is inclined and the target has a contact force with the fingers. It may also damage the target with such a force. Therefore, in Fig. \ref{fig:fig8}(a-5), the gripper pushes back to the central position while moving up for further fruit detachment (Fig. \ref{fig:fig8}(a-6)), in which the upper obstacles are pushed aside. The blue line in Fig. \ref{fig:fig8}(a-7) shows the recorded 3D trajectory of the gripper during the operation, while the red line is the trajectory projection on the $xy$ plane, from which we can see that the gripper drags the target to $-y$ and $+x$ direction and then moves back. In the last image of each case, paths 1, 2 and 3 represent the three stages of operations in the bottom layer, central layers and top layer, respectively. Fig. \ref{fig:fig8}(b) demonstrates one more examples of the obstacle separation algorithm with more obstacles in the central layers and bottom layer. Only two blocks ($\textit{\textbf{L}}_{\mathrm{R}}$ and $\textit{\textbf{C}}_{\mathrm{R}}$) in layer 4 are unoccupied with obstacles for the target in Fig. \ref{fig:fig8}(b-1). Therefore, the gripper uses the horizontal zig-zag push from the left rear to right front (the red line in Fig. \ref{fig:fig8}(b-7) shows the direction) to push the obstacles side to side, as can be seen in Fig. \ref{fig:fig8}(b-2) to (b-4). Then, the gripper continues to use an upward zig-zag push operation to separate the obstacles in the central layers (Fig. \ref{fig:fig8}(b-5) and (b-6)). Without this operation, the target and the obstacles may not be separated but pushed up together due to the contact force between each other. \subsubsection{Performance test and failure cases} We recorded the test data in England and Norway under different settings to analyze the feasibility and performance of the obstacle separation method. The tests in England only show the results using the obstacle separation method, while in Norway, we conducted a comparison test, using and without using the obstacle separation method. For each setting, we implemented 100 attempts for the detected targets. Also, as the focus in this study is the obstacle separation method, only the targets with obstacles were used for the tests. This may result in a lower success rate compared to our previous reports, because the robot has a good performance on isolated strawberries \cite{xiong2018design}. \begin{figure} [ht] \centering \includegraphics[width=3in]{Figure9.pdf} \caption{Comparison of success rates in different layers under different settings.} \label{fig:fig9} \end{figure} Fig. \ref{fig:fig9} reports the success rates in each stage and also the whole process under different settings. The whole process means the manipulation in the whole three stages in the bottom layer, central layers and top layer. In each independent stage, we only considered the results with obstacles in the corresponding layers, while a whole process may contain zero obstacle in one or two stages but at least one obstacle in all the layers. The success in the whole process means that in all the stages the separation is successful. Generally, the comparison tests in Norway show that the obstacle separation method is effective compared to the attempts without using the obstacle separation method. Also, the variety of ``Malling Centenary" tends to be easier to be picked compared to ``Murano". To be more precise, the comparison tests show that the drag operation in the top layer is most effective, increasing the success rate from 42.3\% to 75.5\% in the Norway tests. The bottom layer is the easiest layer in terms of obstacle separation. This might be attributed to the gripper design, since the opening action of the fingers under the target can help to push the obstacles aside. The success rate of the whole process is relatively low compared to the operation in the individual layer. For the test on ``Murano", the success rate of the whole process increases from 22.2\% to 45.6\% by using the separation method. The same separation method shows a better performance (65.1\%) on the variety of ``Malling Centenary". \section{CONCLUSIONS} We present an active obstacle separation method for selectively picking a target fruit surrounded by obstacles. Different from the traditional obstacle avoidance methods, the proposed separation method combining push and drag motions to actively separate obstacles from the target based on 3D visual perception. In addition to the old single linear push, a zig-zag push operation that contains several linear pushes was used for both bottom layer and central layers of the target, which is able to separate more dense obstacles. Moreover, the generated side-to-side motion can break the static contact force between the target and obstacles, thus making it easier for the gripper to receive the target. Furthermore, we proposed a novel drag operation to address the issue of mis-capturing obstacles located above the target, in which the gripper drags the target to a place with fewer obstacles and then pushes back to move the obstacles aside for further detachment. The separation paths are calculated based on the number and distribution of the obstacles. Also, an image processing pipeline was developed to implement the method on a harvesting robot. Field tests showed that the proposed method can improve the picking performance substantially. The performance may be further improved by incorporating a closed-loop vision guided manipulation system. A video of the field experiments can be found at \url{https://drive.google.com/file/d/15BO2_4aaR5KHxbgOJQ9fV76zf0_i4GJs/view?usp=sharing}. \bibliographystyle{IEEEtran}
{'timestamp': '2020-04-21T02:26:04', 'yymm': '2004', 'arxiv_id': '2004.09233', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09233'}
arxiv
\section{Introduction} Message Passing Interface MPI \cite{mpi-forum} is a de facto standard framework for distributed computing in many HPC applications. MPI collective operations involve a group of processes communicating by message passing in an isolated context, known as a communicator. Each process is identified by its rank, an integer number ranging from $0$ to $P-1$, where $P$ is the size of the communicator. \textit{Allreduce} is a complex collective operation that performs a combination of vectors owned by processes into a result vector which is distributed back to the processes. In MPI \textit{Allreduce} operation can be accessed by calling \code{MPI\_Allreduce()} function. Five-year profiling of HPC applications running in production mode \cite{Rabenseifner99} at the University of Stuttgart revealed that more than 17\% of the time was spent in the \code{MPI\_Allreduce()} function and that 28\% of all execution time was spent on program runs that involved a non-power-of-two number of processes. The average size of the data array involved in \textit{Allreduce} is about 425 Bytes which makes special demands on the \textit{Allreduce} performance shown for small data sets. Recently one more application for the \textit{Allreduce} operation has emerged. Distributed training of Deep Neural Networks (DNN) \cite{DDL01, DDL02, DDL03, DDL04} uses \textit{Allreduce} operation to synchronize neural network parameters between separate training processes after each step of gradient descent optimization. This new application involves data sets of medium and big sizes which depends on a particular neural network model bringing new requirements to the \textit{Allreduce} performance. \begin{comment} Combination operation in general may be neither associative nor commutative, in such case the only way to perform \textit{Allreduce} is to gather all data vectors by a single process, perform combination (reduction) and broadcast the result back to other processes. If associative functions are considered then it is possible to perform the reduction in parallel getting the result vector distributed across all processes, finally to get a complete result vector on each process an \textit{Allgather} operation is required. Addition of a commutativity property simplifies the algorithm even more since the order of operations becomes unimportant. For brevity we assume only both associative and commutative combination functions leaving other cases for future work. \end{comment} The \textit{Allreduce} operation has been studied well in recent years, and many algorithms were proposed which behave differently depending on data size, network parameters and the number of processes. Ring algorithm \cite{Barnett93,Patarasuk09} performs \textit{Allreduce} optimally in terms of bandwidth, it is a so-called bandwidth-optimal algorithm, but requires a linear number of steps $2(P-1)$, so it is suitable only for big-sized tasks. Recursive Halving algorithm proposed in \cite{Rabenseifner04} is also bandwidth-optimal but can be done in a logarithmic number of steps $2\log(P)$ (here and further in the paper $\log(P)$ stands for $\log_{2}(P)$). Recursive Doubling algorithm \cite{Thakur05} performs the \textit{Allreduce} operation in the minimal possible number of steps - $\log(P)$, it is a so-called latency-optimal algorithm, but it has a considerable overhead in terms of bandwidth so it can be used effectively only for small messages. A hybrid approach allows combining Recursive Doubling and Recursive Halving to vary the number of steps from $\ceil{\log(P)}$ for the latency-optimal version to $2\ceil{\log(P)}$ for the bandwidth-optimal version. A general approach is to start the reduction phase with the bandwidth-optimal algorithm and when the data size to be exchanged becomes small enough to switch to the latency-optimal version. Thus the number of steps can be decreased by the cost of additional bandwidth overhead. Recursive Doubling, Recursive Halving, and Hybrid algorithms work only for the power-of-two number of processes and require additional work in the general case. We propose a generalization for the \textit{Allreduce} operation based on \textit{group theory} which enables the development of a generalized algorithm successfully solving the problem of non-power-of-two number of processes. Our solution works optimally for any number of processes and can vary the number of steps, trading off latency for bandwidth, even for a prime number of processes. The main goal of this paper is to introduce the novel approach for communication description and the \textit{Allreduce} algorithm with better performance than state-of-the-art solutions for non-power-of-two number of nodes. Figure \ref{fig:estimation-new-to-existing} demonstrates an expected ratio between the time estimation for the proposed algorithm $\tau$ using \eqref{eq:bo_cost}, \eqref{eq:intemediate_cost}, \eqref{eq:lo_cost} and the best estimation for state-of-the-art solutions (Ring, Recursive Halving and Recursive Doubling): $\tau_{best}=min(\tau_{RD}, \tau_{RH}, \tau_{Ring})$. All estimations are made for network parameters given in Table \ref{tab:p2p_params}. \begin{figure}[h!] \centering \includegraphics[scale=0.15]{images/estimation-new-to-existing.pdf} \caption{The relationship between the time estimation for the proposed algorithm calculated by \eqref{eq:bo_cost}, \eqref{eq:intemediate_cost}, \eqref{eq:lo_cost} and the best estimation for state-of-the-art algorithms: Ring, Recursive Halving and Recursive Doubling. The proposed algorithm demonstrates the biggest speed-up for the intermediate data sizes where trading-off bandwidth for latency matters. For very large data sets the advantage over the bandwidth-optimal Ring algorithm becomes negligible. Each curve has two discontinuity points which correspond to switching between state-of-the-art algorithms - the first from Recursive Doubling to Recursive Halving and second from Recursive Halving to Ring. } \label{fig:estimation-new-to-existing} \end{figure} \section{Communication model} \label{comm_model} To model the communication and computation cost of algorithms, we use a cost model as in Chan et al. \cite{Chan07}: \begin{displaymath} \tau_{p2p} = \alpha + \beta m + \gamma{m}, \end{displaymath} where $\alpha$ is the latency term, $\beta$ is the bandwidth term, $m$ is the message size and $\gamma$ is a computation speed. Most of the presented algorithms divide the initial data vector into $P$ parts. For brevity, we assume that all parts are of equal size: $u=m/P$. We assume a peer-to-peer network with full-duplex channels, so there are no network conflicts for any cyclic communication pattern. We don't consider any effects caused by particular hardware and network protocol since all possible optimizations related to specific hardware can be adopted for the presented algorithm also. \section{Related work} General ideas of so-called butterfly algorithms were described in the works of Van de Geijn \cite{Geijn91}, Barnett et al. \cite{Barnett93} and were further developed by Rabenseifner et al. \cite{Rabenseifner04}, Chan et al. \cite{Chan04}, Traff \cite{Traff05} and Thakur et al. \cite{Thakur05} into the bandwidth-optimal Recursive Halving and the latency-optimal Recursive Doubling. It will be shown in the following sections that both algorithms are special cases of the proposed algorithm. Hybrid algorithms described in \cite{Geijn91,Barnett93,Bruck93,Rabenseifner04,Chan04,Chan07} combine bandwidth- and latency-optimized algorithms to smoothly change the total number of steps. The main problem with the presented butterfly algorithms is that they work only for the power-of-two number of processes case (or the power-of-$(k+1)$ case for k-port systems). There are several workarounds for the non-power-of-two number of processes problem. The straightforward solution is to reduce the number of processes to the largest power-of-two $P' < P$ by adding preparation and finalization steps \cite{Barnett93,Bruck93}. At the preparation step excess processes send their data to the processes which perform \textit{Allreduce} and receive the result at the finalization step. This solution requires additional $2m$ data to be sent and the number of steps becomes suboptimal in case of Recursive Doubling. Rabenseifner et al. \cite{Rabenseifner04} introduced a 3-2 elimination protocol which can be plugged into the high-level algorithm such as Recursive Halving to deal with a non-power-of-two number of processes it decreases the overhead to $3/2m$. Our solution doesn't require nor preparation nor finalization steps and thus introduce no overhead. When combination function is commutative data dissemination algorithms were adopted to perform the reduction \cite{Han88,Hensgen88,Walter92}. These algorithms utilize cyclic communication patterns to distribute information across all processes. Further development of this approach can be found in \cite{End16} where authors proposed a way to use pairwise data exchange paying with bandwidth and latency overhead. These approaches doesn't provide an optimal solution in the non-power-of-two case. A latency-optimal algorithm based on cyclic communication patterns is described in \cite{Barnoy93}. It also works only with commutative combination function but requires $\ceil{\log{P}}$ steps for any number of processes. This algorithm is optimal in terms of bandwidth and latency but introduces unnecessary computational overhead, moreover, it provides only latency-optimal version which is a corner case for our generalized approach. Cyclic communication patterns are also used in \textit{Allgather} algorithm proposed by Bruck et al. \cite{TechBruck93,Bruck97} which is a bandwidth-optimal algorithm working for any number of processes. Its application to the \textit{Allreduce} operation was mentioned in \cite{Bruck93} where the structure of \textit{Allgather} steps is used in reversed order for the reduction phase. This gives, as a result, a bandwidth-optimal \textit{Allreduce} algorithm working for any number of processes. This particular algorithm has the same complexity as our bandwidth-optimal version but it requires additional data shift before reduction phase and after the distribution phase. Also no further development made to trade-off bandwidth for latency. Ring algorithm is another bandwidth-optimal \textit{Allreduce} algorithm which performs all communications across the virtual cycle (ring) connecting all processes. Ring algorithm was described by Barnett et al. \cite{Barnett93} and further developed by Patarasuk et al. \cite{Patarasuk07,Patarasuk09} to cover tree topology. This algorithm is advantageous when the vector size is huge since it works with data in a more cache-friendly manner than butterfly algorithms described earlier. Nevertheless, it will be shown that Ring algorithm is directly connected to the butterfly algorithms and is also a special case of the proposed approach. Multiport algorithms for \textit{Allreduce} operation provide a general solution for systems with an arbitrary number of communication channels $k$ between processes. This is a generalization over the single channel case which leads to a lower number of steps equal to $\ceil{\log_{P}k}$. The main contribution in this direction was made by Bruck et al. \cite{Bruck93,Bruck97} whose algorithms were described earlier. The development of the data dissemination algorithm mentioned earlier is a k-port dissemination algorithm given in \cite{End16} but only for a limited subset of $\{P, k\}$. Generalization of the Recursive Doubling algorithm based on usage of multicast messages is described in \cite{Ruefenacht17}. Optimizations for specific topology are discussed in \cite{Barnett93,Chan07,Kohler12}. In \cite{Hasanov17} authors presented a topology-oblivious version of several existing algorithms. There is also an adjacent scientific visualization community where Image Composing algorithm is an analog of the \textit{Allreduce} operation. Radix-k algorithm for big vector size and non-commutative reduction function is proposed in \cite{Peterka09,Kendall10}. It utilizes factorization of $P=p_1\cdot{p_2}\cdot...\cdot{p_n}$ which may be represented as a building of virtual hypercube with dimensions equal to factors and performs linear reduction across each dimension. \section{Basics of group theory} In this section, we briefly describe the main mathematical operations used in the following sections. A \textit{group} is a set (collection of objects) $G$, together with a binary operation "$\cdot$" which inputs two objects in $G$ and outputs a third object in $G$ with the following properties: \begin{itemize}[noitemsep,topsep=0pt] \item the operation "$\cdot$" is associative: \begin{displaymath} (a \cdot b) \cdot c = a \cdot (b \cdot c), a,b,c \in G, \end{displaymath} \item there is an identity object $e$ in $G$: \begin{displaymath} e \cdot a = a \cdot e = a,\ \forall a \in G, \end{displaymath} \item every object $a \in G$ has an inverse $a^{-1} \in G$ such that: \begin{displaymath} a \cdot a^{-1} = a^{-1} \cdot a = e. \end{displaymath} \end{itemize} The operation does not have to be commutative. Groups for which commutativity always holds are called \textit{abelian groups}. The most famous example of groups is a set of integers together with addition operation. Another example is a permutation group - a set of permutations of a given set $M$ together with a composition operation. We are interested in permutation groups of a specific \textit{order}. The \textit{order} of a group is simply the number of elements in this group. If for each pair $x$ and $y$ in $M$ there exists a $g$ in $G$ such that $g \cdot x = y$ then the group is called \textit{transitive}. \textit{Cyclic group} is another particular type of group which elements are combinations of a single element called \textit{generator}. When the order is a prime number, only one cyclic permutation group exists (up to isomorphism). However, for composite numbers, more groups can be found. For example, a cyclic group generated by the permutation $ c = \left(\begin{smallmatrix} 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 \\ 1 & 2 & 3 & 4 & 5 & 6 & 7 & 0 \end{smallmatrix}\right)$ or in cyclic notation $c = (0\ 1\ 2\ 3\ 4\ 5\ 6\ 7)$ is shown in the Table \ref{tab:group-8}.a. It is a transitive permutation group of order $8$ as well as the permutation group given in Table \ref{tab:group-8}.b generated by a set of permutations: \begin{align} \label{eq:self-inverse-8} H=\{ &h_1 = (0\ 1)(2\ 3)(4\ 5)(6\ 7), \nonumber \\ &h_2 = (0\ 2)(1\ 3)(4\ 6)(5\ 7), \nonumber \\ &h_3 = (0\ 4)(1\ 5)(2\ 6)(3\ 7)\}. \end{align} The last one is a specific type of group which elements are self-inverse so composing it with itself produces the identity element. \begin{table} \caption{Examples of permutation groups. a) Cyclic permutation group of order $8$ with the generator $c = (0\,1\,2\,3\,4\,5\,6\,7)$. b) Permutation group of order $8$ generated by a set of permutations $H$ given in \eqref{eq:self-inverse-8}} \label{tab:group-8} \subfloat { \begin{tabular}{ccl} \toprule $\#$& Generation combination&In cyclic notation\\ \midrule 0 & $c^1$ & $(0\ 1\ 2\ 3\ 4\ 5\ 6\ 7)$ \\ 1 & $c^2$ & $(0\ 2\ 4\ 6)(1\ 3\ 5\ 7)$ \\ 2 & $c^3$ & $(0\ 3\ 6\ 1\ 4\ 7\ 2\ 5)$ \\ 3 & $c^4$ & $(0\ 4)(1\ 5)(2\ 6)(3\ 7)$ \\ 4 & $c^5$ & $(0\ 5\ 2\ 7\ 4\ 1\ 6\ 3)$ \\ 5 & $c^6$ & $(0\ 6\ 4\ 2)(1\ 7\ 5\ 3)$ \\ 6 & $c^7$ & $(0\ 7\ 6\ 5\ 4\ 3\ 2\ 1)$ \\ 7 & $e=c^8$ & $()$ \\ \bottomrule \end{tabular}} \subfloat { \begin{tabular}{ccl} \toprule $\#$& Generation combination&In cyclic notation\\ \midrule 0 & $h_1$ & $(0\ 1)(2\ 3)(4\ 5)(6\ 7)$ \\ 1 & $h_2$ & $(0\ 2)(1\ 3)(4\ 6)(5\ 7)$ \\ 2 & $h_1 \cdot h_2$ & $(0\ 3)(1\ 2)(4\ 7)(5\ 6)$ \\ 3 & $h_4$ & $(0\ 4)(1\ 5)(2\ 6)(3\ 7)$ \\ 4 & $h_4 \cdot h_1$ & $(0\ 5)(1\ 4)(2\ 7)(3\ 6)$ \\ 5 & $h_4 \cdot h_2$ & $(0\ 6)(1\ 7)(2\ 4)(3\ 5)$ \\ 6 & $h_4 \cdot h_2 \cdot h_1$ & $(0\ 7)(1\ 6)(2\ 5)(3\ 4)$ \\ 7 & $e=h_1^2=h_2^2=h_4^2$ & $()$ \\ \bottomrule \end{tabular}} \end{table} \newsavebox{\smlmat} \savebox{\smlmat}{ $h = \left(\begin{smallmatrix} 0 & 1 & 2 & 3 & 4 & 5 & 6 \\ 4 & 5 & 2 & 6 & 1 & 0 & 3 \end{smallmatrix}\right)$ } \section{Communication description via permutations} Moves of the Rubik's cube\texttrademark\ can be represented as permutations which rearrange the set of cube pieces. A composition of several move permutations generates another permutation. The complete set of all possible permutations forms the Cube permutation group. Recently it was shown by \cite{cube20} that every position of the Cube can be solved in 20 moves or less. It means that any two permutations are connected by less than 20 compositions with move permutations. In our case, we have a set of processes $\{0,1,...,P-1\}$ that may send data to each other. Let any possible bidirectional data exchange between two processes $i$ and $j$ where $i$ sends data to $j$ and vice versa to be a basic move of our "networking cube." Such a move may be described by a simple transposition: $(i\ j),\ i,j \in \{0,1,...,P-1\}$. At this point, we consider only directions of data exchange without any information about which data is sent. A composition of such elementary transpositions generates other permutations which may be more complex and describe communications involving several processes. For example, a composition of $a=(0\ 1)$ and $b=(1\ 2)$ gives $c=a \cdot b=(0\ 1)(1\ 2)=(0\ 1\ 2)$ which describes a cyclic communication pattern where process $0$ sends data to the process $1$ which sends data to $2$ which finally sends data back to $0$. Moreover, the composition $c'=b \cdot a=(1\ 2)(0\ 1)=(0\ 2\ 1)$ describes an opposite cyclic communication where data is sent from $0$ to $2$ then to $1$ and finally back to $0$. The same way as for Rubik's cube\texttrademark\ all possible compositions of permutations for our "networking cube" form a group $W_P$ which contains permutations describing any possible communication pattern between the set of $P$ processes. We are interested in particular subgroups of $W_P$ which have specific properties. The basis of the proposed approach is an abelian permutation group $T_P=\{t_0,t_1,...,t_{P-1}\}$ of order $P$ which acts transitively on the set $\{0,1,...,P-1\}$. Figure \ref{fig:comm-via-perm} shows an example of $T_P$ for the case of $P=7$ processes when it is a cyclic group with generator $c = (1\ 2\ 3\ 4\ 5\ 6\ 0)$ so $t_k = c^k$. In the previous section examples of two suitable groups were presented in Table \ref{tab:group-8}. Initial data in the \textit{Allreduce} task is a set of data vectors $\mathbf{V}=\{V_0,V_1,...,V_{P-1}\}$ which are owned by the corresponding processes numbered as $\{0,1,...,P-1\}$. Each vector $V_j$ consists of $P$ parts $V_j=(u_{0,j},u_{1,j},...,u_{P-1,j})$. The whole initial data set can be represented as a matrix (see Figure \ref{fig:initial-distr}.a): \begin{equation} \label{eq:initial_data} \mathbf{U}=\{\, u_{i,j} \mid 0 \le i,j < P \,\} \end{equation} where columns are vectors $V_j$ and rows are data elements with the same index number. \begin{figure} \centering \includegraphics[scale=0.8]{images/comm-via-perm-short} \caption{Description of communication patterns via permutation for $P=7$ processes and $T_7$ being a cyclic group with generator $c = (1\ 2\ 3\ 4\ 5\ 6\ 0)$.} \label{fig:comm-via-perm} \end{figure} \subsection{Distributed vector} Distributed vectors consist of data elements owned by different processes. In our approach we use distributed vectors built in the following way: consider an arbitrary permutation $h$ which acts on a set $\{0,1,...,P-1\}$, then a distributed vector is defined as follows: \begin{equation} \label{eq:distr_vector_def} Q=(u_{0,h(0)},u_{1,h(1)},...,u_{P-1,h(P-1)}). \end{equation} An example of a distributed vector \eqref{eq:distr_vector_def} for $P=7$ is shown on Figure \ref{fig:initial-distr}.b. Since the placement of data elements is defined by a permutation then each process owns exactly one data element. \begin{figure} \centering \includegraphics[scale=0.4]{images/initial-distribution} \caption{a) Initial data for $P=7$ represented as a matrix of data elements $u_{i,j}$ where columns are owned by the same process and rows are data elements with the same index number. b) Distributed vector $Q$ built using a permutation ~\usebox{\smlmat} defining placements of data elements. c) Distributed vector $Q_2$ built using the same $h$ but its data elements are shifted in accordance with $t_2$. $T_7$ here is a cyclic group with generator $c = (1\ 2\ 3\ 4\ 5\ 6\ 0)$ shown on Figure \ref{fig:comm-via-perm} where $t_k = c^k$. } \label{fig:initial-distr} \end{figure} \subsection{Initial data description} The initial data \eqref{eq:initial_data} consists of $P^2$ elements $u_{i,j}$, to describe it we need to construct $P$ distributed vectors \eqref{eq:distr_vector_def}: \begin{equation} \label{eq:initial_distr_vectors_set} \bigQ{initial}=\{Q_0,Q_1,...,Q_{P-1}\}, \end{equation} where $Q_k$ is built using the permutations $t_k$ from the group $T_P$ described earlier: \begin{equation} \label{eq:initial_distr_vector} Q_k=(u_{0,t_k(h(0))},u_{1,t_k(h(1))},...,u_{P-1,t_k(h(P-1))}), \end{equation} where $0 \le k < P-1$. An example of $Q_2$ for the case of $P=7$ processes and $T_7$ being a cyclic group with generator $c = (1\ 2\ 3\ 4\ 5\ 6\ 0)$ is shown on Figure \ref{fig:initial-distr}.c. Since the group $T_P$ is transitive then the group $T'_P = h \cdot T_P$ is also transitive. This means that for any $i$ and $j$ there is a $t'_k$ in $T'_P$ such that $j = i \cdot t'_k$ and since the order of the group is $P$ it has only one such mapping. So the set $\{\, u_{i,t_k(h(i))} \mid 0 \le i,k < P-1 \,\}$ defined by \eqref{eq:initial_distr_vectors_set} and \eqref{eq:initial_distr_vector} is equal to the initial data set \eqref{eq:initial_data}. Communication operations will change the placement of distributed data vectors, so an additional upper index should be added to data elements to denote its current position: \begin{displaymath} Q_k=\Big(u_{0,t_k(h(0))}^{t_k(h(0))},u_{1,t_k(h(1))}^{t_k(h(1))},...,u_{P-1,t_k(h(P-1))}^{t_k(h(P-1))}\Big). \end{displaymath} It is possible to put the permutation $t_k$ out from the upper index of elements giving the notation: \begin{equation} \label{eq:distr_vector} Q_k=\mathbf{t_k} q_k, \end{equation} where the current position of data elements in $q_k$ doesn't depend on $k$: \begin{displaymath} q_k=\Big(u_{0,t_k(h(0))}^{h(0)},u_{1,t_k(h(1))}^{h(1)},...,u_{P-1,t_k(h(P-1))}^{h(P-1)}\Big) \end{displaymath} Examples of $Q_0=\mathbf{t_0} q_0$ and $Q_2=\mathbf{t_2} q_2$ are shown on Figure \ref{fig:initial-distr}.b and Figure \ref{fig:initial-distr}.c respectively. Using the notation \eqref{eq:distr_vector} the initial data set \eqref{eq:initial_distr_vectors_set} can be written as: \begin{equation} \label{eq:distr_vector_set} \bigQ{initial}=\mathbf{t_0} q_0 : \mathbf{t_1} q_1 : ... : \mathbf{t_{P-1}} q_{P-1}, \end{equation} here ":" denotes a concatenation which means that two vectors $t_n \cdot q_n$ and $t_m \cdot q_m$ persist at the same time. \subsection{Communication operator} Assume $\mathbf{t_l} \in T_P$ to be a communication operator. Its application to any data vector gives other data vector which data elements change their placement following $\mathbf{t_l}$: \begin{equation} \label{eq:comm_op_0} \mathbf{t_l} \cdot \mathbf{t_k} q_k = \mathbf{t_n} q_k, \end{equation} where $\mathbf{t_k}$ stands for the initial placement of vector $q_k$ and its placement after communication is defined by $\mathbf{t_n} = \mathbf{t_l} \cdot \mathbf{t_k}$. Since $\mathbf{t_k} q_k$ is a distributed vector the communication is performed by all $P$ processes in parallel, so each process sends one local data element and receives the remote one. Thus all network resources are occupied and it is not possible to increase network utilization performing two communications at once. \subsection{Combination of distributed data vectors} In the \textit{Allreduce} task only data elements with the same indexes can be combined. The result of the reduction phase for a single $i^{th}$ data element: \begin{displaymath} u_{i,\Sigma} = u_{i,0} \oplus u_{i,1} \oplus ... \oplus u_{i,P-1}. \end{displaymath} Two distributed vectors $q_n$ and $q_m$ can be combined together if they have identical placement, since their data elements with the equal indices are placed on the same processes: \begin{equation} \label{eq:distr_vectors_combination} \mathbf{t} q_n \oplus \mathbf{t} q_m = \mathbf{t} \cdot ( q_n \oplus q_m ) = \mathbf{t} \cdot ( q_{n+m} ), \end{equation} where $i^{th}$ data element of resulting vector $q_{n+m}$: \begin{displaymath} u_{i,n+m}^{h(i)} = u_{i,t_n(h(i))}^{h(i)} \oplus u_{i,t_m(h(i))}^{h(i)},\ 0 \le i < P-1. \end{displaymath} As for the communication the combination of two distributed vector is performed by $P$ processes in parallel and each process combines only two local data elements. \section{Allreduce as permutation composition} Now when we defined distributed data vectors and basic operations on them, we can start with \textit{Allreduce} description based on the permutation operations. A straightforward solution for the reduction phase is to place all vectors \eqref{eq:distr_vector_set} in the same way and combine them one-by-one. On each step $i$ the following communication operator is applied to the $i^{th}$ data vector: \begin{equation} \label{eq:reduce_dir_perms} \mathbf{t_{i \rightarrow 0}} = \mathbf{t_0} \cdot \mathbf{t_i^{-1}},\ 0 \le i < P-1. \end{equation} After the communication the reduction operation is performed: \begin{equation} \label{eq:reduce_step_general} \mathbf{t_0} q''=\mathbf{t_0} q' \oplus (\mathbf{t_{i \rightarrow 0}} \cdot \mathbf{t_i} q_i) = \mathbf{t_0} q' \oplus (\mathbf{t_0} \cdot \mathbf{t_i^{-1}} \cdot \mathbf{t_i} q_i) = \mathbf{t_0} (q' \oplus q_i),\ 0 \le i < P-1, \end{equation} where $q'$ and $q''$ are intermediate combination result. The complete reduction result can be represented as: \begin{equation} \label{eq:reduce_general} \mathbf{t_0} q_\Sigma = \mathbf{t_0} q_0 \oplus (\mathbf{t_{1 \rightarrow 0}} \cdot \mathbf{t_1} q_1) \oplus ... \oplus (\mathbf{t_{(P-1) \rightarrow 0}} \cdot \mathbf{t_{P-1}} q_{P-1}) = \mathbf{t_0} \big( q_0 \oplus q_1 \oplus ... \oplus q_{P-1} \big). \end{equation} Since only one communication operation can be performed at a time, the straightforward solution requires $P-1$ steps. On each step, the data defined by $\mathbf{t_i} q_i$ is sent to directions defined by the communication operator \eqref{eq:reduce_dir_perms} and combined in accordance with \eqref{eq:reduce_step_general}. During the distribution phase, reversed communications are performed defined as: \begin{equation} \label{eq:distr_dir_perms} \mathbf{t_{0 \rightarrow i}} = \mathbf{t_{i \rightarrow 0}^{-1}}. \end{equation} No combination is performed, so each step produces a duplicate of the vector $q_\Sigma$ with different placement. The final result is: \begin{equation} \label{eq:distr_general} \bigQ{final}=\mathbf{t_0} q_\Sigma\ :\ \mathbf{t_{0 \rightarrow 1}} \cdot \mathbf{t_0} q_\Sigma\ :\ ...\ :\ \mathbf{t_{0 \rightarrow (P-1)}} \cdot \mathbf{t_0} q_\Sigma = \mathbf{t_0} q_\Sigma\ :\ \mathbf{t_1} q_\Sigma\ :\ ...\ :\ \mathbf{t_{P-1}} q_\Sigma. \end{equation} The distribution phase also requires $P-1$ communication steps, so the total number of steps in the straightforward implementation of \textit{Allreduce} is $2(P-1)$, the number of transferred data is $2(P-1) \cdot u$, and the number of computations is $(P-1) \cdot u$, giving the time complexity: \begin{equation} \label{eq:naive_cost} \tau_{naive}=2(P-1)\alpha + 2(P-1) u \cdot \beta + (P-1) u \cdot \gamma. \end{equation} Now let's consider a special case when $T_P$ is a cyclic group with a generator $\mathbf{t}$. In this case $\mathbf{t_i} = \mathbf{t^i}$ and communication operator \eqref{eq:reduce_dir_perms} can be changed to $\mathbf{t}$. The reduction step \eqref{eq:reduce_step_general} becomes: \begin{displaymath} \mathbf{t^{i+1}} q''=\mathbf{t^{i+1}} q_{i+1} \oplus (\mathbf{t} \cdot \mathbf{t^i} q') = \mathbf{t^{i+1}} (q_{i+1} \oplus q'),\ 0 \le i < P-1, \end{displaymath} and the reduction result \eqref{eq:reduce_general} takes the form: \begin{equation} \label{eq:ring_reduce} \mathbf{t^{P-1}} q_\Sigma=\mathbf{t^{P-1}} q_{P-1} \oplus \mathbf{t} \cdot ( \mathbf{t^{P-2}} q_{P-2} \oplus \mathbf{t} \cdot ( ... \oplus \mathbf{t} \cdot (\mathbf{t^0} q_{0}))) = \mathbf{t^{P-1}} \cdot (q_0 \oplus q_1 \oplus ... \oplus q_{P-1}). \end{equation} During the distribution phase the reduction result \eqref{eq:ring_reduce} is distributed using the same communication operator $\mathbf{t}$ in $P-1$ steps giving $\bigQ{final}$. So both reduction and distribution phases can be implemented using the same communication operator $\mathbf{t}$ in $2(P-1)$ steps which is the exact definition of the Ring algorithm. An example schedule of the Ring algorithm for $P=7$ is given on Figure \ref{fig:example-ring-7}. \setlength{\belowcaptionskip}{-10pt} \begin{figure} \centering \begin{minipage}{0.45\textwidth} \centering \includegraphics[width=\linewidth]{images/example-ring-7} \caption{Ring algorithm schedule for $P=7$. Ring algorithm requires $2(P-1)$ steps to complete \textit{Allreduce} with the same communication cycle $t$ used on each step. $q'$ stands got an intermediate reduction result.} \label{fig:example-ring-7} \end{minipage} \hfill \begin{minipage}{0.45\textwidth} \centering \includegraphics[width=\linewidth]{images/example-bo-7} \caption{Schedule of the bandwidth-optimal \textit{Allreduce} algorithm for $P=7$. During reduction phase the set of distributed vectors is folded approximately in a factor of 2 on each step giving the reduce result in $\ceil{\log{2}P}$ steps. The distribution phase consists of a reversed set of steps spreading the result vector among all processes.} \label{fig:example-bo-7} \end{minipage} \end{figure} \setlength{\belowcaptionskip}{+10pt} \begin{figure} \centering \includegraphics[width=\linewidth]{images/example-bo-7-5steps} \caption{Schedule of the \textit{Allreduce} algorithm for $P=7$ with reduced by $1$ number of steps in the distribution phase. During the reduction phase an additional data vector is transferred on each step to get a bigger result containing of $\comm{0} q_\Sigma$ and $\comm{1} q_\Sigma$. This allows to omit the very first step of the distribution phase. By repeating of such algorithm modification it is possible to decrease the number of steps by the cost of the additionally transferred data.} \label{fig:example-bo-7-5steps} \end{figure} \section{Bandwidth-optimal algorithm} The reduction phase can be done much faster if more distributed data vectors are combined on each step. The maximum number of vectors can be combined in one step is $\floor{N_i/2}$ where $N_i$ is the number of separate distributed vectors on step $i$. Such approach requires $\ceil{\log(P)}$ number of steps for the reduction phase. The starting set of vectors on $i^{th}$ step is defined by: \begin{equation} \label{eq:bo_starting_set} \bigQ{i}= \begin{cases} \bigQ{initial}, & \text{if}\ i=0, \\ \comm{0} q_0^* : \comm{1} q'_1 : ... : \comm{N_{i}-1} q'_{N_{i}-1}, & \text{otherwise}, \end{cases} \end{equation} where $q'_k$ stands for an intermediate sum of data vectors and $q^*_0$ - is the first data vector which may not participate in the reduction when $N_i$ is odd. The number of distributed vectors $N_{i}$ is: \begin{equation} \label{eq:bo_starting_set_size} N_{i}= \begin{cases} P, & \text{if}\ i=0, \\ \ceil{N_{i-1}/2}, & \text{otherwise}. \end{cases} \end{equation} Communications on the $i^{th}$ step are defined by the operator: \begin{equation} \label{eq:bo_dir_perms} \mathbf{t_{step,i}} = \comm{-\floor{N_{i}/2}}, \end{equation} which is applied to the set of distributed data vectors: \begin{equation} \label{eq:bo_tx_dist} \bigQ{TX,i} = \comm{\ceil{N_{i}/2}} q'_{\ceil{N_{i}/2}} : ... : \comm{N_{i}-1} q'_{N_{i}-1}. \end{equation} The part of the set $\bigQ{i}$ that doesn't participate in network communication is defined by: \begin{equation} \label{eq:bo_rx_dist} \bigQ{i} \textbackslash \bigQ{TX,i} = \comm{0} q_0^* : \comm{1} q'_1 : ... : \comm{\ceil{N_{i}/2}-1} q'_{\ceil{N_{i}/2}-1}. \end{equation} After the communication is performed $\floor{N_{i}/2}$ vectors will have equal placement and can be combined. The resulting set of vectors after the first step depends on parity of $N_{i}$: \begin{align} \bigQ{even,i+1} &= \comm{0} (q_0 \oplus q_{N_{i}/2}) : \comm{1} (q_1 \oplus q_{N_{i}/2 + 1}) : ... : \comm{N_{i}/2-1} (q_{N_{i}/2-1} \oplus q_{N_{i}-1}) = \nonumber \\ &= \comm{0} q'_0 : \comm{1} q'_1 : ... : \comm{\ceil{N_{i}/2}-1} q'_{\ceil{N_{i}/2}-1}, \text{if $N_{i}$ is even}, \label{eq:bo_step_even} \\ \bigQ{odd,i+1} &= \comm{0} q_0 : \comm{1} (q_1 \oplus q_{\ceil{N_{i}/2}}) : ... : \comm{\ceil{N_{i}/2}-1} (q_{\ceil{N_{i}/2}-1} \oplus q_{(N_{i}-1)}) = \nonumber \\ &= \comm{0} q_0 : \comm{1} q'_1 : ... : \comm{\ceil{N_{i}/2}-1} q'_{\ceil{N_{i}/2}-1}, \text{otherwise}. \label{eq:bo_step_odd} \end{align} At the very last step of the reduction phase $N_{\ceil{log_{2}P}-1}=2$ (this is the only one step for the case $P=2$): \begin{equation} \label{eq:bo_last_step} \bigQ{\ceil{log_{2}P}} = \comm{0} q^*_0 : \comm{-1} \cdot \comm{1} q'_1 = \comm{0} (q^*_0 \oplus q'_1) = \comm{0} q_\Sigma . \end{equation} The distribution phase is a reversed reduction phase without combination performed on each step. An example schedule for the bandwidth-optimal \textit{Allreduce} for $P=7$ is given on Figure \ref{fig:example-bo-7}. Both reduction and distribution phases take $\ceil{\log(P)}$ while the number of transmitted data and the number of calculations stay the same as for Ring algorithm. So the total cost is: \begin{equation} \label{eq:bo_cost} \tau_{bo}=2\ceil{\log(P)} \cdot \alpha + 2(P-1) \cdot u \cdot \beta + (P-1) \cdot u \cdot \gamma . \end{equation} The described bandwidth-optimal butterfly \textit{Allreduce} algorithm works for any number of nodes. A similar algorithm can be constructed if use the Bruck's \textit{Allgather} and the same steps in reversed order at the reduction phase as mentioned in \cite{Bruck93}, but this algorithm requires two additional data reorderings: before the reduction phase and after the distribution phase. The proposed bandwidth-optimal algorithm doesn't need data shift after the end of communications since all data vectors appear in the right positions. Moreover, our algorithm is more general since it allows to use any suitable group $T_P$ to vary utilized communication patterns. When the number of processes is power-of-two and a special group $T_P$ is used (like the group shown in the Table \ref{tab:group-8}.b) then the proposed bandwidth-optimal algorithm becomes equal to the Recursive Halving algorithm. This means that Recursive Halving is a special case of the proposed approach. \section{Moving towards latency-optimal version} The idea of changing the number of steps in the butterfly \textit{Allreduce} algorithm appeared in \cite{Geijn91,Barnett93,Bruck93,Rabenseifner04} and was based on the usage of two algorithms at the same time: bandwidth-optimal and latency-optimal. Initially, the reduction phase is started with the bandwidth-optimal algorithm and when the data size to be sent becomes less than some threshold - the latency-optimal algorithm is used. On the distribution phase switching between algorithms is done in the reversed order. The main problem of such hybrid approaches is that they don't work with a non-power-of-two number of processes. Developing the bandwidth-optimal algorithm discussed in the previous section we get a novel algorithm with ability to change number of steps working for any number of processes. The idea is to get a bigger result on the reduction phase so the distribution phase can take less steps. For example, if we get $t^0 q_\Sigma : t^1 q_\Sigma$ during the reduction phase, we may omit the very first step of the distribution phase (see Figure \ref{fig:example-bo-7-5steps}). We can get the reduction schedule for the $t^1 q_\Sigma$ simply by shifting all vectors in the schedule for $t^0 q_\Sigma$ by $1$ but leave communication operators to be the same. So \eqref{eq:bo_starting_set_size} and \eqref{eq:bo_dir_perms} stay the same while \eqref{eq:bo_starting_set} becomes: \begin{equation} \label{eq:var_starting_set} \bigQ{i}'= \begin{cases} \bigQ{initial}, & \text{if}\ i=0 \\ \comm{1} q_1^* : \comm{2} q'_2 : ... : \comm{N_{i}} q'_{N_{i}}, & \text{otherwise}, \end{cases} \end{equation} Equations \eqref{eq:bo_tx_dist} and \eqref{eq:bo_rx_dist} take the form: \begin{align} &Q'_{TX,i} = \comm{\ceil{N_{i}/2}+1} q'_{\ceil{N_{i}/2}+1} : ... : \comm{N_{i}} q'_{N_{i}}, \\ &Q'_{i-1} \textbackslash Q'_{TX,i} = \comm{1} q^*_1 : \comm{2} q'_2 : ... : \comm{\ceil{N_{i}/2}} q'_{\ceil{N_{i}/2}}. \end{align} The step result descriptions \eqref{eq:bo_step_even}, \eqref{eq:bo_step_odd} and \eqref{eq:bo_last_step} change in the similar way: \begin{align} Q'_{even,i} &= \comm{1} (q^*_1 \oplus q'_{N_{i}/2+1}) : \comm{2} (q'_2 \oplus q'_{N_{i}/2+2}) : ... : \comm{N_{i}/2} (q'_{N_{i}/2} \oplus q'_{N_{i}}), \\ Q'_{odd,i} &= \comm{1} q^*_1 : \comm{2} (q'_2 \oplus q'_{\ceil{N_{i}/2}+1}) : ... : \comm{\ceil{N_{i}/2}} (q'_{\ceil{N_{i}/2}} \oplus q'_{N_{i}}), \\ Q'_{\ceil{log_{2}P}-1} &= \comm{1} (q^*_1 \oplus q'_2) = \comm{1} q_\Sigma. \end{align} Now it is possible to get a difference between the original equations and new ones. We are interesting in additional data to be sent: \begin{equation} Q'_{TX,i} \textbackslash Q_{TX,i} = \comm{N_{i}} q'_{N_{i}}, \end{equation} and additional data to be reduced: \begin{align} Q'_{even,i} \textbackslash Q_{even,i} &= \comm{1} (q^*_1 \oplus q'_{N_{i}/2+1}) : \comm{N_{i}/2} (q'_{N_{i}/2} \oplus q'_{N_{i}}), \\ Q'_{odd,i} \textbackslash Q_{odd,i} &= \comm{1} q*_1 : \comm{\ceil{N_{i}/2}} (q'_{\ceil{N_{i}/2}} \oplus q'_{N_{i}}), \\ Q'_{\ceil{log_{2}P}-1} \textbackslash Q_{\ceil{log_{2}P}-1} &= \comm{1} (q^*_1 \oplus q'_2) = \comm{1} q_\Sigma. \end{align} So adding one data vector $\comm{1} q_\Sigma$ to the result of the reduction phase increases the number of exchanged data by $u$ on each step and also the number of computations by $2u$ for steps when $N_{i}$ is even and by $u$ otherwise. An example of \textit{Allreduce} algorithm schedule for $P=7$ with a reduced number of steps is given in Figure \ref{fig:example-bo-7-5steps}. To reduce the number of steps further it is required to double the number of resulting data vectors, so the amount of additional data to be sent is $(2^{r}-1) \ceil{\log(P)} \cdot u \cdot \beta$, where $r$ is the number of removed steps from the distribution phase. The number of additional calculations is also doubled, in the worst case when $N_{i}$ is even in $\ceil{\log(P)}-2$ steps the number of additional computations is $(2^{r}-1) (2\ceil{\log(P)}-2) \cdot u \cdot \gamma$. The resulting complexity for the algorithm with an intermediate number of steps: \begin{align} \tau_{i} &= (2\ceil{\log(P)} - r) \cdot \alpha + \nonumber \\ &+ \big( 2(P-1) + (2^{r}-1) (\ceil{\log(P)}-1) \big) \cdot u \cdot \beta + \nonumber \\ &+ \big( (P-1) + (2^{r}-1) (2\ceil{\log(P)}-2) \big) \cdot u \cdot \gamma, \label{eq:intemediate_cost} \end{align} where $0 \le r < \ceil{\log(P)}$. The latency-optimal version ($r = \ceil{\log(P)}$) considered separately in the next subsection. It is possible to analytically determine the optimal number of steps for the proposed algorithm by finding a minimum of \eqref{eq:intemediate_cost}: \begin{equation} \label{eq:opt_number_of_steps} r = \log\Big( \dfrac{\alpha}{m(\beta + 2\gamma)} \Big) + \log\Big( \dfrac{P}{(\log(P) - 1)ln2} \Big) \end{equation} The resulting expression consists of two parts: the first one depends on network parameters and the initial data size $m$, the second one depends only on the number of processes. Usage of \eqref{eq:opt_number_of_steps} allows calculating the optimal number of steps based on the estimated network parameters $\alpha, \beta$ and calculation speed $\gamma$. When the number of processes is power-of-two and a special group $T_P$ is used (like the group shown in the Table \ref{tab:group-8}.b) then the proposed latency-optimal algorithm becomes equal to the Recursive Doubling algorithm which means that Recursive Doubling is a special case of the proposed approach. \section{Latency-optimal version} Latency optimal version of the algorithm is a corner case of the version with intermediate number of steps where the reduction phase ends with complete \textit{Allreduce} result. On each step all data vectors are sent so \eqref{eq:bo_tx_dist} becomes: \begin{equation} Q''_{TX} = \comm{0} q'_{0} : \comm{1} q'_{1} : ... : \comm{P-1} q'_{P-1}, \end{equation} and \eqref{eq:bo_rx_dist}: \begin{align} Q''_{i-1} \textbackslash Q''_{TX} =\ \comm{0} q^*_0 : \comm{1} q^*_1 : ... : \comm{P-1} q^*_{P-1} : \ \comm{0} q'_0 : \comm{1} q'_1 : ... : \comm{P-1} q'_{P-1} \end{align} Remember that $q^*$ appears at the step when the number of distributed data vectors is odd and reduction does not involve all vectors which leads to the heterogeneous intermediate result. So $q^*$ and $q'$ cannot be combined even if they have the same placement. The step result descriptions \eqref{eq:bo_step_even}, \eqref{eq:bo_step_odd} and \eqref{eq:bo_last_step} take the form: \begin{align} &Q''_0 =\comm{0} q^*_0 : \comm{1} q^*_1 : ... : \comm{P-1} q^*_{P-1} : \comm{0} (q_0 \oplus q_{\ceil{P/2}-1}) : \comm{1} (q_1 \oplus q_{\ceil{P/2}}) : ... : \comm{P-1} (q_{P-1} \oplus q_{\ceil{P/2}-2}), \\ &Q''_{even,i} = \comm{0} (q^*_0 \oplus q'_{N_{i}/2}) : \comm{1} (q^*_1 \oplus q'_{N_{i}/2 + 1}) : ... : \comm{P-1} (q^*_{P-1} \oplus q'_{N_{i}/2-1}) : \nonumber \\ & \qquad \qquad : \comm{0} (q'_{0} \oplus q'_{N_{i}/2}): \comm{1} (q'_{1} \oplus q'_{N_{i}/2 + 1}): ... : \comm{P-1} (q'_{P-1} \oplus q'_{N_{i}/2-1}), \\ &Q''_{odd,i} = \comm{0} q^*_0 : \comm{1} q^*_1 : ... : \comm{P-1} q^*_{P-1} : \nonumber \\ & \qquad \qquad : \comm{0} (q'_{0} \oplus q'_{\ceil{N_{i}/2}-1}): \comm{1} (q'_{1} \oplus q'_{\ceil{N_{i}/2}}): ... : \comm{P-1} (q'_{P-1} \oplus q'_{\ceil{N_{i}/2}-2}), \\ &Q'_{\ceil{log_{2}P}-1} = \comm{0} (q^*_0 \oplus q'_1) : \comm{1} (q^*_1 \oplus q'_2) : ... : \comm{P-1} (q^*_{P-1} \oplus q'_0) = \comm{0} q_\Sigma : \comm{1} q_\Sigma : ... : \comm{P-1} q_\Sigma. \end{align} The distribution phase, in this case, is completely omitted. The resulting complexity for the latency-optimal version in the worst case (when $N_{i}$ is even in $\ceil{\log(P)}-2$ steps) is: \begin{equation} \label{eq:lo_cost} \tau_{lo}= \ceil{\log(P)} \cdot \alpha + P \ceil{\log(P)} \cdot u \cdot \beta + P (2\ceil{\log(P)}-2) \cdot u \cdot \gamma. \end{equation} \section{Experimental results} We performed experiments on our cluster of 8 machines with 20 physical cores each connected by 10 GE through the network switch. MPI processes were mapped uniformly to cluster nodes but to achieve properties close to a peer-to-peer network ranks of the processes were randomly shuffled. A comparison was made between the proposed algorithm from one side and OpenMPI on the other side. OpenMPI implementation of \textit{Allreduce} utilizes two separate algorithms - Recursive Doubling for data sizes less than 10 KB and Ring for bigger data sets. To have a complete picture we implemented Recursive Halving algorithm which works better on data of medium size. To calculate an optimal number of steps for the proposed algorithm simple measurements were performed to estimate latency, bandwidth and computation speed. The estimated values can be found in Table \ref{tab:p2p_params}. Figure \ref{fig:existing-to-new-comp-smallest} shows a comparison of the proposed algorithm with OpenMPI and Recursive Halving algorithms performed for small data sizes and the number of processes $P=127$. Performance degradation of OpenMPI at 10 KB caused by switching from Recursive Doubling to Ring algorithm. The proposed algorithm shows better performance even for the estimated number of steps calculated using the network parameters from Table \ref{tab:p2p_params}. There are two reasons: firstly the proposed algorithm has no bandwidth overhead caused by the reduction of the number of processes to the nearest power-of-two, and secondly, it may change the number of steps to better fit current data size. The best possible result for the proposed algorithm (red dashed line) corresponds to the case when we know the exact optimal number of steps. The provided comparison demonstrates that the estimated number of steps fits well with experimental data. Figure \ref{fig:existing-to-new-comp-small} shows a comparison of the proposed algorithm with Recursive Halving algorithm made for medium data sizes and the number of processes $P=127$. OpenMPI is not presented since it shows too bad performance for given data sizes. The performance gap between the proposed algorithm and Recursive Halving is growing with the size since Recursive Halving has bandwidth overhead caused by the reduction of the number of processes to the nearest power-of-two. A comparison for big data sizes is given in Figure \ref{fig:existing-to-new-comp-big}. Ring algorithm (used by OpenMPI) finally beats the proposed one which is due to better cache utilization. However, it is theoretically possible to improve the proposed algorithm in such a way that the number of steps will be bigger than $2\log(P)$ resulting in a smaller size of messages to be sent on each step. This improvement is one of the tasks we are currently working on. Figure \ref{fig:diff-versions-comp} demonstrates the performance of different versions of the proposed algorithm for $P=127$. The bandwidth-optimal and latency-optimal versions together demonstrate the worst possible performance of the proposed algorithm while the green solid line corresponds to the optimal number of steps for the given data size. The point where bandwidth-optimal and latency-optimal versions intersect shows the biggest benefit from the usage of the flexible number of steps. A comparison concerning the number of processes is demonstrated in Figure \ref{fig:existing-to-new-comp-nodes-smallest}. A comparison was made for data size $m=425$ Bytes which is the average size of the data array involved in \textit{Allreduce} \cite{Rabenseifner99}. The number of steps for the proposed algorithm corresponds to the latency-optimal version for all $P$. The performance of Recursive Doubling algorithm isn't changed sharply when the number of processes exceeds power-of-two but instead, it grows very smoothly. It is caused by two reasons: firstly, not all processes participate in the preparation and finalization steps and secondly, the latency for one-way transmission is much smaller than for bidirectional data exchange. In the proposed algorithm all processes participate in bidirectional data exchange on each step which leads to a sharp performance degradation introduced by each additional step. Nevertheless, the proposed algorithm demonstrates much better performance when the number of processes becomes significantly bigger than the nearest power-of-two. A comparison against the number of nodes for bigger data size $m=9$ KBytes is given in Figure \ref{fig:existing-to-new-comp-nodes-medium}. For big number of processes the proposed algorithm shows better performance even in a power-of-two case since it is able to change the number of steps adopting to the current conditions. \begin{table} \caption{Estimated point-to-point communication parameters for the 10GE cluster used in experiments to calculate the optimal number of steps for the proposed algorithm. } \label{tab:p2p_params} \begin{tabular}{ccl} \toprule $\alpha$ & $3 \cdot 10^{-5}$ & $sec$ \\ $\beta$ & $1 \cdot 10^{-8}$ & $sec / Byte$ \\ $\gamma$ & $2 \cdot 10^{-10}$ & $sec / Byte$ \\ \bottomrule \end{tabular} \end{table} \begin{figure} \centering \begin{minipage}{0.45\textwidth} \centering \includegraphics[scale=0.15]{images/existing-to-new-comp-smallest.pdf} \caption{A comparison of the proposed algorithm with OpenMPI and Recursive Halving on small data sets for $P=127$. } \label{fig:existing-to-new-comp-smallest} \end{minipage} \hfill \begin{minipage}{0.45\textwidth} \centering \includegraphics[scale=0.15]{images/existing-to-new-comp-big.pdf} \caption{A comparison of the proposed algorithm with OpenMPI and Recursive Halving on big data sets for $P=127$. } \label{fig:existing-to-new-comp-big} \end{minipage} \begin{minipage}{0.45\textwidth} \centering \includegraphics[scale=0.15]{images/existing-to-new-comp-small.pdf} \caption{A comparison of the proposed algorithm with Recursive Halving on medium data sets for $P=127$. } \label{fig:existing-to-new-comp-small} \end{minipage} \hfill \begin{minipage}{0.45\textwidth} \centering \includegraphics[scale=0.15]{images/diff-versions-comp.pdf} \caption{A comparison of different versions of the proposed algorithm for $P=127$. } \label{fig:diff-versions-comp} \end{minipage} \begin{minipage}{0.45\textwidth} \centering \includegraphics[scale=0.15]{images/existing-to-new-comp-nodes-smallest.pdf} \caption{A comparison of \textit{Allreduce} algorithms depending on the number of processes for data size $m=425$ Bytes. } \label{fig:existing-to-new-comp-nodes-smallest} \end{minipage} \hfill \begin{minipage}{0.45\textwidth} \centering \includegraphics[scale=0.15]{images/existing-to-new-comp-nodes-medium.pdf} \caption{A comparison of \textit{Allreduce} algorithms performance depending on the number of processes for data size $m=9$ KBytes. } \label{fig:existing-to-new-comp-nodes-medium} \end{minipage} \end{figure} \section{Conclusion} The described \textit{Allreduce} algorithm is a general solution working for any number of processes and any number of steps between $\log{P}$ and $2\log{P}$. It was shown that widely used algorithms such as Ring, Recursive Halving and Recursive Doubling are special cases of the introduced common approach. Our main contributions are: \begin{itemize}[noitemsep,topsep=0pt] \item theoretical generalization of existing \textit{Allreduce} algorithms based on group theory; \item novel algorithm based on the proposed theory which provides latency-optimal and bandwidth-optimal solutions for any number of processes and is able to trade-off latency for bandwidth by changing the number of steps. \end{itemize} While there were some attempts to cover latency-optimal and bandwidth-optimal cases \cite{Barnoy93, TechBruck93, Bruck97} for a non-power-of-two number of processes they are not completely optimal and built with fixed communication patterns. The proposed algorithm provides a complete solution including all versions of \textit{Allreduce} and moreover it is possible to vary utilized communication patterns using different groups $T_P$ which may give a benefit when more complicated network topologies are considered. A performance comparison was made of the proposed algorithm with existing solutions. The novel algorithm shows significantly better performance on small and medium data sizes. Further optimization of the proposed solution aiming performance improvement for large data sets is possible. For example, it is possible to implement a version of the algorithm which operates with smaller pieces of data but with a bigger number of steps between $2\ceil{\log(P)}$ and $2(P-1)$. \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2020-04-22T02:10:18', 'yymm': '2004', 'arxiv_id': '2004.09362', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09362'}
arxiv
\section{Introduction} Evolutionary diversity optimisation aims to construct a set of diverse solutions that all have high quality but differ with respect to important properties of the solutions. This area of research started by Ulrich and Thiele~\cite{DBLP:conf/gecco/UlrichBZ10,DBLP:conf/gecco/UlrichT11} has recently gained significant attention within the evolutionary computation community. It equips practitioners with high quality solutions of variable designs. Furthermore, the methods developed can be used in the context of machine learning and algorithm selection and configuration. Here, evolutionary diversity optimisation is used to evolve a diverse set of instances that can be used for training prediction models that forecast algorithm performance on a newly given instance. Recent studies in this area of research mainly focused on the diversity measure to be used in the selection process when characterising solutions by underlying features. Differences in feature values as well as weighted combinations of two or more features have been examined in the context of Travelling Salesperson Problem (TSP) instances and images~\cite{DBLP:conf/ppsn/GaoNN16,DBLP:conf/gecco/AlexanderKN17}. More recently the use of the discrepancy measure as well as the use of popular indicators from the area of evolutionary multi-objective optimisation have been proposed and evaluated~\cite{DBLP:journals/corr/abs-1802-05448,DBLP:conf/gecco/NeumannG0019}. Special mutation operators for creating diverse sets of TSP instances have been investigated in~\cite{DBLP:conf/foga/BossekKN00T19}. In this paper, we examine, for the first time, TSP in the context of evolutionary diversity optimisation. Our focus is on the diversity of the tours themselves, not their qualities. The TSP has been subject to a wide range of studies. Various evolutionary algorithms and other heuristic search methods as well as exact solvers have been developed over the years~\cite{lin1973,helsgaun2000,xie2009,Nagata2013}. Furthermore, the TSP has been studied widely in the area of algorithm selection and configuration~(see \cite{DBLP:journals/ec/KerschkeHNT19} for a recent overview on this research area) and a wide range of studies regarding important features of TSP instances and their relation to algorithm performance have been carried out~\cite{smithmiles2011,kanda2011,mersmann2013,KKBHTLeveragingTSP}. Evolutionary diversity optimisation has so far only been considered for evolving TSP instances~\cite{DBLP:conf/ppsn/GaoNN16,DBLP:journals/corr/abs-1802-05448,DBLP:conf/gecco/NeumannG0019}, but not for computing a diverse set of high quality tours for a given TSP instance. In this paper, we examine ways to evolve a diverse set of high quality TSP tours for a given TSP instance and population size. A crucial aspect in our study is how to measure the diversity of a tours population for an effective diversity-driven approach. To establish diversity-oriented evolutionary pressure, we propose two diversity measures: an edge distribution diversity measure and a pairwise dissimilarity measure. We study both measures with respect to their properties in the context of evolutionary diversity optimisation and carry out experimental investigations showing how evolutionary algorithms generate diverse populations using the two measures on unweighted TSP instances where all tours are accepted. Our results for this basic set up shows that these cases can be handled effectively and set the basis for studies on classical TSPlib instances~\cite{DBLP:journals/informs/Reinelt91} where tours are filtered based on qualities. We investigate the introduced evolutionary diversity optimisation approach using the two diversity measures on classical instances, and explore the differences in results when using classical $k$-opt operations where $k=2,3,4$ for a wide range of quality thresholds imposed on the tours. Furthermore, we study how the population size which determines the size of the set of tours effects the ability of the evolutionary diversity optimisation approaches to obtain a high diversity score. The paper is structured as follows. In Section~\ref{sec2}, we introduce the Traveling Salesperson Problem in the context of evolutionary diversity optimisation and the algorithms that are part of our investigations. In Section~\ref{sec3}, we introduce the edge diversity measure and investigate its theoretical properties. Section~\ref{sec4} introduces the pairwise distance diversity measure along with its theoretical properties. We report on our experimental investigations in Section~\ref{sec5} and finish with some conclusions. \section{Maximising Diversity in TSP} \label{sec2} The Traveling Salesperson problem (TSP), one of the best-known $\mathcal{NP}$-hard combinatorial optimisation problems, can be described as follows: Given a complete graph $G=(V,E)$ with $n = |V|$ cities, $m = n(n-1)/2 = |E|$ edges and the pairwise distances between the cities, the goal is to compute a tour of minimal length that visits each city exactly once and finally returns to the original city. For the Euclidean TSP all cities lie in the Euclidean plane and the pairwise distances between the cities are determined by the Euclidean metric. Let $V = \{1, \ldots, n\}$. The goal is to find a permutation $\pi : V \rightarrow V$ that minimises the cost function \begin{align*} c(\pi) = d(\pi(n),\pi(1)) + \sum_{i=1}^{n-1} d(\pi(i),\pi(i+1)), \end{align*} where $d(i,j)$ is the Euclidean distance between points $i$ and $j$. Note that the Euclidean TSP remains an $\mathcal{NP}$-hard combinatorial optimisation problem. In this paper, we consider diversity optimisation for the Traveling Salesperson Problem. For each TSP instance, our goal is to find a set $P$ of $\mu = |P|$ tours that is diverse with respect to some diversity measure, while each tour meets a given quality threshold. Let $I$ be an individual (which constitutes a permutation of the given $n$ cities) and $c(I)$ be the cost of $I$. The quality threshold is met iff $c(I) \leq (1 + \alpha) \cdot OPT$, where $OPT$ is the value of an optimal tour and $\alpha>0$ is a parameter that determines the required quality of a desired solution. The quality criterion means that the quality threshold is met iff $I$ is a $(1 + \alpha)$ approximation of an optimal solution. We assume that the optimal tour is known for a given TSP instance. In order to optimise the diversity for the Traveling Salesperson Problem we employ a $(\mu+1)$-EA that has already been used in the context of evolutionary diversity optimisation~\cite{DBLP:conf/ppsn/GaoNN16,DBLP:conf/gecco/AlexanderKN17,DBLP:journals/corr/abs-1802-05448,DBLP:conf/gecco/NeumannG0019,DBLP:conf/foga/BossekKN00T19}. Our approach differs from the previous ones in terms of the considered problem and underlying diversity measure that drives the optimisation approach. We use Algorithm~\ref{alg:ea} to compute a diverse population consisting of TSP tours where each individual/tour $I$ has to meet a given quality criteria $c(I)$ according to a given threshold. Initially, the population $P$ is generated with $\mu$ individuals, and exactly one offspring $I'$ is produced in each iteration. If the offspring $I'$ does not satisfy $c(I') \leq (1+\alpha)\cdot OPT$, then it is discarded. Otherwise $I'$ is added to the population. Afterwards, elitist survival selection is performed with respect to a diversity measure $D$. For our investigations, we consider some function indicating overlaps between tours $D \colon P \rightarrow \mathbb{R}$, which should be minimized to improve diversity. Thus, an individual $I \in P$ is removed such that $D(P\setminus \{I\})$ is minimal among all individuals $J \in P$. We introduce two diversity measures for evolutionary diversity optimisation for TSP, namely an \emph{edge diversity} (ED) optimisation approach in Section~\ref{sec3} and a \emph{pairwise edge distances} (PD) optimisation approach in Section~\ref{sec4}. We consider vector functions instead of traditional scalar functions, with the hope to capture more nuances in the survival selection mechanism elegantly. The edge diversity optimisation approach attempts to maximise population diversity without relying on dissimilarities between tours. Instead, it considers how frequent each edge is present in the population, and aims to equalise these frequencies. The goal is a population of tours containing every edge, each as close to $k$ times as possible for some $k$. The approach makes sense if edges can be considered independent of each other, meaning each edge is present in the population at a frequency independent of that of other edges. This is not true for tours, thus important information may potentially be left out. On the other hand, the pairwise edge distances approach considers solely the edge distances between all pairs of tours in the population in terms of overlap. It attempts to simultaneously maximise these distances and equalising them, with an emphasis on pairs with the least distances. In effect, it tries to increase these small distances by moving tours away from their closest tours and possibly closer to further tours, using mutation operators. Consequently, it tends to generally increase the dissimilarities between a tour $I$ and the rest $P\setminus\{I\}$. This helps lessen the clustering phenomenon, where tours in the population form low-diversity clusters. The evolutionary diversity algorithm based on edge diversity measure is compared to the evolutionary diversity optimisation approach based on pairwise edge distances measure in two different settings, using simple unconstrained TSP tours and TSPlib instances~\cite{DBLP:journals/informs/Reinelt91} in Section~\ref{sec5}. \begin{algorithm}[tp] \SetKwData{Left}{left}\SetKwData{This}{this}\SetKwData{Up}{up} \SetKwInOut{Input}{input}\SetKwInOut{Output}{output} {Initialise the population $P$ with $\mu$ TSP tours such that $c(I) \leq (1+ \alpha)\cdot OPT$ for all $I \in P$.\\ Choose $I \in P$ uniformly at random and produce an offspring $I'$ of $I$ by mutation.\\ If $c(I') \leq (1+ \alpha)\cdot OPT$, add $I'$ to $P$. \\ If $|P| = \mu+1$, remove exactly one individual $I$, where $I=\arg \min_{J \in P} D(P\setminus \{J\})$, from $P$.\\ Repeat steps 2 to 4 until a termination criterion is reached.\\ } \caption{Diversity maximising ($\mu + 1$)-EA} \label{alg:ea} \end{algorithm} \section{Maximising edge diversity} \label{sec3} In this approach, we consider diversity in terms of equal representations of edges by tours in the population, or \emph{edge diversity}. It takes into account, for each edge, the number of tours containing it, among the $\mu$ solutions in the population. These numbers are referred to as \emph{edge counts}. Given a population $P$ and an edge $e \in E$, we denote by $n(e, P)$ its edge count, which is defined, \begin{align*} n(e, P) := \left|\{T \in P \, | \, e \in E(T)\}\right| \in \{0, \ldots, \mu\} \end{align*} where $E(T) \subset E$ is the set of edges used by solution $T$. Then in order to maximise the edge diversity we aim to minimise the vector \begin{align*} \mathcal{N}(P) = \text{sort}\left(n(e_1, P), n(e_2, P), \ldots, n(e_m, P)\right) \end{align*} in the lexicographic order where sorting is performed in descending order. This is based on the idea of maximising genotypic diversity as the mean of pairwise edge distances~\cite{DiversityPermutation}. Since $\mu$ is fixed, we change the mean to a sum to simplify the function \begin{align*} gtype(P) = \sum_{T_1\in P}\sum_{T_2\in P}|E(T_1)\setminus E(T_2)|. \end{align*} The maximum edge distance between two different tours is $n$, so the maximum diversity is $\mu(\mu-1)n$. Let $n_i=n(e_i,P)$. There are $n_i$ tours in $P$ sharing edge $e_i$. Therefore, it affects $n_i(n_i-1)/2$ pair-wise edge distances, reducing each by $1$. Since they can be added up independently across all edges, the diversity measure is then \begin{align*} gtype(P) = \mu(\mu-1)n+\sum_{i}n_i-\sum_in^2_i. \end{align*} Since $\sum_in_i=\mu n$ is constant, maximising diversity is reduced to minimising $\sum_in^2_i$. Given $\sum_in_i$ being constant, the Cauchy–Schwarz inequality implies that $\sum_in^2_i$ is the smallest when all $n_i$ are as close to being equal to each other as possible. The population with such property minimises $\mathcal{N}$, meaning \begin{align*} \argmax_P\{gtype(P)\} = \argmin_P\{\mathcal{N}(P)\}. \end{align*} For complete graphs, the optima for $\mathcal{N}(P)$ can be determined based on the following result, so the maximum diversity can be calculated. \begin{thm}\label{theo:ed_opt} For every pair of integers $\mu\geq1$ and $n\geq3$, given a complete graph $G=(V,E)$ where $|V|=n$, there is a $\mu$-size population $P$ of tours such that \[\max_{e\in E}\{n(e,P)\}-\min_{e\in E}\{n(e,P)\}\leq1.\] \end{thm} \begin{proof} We prove this by defining a way to construct such a population. According to Theorem~1 in \cite{Alspach1990}, in every complete graph with $n\geq3$ vertices, there is a set of $h=\left\lfloor\frac{n-1}{2}\right\rfloor$ pairwise edge-disjoint Hamiltonian cycles. We denote by $H$ the set of all such Hamiltonian cycles in $G$, and $E(H)$ the set of all edges $H$ contains. We consider 2 cases: $n$ is odd, and $n$ is even. Assuming $n$ is odd, then $G$ can be decomposed completely into edge-disjoint tours, meaning $E(H)=E$. Let $\mu=kh+r$ where $r\in[0,h)$ and $r\equiv \mu\bmod h$. We construct a population $P'$ by adding all tours in $H$, each exactly $k$ times. We then construct $P$ from $P'$ by adding all tours in $L$ for any $L\subset H$ where $|L|=r$. With this, $n(e,P)=k$ for all $e\notin E(L)$, and $n(e,P)=k+1$ for all $e\in E(L)$. Assuming $n$ is even, then according to \cite{Alspach1990}, for any perfect matching $M$ in $G$, the sub-graph $G^*=(V,E\setminus M)$ can be decomposed completely into edge-disjoint tours. This means $E(H)=E\setminus M$ for some perfect matching $M$ in $G$. Let $T$ be the tour in $G$ that goes through all edges in $M$, $M'=E(T)\setminus M$ be another perfect matching edge-disjoint with $M$, $H'$ be the set of all edges-disjoint tours in $G'=(V,E\setminus M')$, and $\mu=k(h+1)+r$ where $r\in[0,h]$ and $r\equiv \mu\bmod (h+1)$. We construct $P$ with the following steps: \begin{enumerate} \item Add all tours in $H$, each $\left\lfloor\frac{k+1}{2}\right\rfloor$ times \item Add all tours in $H'$, each $\left\lfloor\frac{k}{2}\right\rfloor$ times \item Add tour $T$ $k$ times \item Add all tours in $L$ where $L\subseteq H$ if $k$ is even, or $L\subseteq H'$ otherwise, such that $|L|=r$. \end{enumerate} The result is a population $P$ such that $|P|=\mu$. If $k$ is odd, $n(e,P)=k+1$ for all $e\in E(L)\cup M'$ and $n(e,P)=k$ otherwise. If $k$ is even and positive, $n(e,P)=k+1$ for all $e\in E(L)\cup M$ and $n(e,P)=k$ otherwise. If $k=0$, $n(e,P)=1$ for all $e\in E(L)$ and $n(e,P)=0$ otherwise. \end{proof} As demonstrated by the proof, a drawback of this approach is that it does not necessarily prevent duplication of tours in $P$ when $\mu$ is sufficiently large. This is because the sum of $L1$-norm distances is no more sensitive to small distances than large distances. Consequently, the diversity score based on it can still be large when the population consists of low-diversity sub-populations that are highly dissimilar. In other words, this approach is susceptible to clustering. In the context of EAs, this approach formulates a survival selection mechanism: removing from the population the individual $I\in\argmin_{I\in P}\{\mathcal{N}(P\setminus\{I\})\}$. For an efficient implementation, we consider an equivalent fitness function for each individual $I\in P$ \[n_P(I)=\text{sort}\left((n(e,P))_{e\in I}\right)\] with descending sorting order. The survival selection mechanism then removes $I\in\argmax_{I\in P}\{n_P(I)\}$. The equivalence can be shown. Since elements of $\mathcal{N}(P\setminus\{I\})$ and $n_P(I)$ are in descending order, they can each be uniquely defined by a vector $(m^I_i)_{i=1,\dots,\mu}$ and $(n^I_j)_{j=1,\dots,\mu}$, respectively, where $m^I_i$ and $n^I_i$ are numbers of elements in $\mathcal{N}(P\setminus\{I\})$ and $n_P(I)$ equal to $i$, respectively. For $X,Y\in P$, if $\mathcal{N}(P\setminus\{X\})<\mathcal{N}(P\setminus\{Y\})$ lexicographically, then there must be $j\in[1,\mu]$ such that $m^X_j<m^Y_j$ and $m^X_i=m^Y_i$ for all $i\in(j,\mu]$. Fewer elements equal to $j$ in $\mathcal{N}(P\setminus\{X\})$ must be the consequence of removing more of them, meaning $n^X_j>n^Y_j$ and $n^X_i=n^Y_i$ for all $i\in(j,\mu]$. This implies that $n_P(X)>n_P(Y)$ lexicographically. On the other hand, it is trivial to prove that $\mathcal{N}(P\setminus\{X\})=\mathcal{N}(P\setminus\{Y\})$ implies $n_P(X)=n_P(Y)$. This means \[\argmin_{I\in P}\{\mathcal{N}(P\setminus\{I\})\}=\argmax_{I\in P}\{n_P(I)\}.\] With this method, the survival selection mechanism is consisted of three phases: \begin{enumerate} \item Calculating the edge counts table: $O(\mu n)$ \item Calculating $n_P(I)$ for all $I$: $O(\mu n\log n)$ \item Finding and removing $I=\argmax_{I\in P}\{n_P(I)\}$: $O(\mu n)$ \end{enumerate} The complexity of the survival selection is then $O(\mu n\log n)$. On the other hand, the mechanism's complexity when using $gtype(P\setminus\{I\})$ as fitness values is $O(\mu^2n+\mu^3)$ ($O(\mu^2n)$ from calculating the edge distances table and $O(\mu^2)$ from calculating $gtype$ from said table for each tour). Asymptotically speaking, our proposal can be faster per iteration in many cases. \section{Equalising pairwise edge distances} \label{sec4} One way to remedy the clustering phenomenon is to increase edge distances between highly similar tours, potentially at the cost of decreasing edge distances between highly dissimilar tours. This method essentially equalises the tours' pairwise edge distances. As such, we present another approach that discourages clustering by emphasising uniform pairwise edge distances while maximising diversity. We reformulate the edge distance as edge overlap \begin{align*} o_{XY}=|E(X)\cap E(Y)|=n-|E(X)\setminus E(Y)|,\forall X,Y\in P. \end{align*} The aim is then to minimise the vector \begin{align*} \mathcal{D}(P) = \text{sort}\left(\left(o_{XY}\right)_{X,Y\in P}\right) \end{align*} in the lexicographic order where sorting is performed in descending order. This approach simultaneously maximises diversity via minimising $\sum_{X,Y\in P}o_{XY}$, while also maximising uniformity via equalising $o_{XY}$. It can be the case that $\mathcal{D}(P)<\mathcal{D}(P')$ and $gtype(P)<gtype(P')$. \begin{exm} Consider a problem instance with a complete graph of $n=5$ vertices and $\mu=3$. Let there be four tours $T_1=(1,3,5,4,2)$, $T_2=(1,5,4,3,2)$, $T_3=(1,2,5,3,4)$ and $T_4=(1,5,2,3,4)$, and two populations $P_1=\{T_1,T_2,T_3\}$ and $P_2=\{T_1,T_2,T_4\}$, we have \begin{itemize} \item $gtype(P_1)=18<gtype(P_2)=20$ \item $\mathcal{D}(P_1)=(2,2,2)<\mathcal{D}(P_2)=(3,2,0).$ \end{itemize} It is clear that $P_1$ maximises edge distances uniformity and $P_2$ maximises $gtype$. Furthermore, we can see that among all $3$-size populations of maximum $gtype$, $P_2$ maximises edge distances uniformity. Likewise, among all $3$-size populations of maximum edge distances uniformity, $P_1$ maximises $gtype$. This example shows that maximising $gtype$ and edge distances uniformity at the same time can be non-trivial. \end{exm} In such cases, it is likely that $o_{XY}$ are more equalised in $P$ than in $P'$. Moreover, the more $gtype(P)$ is larger than $gtype(P')$, the more likely that $\mathcal{D}(P)<\mathcal{D}(P')$. This means evolving with lowering $\mathcal{D}(P)$ as the evolutionary force tends to increase the $gtype$ score. However, the maximisation performance is potentially compromised by the emphasis on edge distances uniformity, so the $gtype$ score can decrease and its maximum is sometimes unreachable. Given the drawback of this diversity measure, this may not be undesirable. \begin{table*}[t] \renewcommand{\arraystretch}{1.2845} \renewcommand\tabcolsep{3.1pt} \caption{Comparison in terms of diversity (gtype), the number of iterations (\#iter) and results of statistical testing (stat) between variants with ED approach in unconstrained cases. The Kruskal-Wallis test and the Bonferroni correction method~\cite{Corder09} are used on \#iter. $X^+$ means the measure is larger than the one for variant $X$, $X^-$ means smaller and $X^*$ means no difference. } \label{tb:Edge_counts} \begin{scriptsize} \begin{tabular}{@{}rrccrrcccrrcccrrc} \toprule \multirow{2}{*}{$n$} & \multirow{2}{*}{$\mu$} & \multicolumn{5}{c}{\bfseries 2-OPT(1)} & \multicolumn{5}{c}{\bfseries 3-OPT(2)} & \multicolumn{5}{c}{\bfseries 4-OPT(3)} \\ \cmidrule(l{2pt}r{2pt}){3-7} \cmidrule(l{2pt}r{2pt}){8-12} \cmidrule(l{2pt}r{2pt}){13-17} & & \textbf{gtype} & \textbf{std} & \textbf{\# iter} &\textbf{std} & \textbf{stat} &\textbf{gtype} & \textbf{std} & \textbf{\# iter} &\textbf{std} & \textbf{stat} & \textbf{gtype} & \textbf{std} & \textbf{\# iter} &\textbf{std} & \textbf{stat}\\ \midrule \multirow{4}{*}{50}&3&100.00\%&0.00&104.50&59.19&$2^{+},3^{+}$&100.00\%&0.00&68.60&35.67&$1^{-},3^{*}$&100.00\%&0.00&\textbf{54.37}&24.28&$1^{-},2^{*}$\\ &10&100.00\%&0.00&\textbf{1635.80}&485.88&$2^{*},3^{*}$&100.00\%&0.00&1808.43&484.96&$1^{*},3^{*}$&100.00\%&0.00&1736.60&545.36&$1^{*},2^{*}$\\ &20&100.00\%&0.00&\textbf{25383.03}&8594.81&$2^{-},3^{-}$&99.97\%&0.02&49881.60&471.00&$1^{+},3^{*}$&99.93\%&0.02&50000.00&0.00&$1^{+},2^{*}$\\ &50&99.99\%&0.00&\textbf{125000.00}&0.00&$2^{*},3^{*}$&99.95\%&0.00&\textbf{125000.00}&0.00&$1^{*},3^{*}$&99.93\%&0.01&\textbf{125000.00}&0.00&$1^{*},2^{*}$\\ \hline \multirow{4}{*}{100}&3&100.00\%&0.00&170.83&98.50&$2^{*},3^{+}$&100.00\%&0.00&137.53&69.76&$1^{*},3^{*}$&100.00\%&0.00&\textbf{102.13}&58.69&$1^{-},2^{*}$\\ &10&100.00\%&0.00&1901.73&632.60&$2^{*},3^{+}$&100.00\%&0.00&1598.80&386.85&$1^{*},3^{+}$&100.00\%&0.00&\textbf{1305.63}&343.38&$1^{-},2^{-}$\\ &20&100.00\%&0.00&\textbf{8422.40}&1742.96&$2^{-},3^{*}$&100.00\%&0.00&9902.63&1984.39&$1^{+},3^{*}$&100.00\%&0.00&9414.27&2018.82&$1^{*},2^{*}$\\ &50&99.95\%&0.00&\textbf{500000.00}&0.00&$2^{*},3^{*}$&99.86\%&0.00&\textbf{500000.00}&0.00&$1^{*},3^{*}$&99.82\%&0.01&\textbf{500000.00}&0.00&$1^{*},2^{*}$\\ \hline \multirow{4}{*}{200}&3&100.00\%&0.00&401.03&213.80&$2^{+},3^{+}$&100.00\%&0.00&254.80&111.06&$1^{-},3^{*}$&100.00\%&0.00&\textbf{197.60}&78.85&$1^{-},2^{*}$\\ &10&100.00\%&0.00&3350.47&958.53&$2^{+},3^{+}$&100.00\%&0.00&2261.10&570.16&$1^{-},3^{*}$&100.00\%&0.00&\textbf{1888.87}&510.91&$1^{-},2^{*}$\\ &20&100.00\%&0.00&10189.73&2233.72&$2^{+},3^{+}$&100.00\%&0.00&8959.07&2242.66&$1^{-},3^{*}$&100.00\%&0.00&\textbf{7901.73}&1286.07&$1^{-},2^{*}$\\ &50&100.00\%&0.00&\textbf{76856.37}&14056.12&$2^{-},3^{-}$&100.00\%&0.00&102039.53&17118.06&$1^{+},3^{-}$&100.00\%&0.00&132837.73&25315.99&$1^{+},2^{+}$\\ \hline \multirow{4}{*}{500}&3&100.00\%&0.00&974.33&509.02&$2^{+},3^{+}$&100.00\%&0.00&631.20&267.24&$1^{-},3^{*}$&100.00\%&0.00&\textbf{560.77}&332.16&$1^{-},2^{*}$\\ &10&100.00\%&0.00&6608.33&2298.31&$2^{*},3^{+}$&100.00\%&0.00&5281.23&1729.61&$1^{*},3^{+}$&100.00\%&0.00&\textbf{3537.07}&965.71&$1^{-},2^{-}$\\ &20&100.00\%&0.00&20888.53&5343.92&$2^{+},3^{+}$&100.00\%&0.00&15007.67&3265.35&$1^{-},3^{+}$&100.00\%&0.00&\textbf{11821.93}&3388.06&$1^{-},2^{-}$\\ &50&100.00\%&0.00&93280.70&17697.95&$2^{+},3^{+}$&100.00\%&0.00&67817.73&13010.55&$1^{-},3^{*}$&100.00\%&0.00&\textbf{64425.13}&9267.66&$1^{-},2^{*}$\\ \hline \end{tabular} \end{scriptsize} \end{table*} \begin{table*}[htbp] \renewcommand{\arraystretch}{1.2845} \renewcommand\tabcolsep{3.1pt} \caption{Comparison in terms of diversity (gtype), the number of iterations (\#iter) and results of statistical testing (stat) between variants with PD approach in unconstrained cases. Tests and notations used are the same as in Table~\ref{tb:Edge_counts}.} \label{tb:Pair_dist} \begin{scriptsize} \begin{tabular}{@{}rrccrrcccrrcccrrc} \toprule \multirow{2}{*}{$n$} & \multirow{2}{*}{$\mu$} & \multicolumn{5}{c}{\bfseries 2-OPT(1)} & \multicolumn{5}{c}{\bfseries 3-OPT(2)} & \multicolumn{5}{c}{\bfseries 4-OPT(3)} \\ \cmidrule(l{2pt}r{2pt}){3-7} \cmidrule(l{2pt}r{2pt}){8-12} \cmidrule(l{2pt}r{2pt}){13-17} & & \textbf{gtype} & \textbf{std} & \textbf{\# iter} &\textbf{std} & \textbf{stat} &\textbf{gtype} & \textbf{std} & \textbf{\# iter} &\textbf{std} & \textbf{stat} & \textbf{gtype} & \textbf{std} & \textbf{\# iter} &\textbf{std} & \textbf{stat}\\ \midrule \multirow{4}{*}{50}&3&100.00\%&0.00&83.43&42.67&$2^{*},3^{+}$&100.00\%&0.00&67.03&31.22&$1^{*},3^{*}$&100.00\%&0.00&\textbf{59.53}&39.87&$1^{-},2^{*}$\\ &10&100.00\%&0.00&\textbf{1493.13}&380.08&$2^{*},3^{*}$&100.00\%&0.00&1605.20&472.96&$1^{*},3^{*}$&100.00\%&0.00&1748.20&659.40&$1^{*},2^{*}$\\ &20&100.00\%&0.00&\textbf{26794.30}&7051.89&$2^{-},3^{-}$&99.96\%&0.02&49955.43&244.10&$1^{+},3^{*}$&99.92\%&0.02&50000.00&0.00&$1^{+},2^{*}$\\ &50&99.89\%&0.01&\textbf{125000.00}&0.00&$2^{*},3^{*}$&99.76\%&0.01&\textbf{125000.00}&0.00&$1^{*},3^{*}$&99.72\%&0.01&\textbf{125000.00}&0.00&$1^{*},2^{*}$\\ \hline \multirow{4}{*}{100}&3&100.00\%&0.00&211.83&83.51&$2^{+},3^{+}$&100.00\%&0.00&109.27&61.33&$1^{-},3^{*}$&100.00\%&0.00&\textbf{107.07}&54.83&$1^{-},2^{*}$\\ &10&100.00\%&0.00&1853.67&411.67&$2^{+},3^{+}$&100.00\%&0.00&1563.40&412.61&$1^{-},3^{*}$&100.00\%&0.00&\textbf{1403.73}&458.76&$1^{-},2^{*}$\\ &20&100.00\%&0.00&\textbf{8377.83}&1259.16&$2^{*},3^{-}$&100.00\%&0.00&9648.03&2079.70&$1^{*},3^{*}$&100.00\%&0.00&9895.17&2165.04&$1^{+},2^{*}$\\ &50&99.94\%&0.00&\textbf{500000.00}&0.00&$2^{*},3^{*}$&99.83\%&0.01&\textbf{500000.00}&0.00&$1^{*},3^{*}$&99.77\%&0.01&\textbf{500000.00}&0.00&$1^{*},2^{*}$\\ \hline \multirow{4}{*}{200}&3&100.00\%&0.00&451.60&249.54&$2^{+},3^{+}$&100.00\%&0.00&285.97&155.56&$1^{-},3^{*}$&100.00\%&0.00&\textbf{209.80}&79.16&$1^{-},2^{*}$\\ &10&100.00\%&0.00&3161.17&751.84&$2^{+},3^{+}$&100.00\%&0.00&2271.67&624.29&$1^{-},3^{+}$&100.00\%&0.00&\textbf{1769.40}&384.22&$1^{-},2^{-}$\\ &20&100.00\%&0.00&9776.93&1925.45&$2^{+},3^{+}$&100.00\%&0.00&7550.90&1390.00&$1^{-},3^{*}$&100.00\%&0.00&\textbf{7371.20}&1388.57&$1^{-},2^{*}$\\ &50&100.00\%&0.00&\textbf{77706.33}&13011.40&$2^{-},3^{-}$&100.00\%&0.00&106661.57&19402.75&$1^{+},3^{-}$&100.00\%&0.00&132255.53&30508.53&$1^{+},2^{+}$\\ \hline \multirow{4}{*}{500}&3&100.00\%&0.00&828.90&320.42&$2^{+},3^{+}$&100.00\%&0.00&552.70&276.51&$1^{-},3^{*}$&100.00\%&0.00&\textbf{499.20}&258.36&$1^{-},2^{*}$\\ &10&100.00\%&0.00&7036.17&1475.13&$2^{+},3^{+}$&100.00\%&0.00&4686.20&972.09&$1^{-},3^{*}$&100.00\%&0.00&\textbf{3806.03}&971.33&$1^{-},2^{*}$\\ &20&100.00\%&0.00&19258.20&4942.90&$2^{+},3^{+}$&100.00\%&0.00&13667.33&3053.62&$1^{-},3^{*}$&100.00\%&0.00&\textbf{12294.77}&2767.25&$1^{-},2^{*}$\\ &50&100.00\%&0.00&80004.13&9644.84&$2^{+},3^{+}$&100.00\%&0.00&69792.40&13370.98&$1^{-},3^{*}$&100.00\%&0.00&\textbf{63174.17}&10205.59&$1^{-},2^{*}$\\ \hline \end{tabular} \end{scriptsize} \end{table*} For a problem instance with graph $G$ and integer $\mu$, assuming there is a population $P^*$ with maximum $gtype$ \[2\sum_{X,Y\in P^*}o_{XY}=\mu(\mu-1)n-\max_P\{gtype(P)\},\] and maximum edge distances uniformity \[\max_{X,Y\in P}\{o_{XY}\}-\min_{X,Y\in P}\{o_{XY}\}\leq1,\] then $P^*\in\argmin_P\{\mathcal{D}(P)\}$. When $G$ is complete and $\mu\leq\left\lfloor\frac{n-1}{2}\right\rfloor$, this assumption is true according to the proof for Theorem~\ref{theo:ed_opt}, and $o_{XY}$ are all zero in $P^*$. Like the ED approach, this approach determines the survival mechanism of the EA: removing from the population the individual $I\in\argmin_{I\in P}\{\mathcal{D}(P\setminus\{I\})\}$. The same method can be used to derive an efficient implementation of $O(\mu^2n+\mu^2\log\mu)$ time complexity for this mechanism. Consider the fitness function \[d_P(I)=\text{sort}\left((o_{IX})_{X\in P\setminus\{I\}}\right)\] with descending sorting order, it can be shown that $\argmin_I\{\mathcal{D}(P\setminus\{I\})\}=\argmax_I\{d_P(I)\}$. As before, we can uniquely define $\mathcal{D}(P)$ and $d_P(I)$ with $(m_i)_{i=1,\dots,n}$ and $(n^I_i)_{i=1,\dots,n}$, respectively. This implies that $\mathcal{D}(P\setminus\{I\})$ is defined by $(m_i-n^I_i)_{i=1,\dots,n}$. For $X,Y\in P$, if $\mathcal{D}(P\setminus\{X\})<\mathcal{D}(P\setminus\{Y\})$ lexicographically, then it must be that there is $j\in[1,n]$ such that $n^X_j>n^Y_j$ and $n^X_i=n^Y_i$ for all $i\in(j,n]$. This means $d_P(X)>d_P(Y)$. Furthermore, $\mathcal{D}(P\setminus\{X\})<\mathcal{D}(P\setminus\{Y\})$ obviously implies $d_P(X)=d_P(Y)$. Intuitively, this implementation removes $I$ that has the smallest edge distance to $P\setminus\{I\}$, defined by the minimum edge distance between $I$ and all tours in $P\setminus\{I\}$. The lexicographic ordering of vectors allows an elegant way to resolve draw cases: comparing the second minimum distances, the third, the fourth and so on. The result is the guaranteed non-increasing edge distance between $I'$ and $P\setminus\{I'\}$ for all other tours $I'$ as well. The consequence is convergence to a solution population, in which each tour is reasonably dissimilar to the rest. This approach aligns closely with the diversity formulated in \cite{DiversityManyObj}, with edge distance being the dissimilarity metric. Since $\mu$ is fixed, we introduce an additional normalization factor. \[div(P)=\sum_{T\in P}dist(T,P\setminus\{T\})=\frac{1}{\mu n}\sum_{T\in P}\min_{X\in P\setminus\{T\}}\left\lbrace|E(T)\setminus E(X)|\right\rbrace.\] Note that the difference between $gtype$ and $div$ is the focus on the minimum edge distances, the two measures would be the same if $min$ were replaced by $sum$ or $mean$. We hypothesise that edge distances uniformity is strongly positively correlated to $div$. This is explored further in Section \ref{sec5}. \section{Experimental investigations} \label{sec5} We perform different series of experiments to gain insights into the process of evolving diverse TSP tours. In all experiments our input is a complete graph $G = (V, E)$ with real-valued cost function $w : E \to \mathbb{R}^{+}$. We consider 6 variants of algorithm \ref{alg:ea}, differing in their mutation operators and survival selection mechanisms. The mutation operators are 2-OPT, 3-OPT, 4-OPT, and the survival selection mechanisms are based on the two proposed approaches. \subsection{Unconstrained Diversity Optimisation} In this setting our focus is on diverse TSP tours without constraints on tours' qualities. As such, we study our approaches with random initial populations. We experiment with all combinations of $n=\{50,100,200,500\}$ and $\mu=\{3,10,20,50\}$. For each $(n,\mu)$ combination, 30 populations are randomly generated as initial populations for all EA variants, controlling for the initialisation factor. Furthermore, with the established guarantee for optima, a termination criterion is such optima are reached. As for minimising $\mathcal{D}(P)$, another criterion \[\max_{X,Y\in P}\{o_{XY}\}-\min_{X,Y\in P}\{o_{XY}\}\leq1\] is added forming a bound on the optima. An additional limit of $\mu n^2$ iterations is imposed on the experiments. Also, since optimal $gtype$ scores can be calculated, we record the scores in percentages for ease of comparison across all settings. According to Tables \ref{tb:Edge_counts}, \ref{tb:Pair_dist}, all variants seem to reliably achieve optima in all cases where $\mu\leq\left\lfloor\frac{n-1}{2}\right\rfloor$, except for 4-OPT variants seemingly stuck in local optima when $n=50$ and $\mu=20$. In the other hard cases, none ever reached the optima within the time limits. This suggests that when close to the optima, the probability of increasing $gtype$ in an iteration decreases substantially with increasing $\mu/n$. Also, in such cases, all variants with 2-OPT mutation operator achieve higher $gtype$ score than those with 3-OPT, which in turn outperform those with 4-OPT. Furthermore, for $(n,\mu)=(50,20)$, all 2-OPT variants always reaches the optimum, while 3-OPT variants struggle and 4-OPT variants fail entirely. This indicates that large-step mutation operators are prone to being stuck in local optima when the population is close to maximum $gtype$. Additionally, minimising $\mathcal{N}(P)$ and minimising $\mathcal{D}(P)$ seem to produce the similar final $gtype$ scores within similar numbers of iterations in all cases, given the same mutation operator used. This indicates that minimising $\mathcal{D}(P)$ also tends to maximise $gtype$ when all tours are accepted. However, in the hard cases, the PD approach achieves somewhat lower $gtype$ scores than ED across all variants. This suggests that the trade-offs between edge diversity and edge distances uniformity are non-trivial near optima. Another observation is that with small enough $\mu/n$, 2-OPT variants tend to take more iterations than 3-OPT variants, which in turn tend to terminate later than 4-OPT variants. When $\mu/n$ is larger than some number, the trend seems to revert. However, the indication for this observation is weak since no statistically significant difference can be seen in many cases. \subsection{Constrained Diversity Optimisation} Now we consider TSP instances from the famous TSPlib, specifically eil51, eil76, eil101. For these experiments, we use the provided optimal tour for each instance, initialise $P$ with $\mu$ copies of it and perform diversity maximisation subject to $c(I) \leq (1 + \alpha)\cdot OPT$ for all $I \in P$. I.~e., we accept tours only if they deviate in length by a factor of at most $(1+\alpha)$ from the optimal tour length OPT. We set up the instances for our experiments with $\mu=\{5,10,20,50\}$ and $\alpha=\{0.05, 0.2, 0.5, 1.0\}$. For each instance, we run each algorithm variant 30 times and record the final population. As before, $gtype$ scores are reported in percentages, since these instances involve complete graphs and Theorem~\ref{theo:ed_opt} applies. In addition, we record $\varsigma(P)=\left(\max_{X,Y\in P}\{o_{XY}\}-\min_{X,Y\in P}\{o_{XY}\}\right)/n$ to observe uniformity in edge distances between tours; lower scores indicate higher uniformity. All scores are averaged over 30 runs. According to Table~\ref{tb:TSPlib}, $gtype$ scores achieved predictably increase with increasing $\alpha$, albeit with diminishing return. On the other hand, $\varsigma$ scores tend to increase with increasing $\mu$, and dramatically decrease with increasing $\alpha$. In terms of mutation operators, 2-OPT seems to be the best performer overall, while 3-OPT and 4-OPT perform similar. Furthermore, all things equal, minimising $\mathcal{N}(P)$ tends to produce slightly higher $gtype$ scores and noticeably lower $\varsigma$ scores than minimising $\mathcal{D}(P)$. The PD approach seems to better capitalise on increasing $\alpha$, improving edge distances uniformity faster. Moreover, the edge distances uniformity of the PD approach's output populations is less susceptible to compromise due to increasing $\mu$ within this range. These phenomena align with the remark that the ED approach focuses on $gtype$ while the PD approach compromises it for edge distances uniformity. \begin{table*}[htbp] \renewcommand{\arraystretch}{1.2845} \renewcommand\tabcolsep{5.7pt} \caption{Comparison in terms of diversity (gtype) and pairwise edge distances ranges ($\varsigma$) among all variants of the EA on TSPlib instances. Better values with statistical significance (based on Wilcoxon rank sum tests with 95\% confidence threshold) between ED and PD are bold-faced. } \label{tb:TSPlib} \begin{scriptsize} \begin{tabular}{crrcccccccccccc} \toprule \multirow{3}{*}{\textbf{}}&\multirow{3}{*}{\textbf{$\mu$}} & \multirow{3}{*}{\textbf{$\alpha$}} & \multicolumn{6}{c}{\bfseries ED} & \multicolumn{6}{c}{\bfseries PD}\\ \cmidrule(l{2pt}r{2pt}){4-9} \cmidrule(l{2pt}r{2pt}){10-15} & & & \multicolumn{2}{c}{\bfseries2-OPT} & \multicolumn{2}{c}{\bfseries3-OPT}& \multicolumn{2}{c}{\bfseries4-OPT}& \multicolumn{2}{c}{\bfseries2-OPT} & \multicolumn{2}{c}{\bfseries3-OPT}& \multicolumn{2}{c}{\bfseries4-OPT} \\ \cmidrule(l{2pt}r{2pt}){4-5} \cmidrule(l{2pt}r{2pt}){6-7} \cmidrule(l{2pt}r{2pt}){8-9} \cmidrule(l{2pt}r{2pt}){10-11} \cmidrule(l{2pt}r{2pt}){12-13} \cmidrule(l{2pt}r{2pt}){14-15} &&&\textbf{gtype}&\textbf{$\varsigma$}&\textbf{gtype}&\textbf{$\varsigma$}&\textbf{gtype}&\textbf{$\varsigma$}&\textbf{gtype}&\textbf{$\varsigma$}&\textbf{gtype}&\textbf{$\varsigma$}&\textbf{gtype}&\textbf{$\varsigma$}\\ \midrule \multirow{20}{*}[0.5cm]{\rotatebox[origin=c]{90}{eil51}}&3&0.05&34.27\%&68.37\%&36.23\%&67.78\%&28.95\%&74.05\%&32.07\%&69.54\%&35.95\%&66.14\%&29.78\%&71.96\%\\& &0.2&70.78\%&31.83\%&67.93\%&35.03\%&63.68\%&40.46\%&71.11\%&30.20\%&65.95\%&35.75\%&63.12\%&38.56\%\\& &0.5&93.83\%&8.43\%&90.85\%&11.05\%&90.78\%&11.37\%&93.62\%&\textbf{7.12\%}&90.26\%&11.18\%&90.37\%&10.59\%\\& &1&99.89\%&0.13\%&99.83\%&0.26\%&99.80\%&0.33\%&99.80\%&0.33\%&99.74\%&0.65\%&99.76\%&0.52\%\\\cmidrule(l{2pt}r{2pt}){2-15} &10&0.05&\textbf{31.82\%}&79.67\%&\textbf{33.64\%}&78.43\%&27.79\%&82.88\%&29.37\%&78.24\%&31.60\%&\textbf{75.95\%}&27.65\%&\textbf{79.61\%}\\& &0.2&\textbf{63.04\%}&70.39\%&\textbf{60.60\%}&67.12\%&\textbf{57.78\%}&63.40\%&60.99\%&\textbf{44.90\%}&59.23\%&\textbf{47.39\%}&55.99\%&\textbf{51.31\%}\\& &0.5&\textbf{83.14\%}&30.85\%&\textbf{81.34\%}&36.67\%&\textbf{81.29\%}&37.58\%&82.00\%&\textbf{20.33\%}&80.12\%&\textbf{23.01\%}&79.87\%&\textbf{23.99\%}\\& &1&\textbf{95.06\%}&10.26\%&\textbf{94.14\%}&11.76\%&\textbf{94.19\%}&11.63\%&94.57\%&\textbf{7.58\%}&93.30\%&\textbf{8.50\%}&93.16\%&\textbf{8.50\%}\\\cmidrule(l{2pt}r{2pt}){2-15} &20&0.05&\textbf{32.52\%}&95.23\%&\textbf{32.86\%}&91.37\%&\textbf{27.89\%}&90.85\%&29.20\%&\textbf{82.42\%}&31.23\%&\textbf{79.08\%}&26.45\%&\textbf{83.53\%}\\& &0.2&\textbf{62.32\%}&92.09\%&\textbf{59.98\%}&91.57\%&\textbf{57.46\%}&91.70\%&59.30\%&\textbf{49.15\%}&57.84\%&\textbf{51.37\%}&54.53\%&\textbf{55.29\%}\\& &0.5&\textbf{80.95\%}&59.02\%&\textbf{79.24\%}&63.27\%&\textbf{79.60\%}&64.84\%&79.03\%&\textbf{25.29\%}&77.69\%&\textbf{27.84\%}&77.32\%&\textbf{29.08\%}\\& &1&\textbf{92.17\%}&19.87\%&\textbf{91.41\%}&22.42\%&\textbf{91.58\%}&21.31\%&90.97\%&\textbf{11.83\%}&90.28\%&\textbf{12.42\%}&90.24\%&\textbf{12.75\%}\\\cmidrule(l{2pt}r{2pt}){2-15} &50&0.05&\textbf{32.66\%}&100.00\%&\textbf{33.23\%}&100.00\%&\textbf{28.01\%}&100.00\%&29.81\%&\textbf{85.88\%}&31.75\%&\textbf{82.48\%}&26.93\%&\textbf{85.95\%}\\& &0.2&\textbf{63.26\%}&99.48\%&\textbf{61.52\%}&97.78\%&\textbf{58.92\%}&96.99\%&59.68\%&\textbf{53.59\%}&58.36\%&\textbf{57.12\%}&55.04\%&\textbf{59.80\%}\\& &0.5&\textbf{80.74\%}&92.35\%&\textbf{79.56\%}&90.59\%&\textbf{79.80\%}&88.76\%&79.15\%&\textbf{29.67\%}&78.12\%&\textbf{32.29\%}&77.94\%&\textbf{33.66\%}\\& &1&\textbf{91.65\%}&48.95\%&\textbf{91.25\%}&52.68\%&\textbf{91.33\%}&48.37\%&90.60\%&\textbf{15.69\%}&90.42\%&\textbf{15.75\%}&90.42\%&\textbf{16.67\%}\\\hline \multirow{20}{*}[0.5cm]{\rotatebox[origin=c]{90}{eil76}}&3&0.05&30.12\%&71.84\%&30.06\%&72.89\%&24.20\%&78.60\%&29.04\%&71.97\%&29.80\%&71.89\%&24.08\%&76.97\%\\& &0.2&70.23\%&31.67\%&63.98\%&38.90\%&60.39\%&42.02\%&69.05\%&32.15\%&63.17\%&37.76\%&59.11\%&42.06\%\\& &0.5&94.66\%&6.49\%&90.63\%&11.45\%&91.05\%&11.14\%&94.72\%&5.88\%&90.82\%&\textbf{9.74\%}&90.29\%&10.61\%\\& &1&99.91\%&0.22\%&99.63\%&0.57\%&99.80\%&0.48\%&99.90\%&0.09\%&99.65\%&0.53\%&99.69\%&0.57\%\\\cmidrule(l{2pt}r{2pt}){2-15} &10&0.05&\textbf{28.52\%}&79.39\%&\textbf{29.33\%}&78.95\%&23.14\%&83.60\%&27.09\%&78.73\%&28.35\%&79.17\%&22.87\%&82.59\%\\& &0.2&\textbf{61.56\%}&57.19\%&\textbf{58.62\%}&56.75\%&\textbf{56.01\%}&60.13\%&59.57\%&\textbf{44.91\%}&56.41\%&\textbf{49.08\%}&53.67\%&\textbf{52.24\%}\\& &0.5&\textbf{84.71\%}&28.60\%&\textbf{81.03\%}&36.45\%&\textbf{81.92\%}&33.64\%&82.94\%&\textbf{18.99\%}&79.54\%&\textbf{23.07\%}&79.45\%&\textbf{23.90\%}\\& &1&\textbf{95.92\%}&7.94\%&\textbf{94.39\%}&9.96\%&\textbf{94.78\%}&9.43\%&95.32\%&\textbf{5.83\%}&93.66\%&\textbf{7.72\%}&93.74\%&\textbf{7.72\%}\\\cmidrule(l{2pt}r{2pt}){2-15} &20&0.05&\textbf{28.74\%}&88.95\%&\textbf{28.85\%}&88.68\%&\textbf{23.69\%}&88.42\%&26.96\%&\textbf{81.49\%}&27.38\%&\textbf{81.97\%}&22.25\%&\textbf{85.18\%}\\& &0.2&\textbf{61.19\%}&92.76\%&\textbf{58.37\%}&92.89\%&\textbf{56.06\%}&91.45\%&58.50\%&\textbf{48.29\%}&55.41\%&\textbf{53.16\%}&52.20\%&\textbf{56.67\%}\\& &0.5&\textbf{82.35\%}&53.90\%&\textbf{79.64\%}&65.39\%&\textbf{80.32\%}&58.68\%&79.72\%&\textbf{23.73\%}&77.58\%&\textbf{26.84\%}&77.40\%&\textbf{28.42\%}\\& &1&\textbf{93.03\%}&16.10\%&\textbf{91.95\%}&20.04\%&\textbf{92.37\%}&18.11\%&91.67\%&\textbf{10.26\%}&90.67\%&\textbf{11.58\%}&90.78\%&\textbf{11.84\%}\\\cmidrule(l{2pt}r{2pt}){2-15} &50&0.05&\textbf{28.84\%}&100.00\%&\textbf{28.41\%}&99.91\%&\textbf{23.99\%}&98.95\%&27.01\%&\textbf{84.47\%}&27.77\%&\textbf{85.09\%}&22.52\%&\textbf{87.28\%}\\& &0.2&\textbf{62.42\%}&98.95\%&\textbf{59.32\%}&98.73\%&\textbf{56.80\%}&98.07\%&58.16\%&\textbf{52.54\%}&55.73\%&\textbf{56.80\%}&52.29\%&\textbf{60.35\%}\\& &0.5&\textbf{81.53\%}&86.62\%&\textbf{79.74\%}&90.39\%&\textbf{80.35\%}&88.03\%&79.05\%&\textbf{27.50\%}&77.21\%&\textbf{31.01\%}&77.08\%&\textbf{32.63\%}\\& &1&\textbf{91.73\%}&42.19\%&\textbf{91.18\%}&46.62\%&\textbf{91.39\%}&38.55\%&90.32\%&\textbf{13.68\%}&89.84\%&\textbf{14.78\%}&90.02\%&\textbf{14.91\%}\\\hline \multirow{20}{*}[0.5cm]{\rotatebox[origin=c]{90}{eil101}}&3&0.05&35.84\%&65.97\%&\textbf{36.79\%}&65.74\%&31.21\%&70.99\%&35.69\%&65.71\%&35.49\%&65.51\%&30.24\%&70.69\%\\& &0.2&\textbf{72.61\%}&29.60\%&67.50\%&34.69\%&65.30\%&36.40\%&71.29\%&29.11\%&65.56\%&35.08\%&63.99\%&36.83\%\\& &0.5&95.03\%&5.91\%&91.86\%&9.64\%&92.29\%&9.27\%&94.72\%&5.78\%&91.60\%&8.98\%&91.63\%&9.11\%\\& &1&99.79\%&0.40\%&99.49\%&0.76\%&99.72\%&0.50\%&99.81\%&0.36\%&99.57\%&0.66\%&99.85\%&\textbf{0.23\%}\\\cmidrule(l{2pt}r{2pt}){2-15} &10&0.05&31.88\%&76.27\%&\textbf{33.44\%}&74.19\%&\textbf{28.88\%}&78.88\%&31.36\%&\textbf{73.37\%}&32.60\%&\textbf{72.05\%}&27.77\%&\textbf{76.93\%}\\& &0.2&\textbf{63.70\%}&49.64\%&\textbf{60.78\%}&54.16\%&\textbf{58.69\%}&55.38\%&62.44\%&\textbf{40.89\%}&59.29\%&\textbf{44.95\%}&56.49\%&\textbf{47.95\%}\\& &0.5&\textbf{85.14\%}&25.78\%&\textbf{82.55\%}&30.43\%&\textbf{82.75\%}&33.00\%&83.84\%&\textbf{17.52\%}&81.64\%&\textbf{20.20\%}&80.78\%&\textbf{21.55\%}\\& &1&\textbf{96.29\%}&6.80\%&\textbf{95.07\%}&9.08\%&\textbf{95.25\%}&8.75\%&95.97\%&\textbf{4.95\%}&94.37\%&\textbf{6.77\%}&94.37\%&\textbf{6.86\%}\\\cmidrule(l{2pt}r{2pt}){2-15} &20&0.05&\textbf{32.80\%}&85.28\%&\textbf{33.52\%}&85.31\%&\textbf{28.74\%}&85.97\%&30.58\%&\textbf{76.63\%}&31.78\%&\textbf{75.38\%}&27.21\%&\textbf{79.90\%}\\& &0.2&\textbf{63.37\%}&92.48\%&\textbf{60.27\%}&89.70\%&\textbf{58.75\%}&89.90\%&60.83\%&\textbf{44.36\%}&58.11\%&\textbf{48.91\%}&55.30\%&\textbf{51.16\%}\\& &0.5&\textbf{82.93\%}&56.17\%&\textbf{80.68\%}&57.49\%&\textbf{81.19\%}&55.68\%&81.04\%&\textbf{21.22\%}&79.08\%&\textbf{24.19\%}&79.05\%&\textbf{25.21\%}\\& &1&\textbf{93.71\%}&14.98\%&\textbf{92.62\%}&17.99\%&\textbf{93.06\%}&15.91\%&92.28\%&\textbf{9.01\%}&91.31\%&\textbf{10.23\%}&91.42\%&\textbf{10.43\%}\\\cmidrule(l{2pt}r{2pt}){2-15} &50&0.05&\textbf{34.32\%}&100.00\%&\textbf{33.17\%}&99.47\%&\textbf{28.96\%}&99.01\%&30.26\%&\textbf{79.44\%}&31.34\%&\textbf{78.75\%}&26.91\%&\textbf{82.71\%}\\& &0.2&\textbf{63.92\%}&98.48\%&\textbf{60.95\%}&97.92\%&\textbf{59.39\%}&97.66\%&59.76\%&\textbf{48.25\%}&57.89\%&\textbf{52.24\%}&54.86\%&\textbf{55.74\%}\\& &0.5&\textbf{81.65\%}&86.30\%&\textbf{79.96\%}&90.23\%&\textbf{80.51\%}&85.87\%&79.34\%&\textbf{24.85\%}&78.20\%&\textbf{27.36\%}&77.85\%&\textbf{28.84\%}\\& &1&\textbf{91.58\%}&34.69\%&\textbf{90.88\%}&45.38\%&\textbf{91.20\%}&36.60\%&90.01\%&\textbf{12.34\%}&89.60\%&\textbf{13.17\%}&89.80\%&\textbf{13.43\%}\\\hline \end{tabular} \end{scriptsize} \end{table*} \begin{figure}[t] \centering \begin{subfigure}{0.4\linewidth} \centering \includegraphics[width=1\linewidth]{images/uniform_vs_div.eps} \caption{$\varsigma$ and $div$}\label{fig:uniform_div_corr} \end{subfigure} \begin{subfigure}{0.4\linewidth} \centering \includegraphics[width=1\linewidth]{images/gtype_vs_div.eps} \caption{$gtype$ and $div$}\label{fig:gtype_div} \end{subfigure} \caption{ Scatter plots of all 8640 runs on the TSPlib instances. Each point corresponds to a final population after one run. The Pearson correlation coefficient between $\varsigma$ and $div$ is $-0.9815$ with $p<0.0001$.} \end{figure} Additionally, we investigate the correlation between edge distances uniformity and the diversity score $div(P)$. Figure \ref{fig:uniform_div_corr} shows a strong negative linear correlation between $div(P)$ and $\varsigma(P)$ across all cases. This suggests that focusing on edge distances uniformity, while maximising $gtype$, is effective in maximising $div$. Combined with earlier observations, we can conclude that the PD approach is much more likely to make a better compromise between maximising $gtype$ and maximising $div$. This is illustrated in Figure~\ref{fig:gtype_div}, indicating that for each $\alpha$ value, the PD approach maintains higher $div$ scores across all $\mu$ values without significantly sacrificing $gtype$ scores. \begin{figure}[t] \centering \begin{subfigure}{0.24\linewidth} \centering \includegraphics[width=1\linewidth]{images/eil51_50_5_ec_2opt.eps} \caption{ED, $\alpha=0.05$} \end{subfigure} \begin{subfigure}{0.24\linewidth} \centering \includegraphics[width=1\linewidth]{images/eil51_50_20_ec_2opt.eps} \caption{ED, $\alpha=0.2$} \end{subfigure} \begin{subfigure}{0.24\linewidth} \centering \includegraphics[width=1\linewidth]{images/eil51_50_50_ec_2opt.eps} \caption{ED, $\alpha=0.5$} \end{subfigure} \begin{subfigure}{0.24\linewidth} \centering \includegraphics[width=1\linewidth]{images/eil51_50_100_ec_2opt.eps} \caption{ED, $\alpha=1.0$} \end{subfigure} \begin{subfigure}{0.24\linewidth} \centering \includegraphics[width=1\linewidth]{images/eil51_50_5_pd_2opt.eps} \caption{PD, $\alpha=0.05$} \end{subfigure} \begin{subfigure}{0.24\linewidth} \centering \includegraphics[width=1\linewidth]{images/eil51_50_20_pd_2opt.eps} \caption{PD, $\alpha=0.2$} \end{subfigure} \begin{subfigure}{0.24\linewidth} \centering \includegraphics[width=1\linewidth]{images/eil51_50_50_pd_2opt.eps} \caption{PD, $\alpha=0.5$} \end{subfigure} \begin{subfigure}{0.24\linewidth} \centering \includegraphics[width=1\linewidth]{images/eil51_50_100_pd_2opt.eps} \caption{PD, $\alpha=1.0$} \end{subfigure} \caption{Visualised edge counts from resulted populations in eil51 cases with $\mu=50$. The optimal tour is marked with red edges. Darker edges have higher counts.} \label{fig:edge_count} \end{figure} \begin{figure*}[htbp] \centering \begin{subfigure}{1\linewidth} \centering \includegraphics[width=1\linewidth]{images/eil51_10_5_ec_2opt_pop.eps} \caption{ED, $\alpha=5\%$} \end{subfigure} ~\\ \begin{subfigure}{1\linewidth} \centering \includegraphics[width=\linewidth]{images/eil51_10_5_pd_2opt_pop.eps} \caption{PD, $\alpha=5\%$} \end{subfigure} ~\\ \begin{subfigure}{1\linewidth} \centering \includegraphics[width=1\linewidth]{images/eil51_10_20_ec_2opt_pop.eps} \caption{ED, $\alpha=20\%$} \end{subfigure} ~\\ \begin{subfigure}{1\linewidth} \centering \includegraphics[width=1\linewidth]{images/eil51_10_20_pd_2opt_pop.eps} \caption{PD, $\alpha=20\%$} \end{subfigure} \caption{ Visualised tour populations from resulted populations in eil51 cases with $\mu=10$ and 2-OPT as mutation operator. Red edges are shared by at least two tours in the population, and blue ones are unique to the tour. Left-to-right is the ascending tour length order.} \label{fig:populations} \end{figure*} The visuals in Figure~\ref{fig:edge_count} show that the PD approach results in fewer zero-count edges than the ED, regardless of $\alpha$. It also results in higher maximum edge counts than the ED in those cases. This is because minimising $\mathcal{N}(P)$ flattens the edge counts distribution from the top down with the descending sorting order. The implication is that the counts distribution among the lower end is not guaranteed improvement, especially among the zero-count. On the other hand, minimising $\mathcal{D}(P)$, while not directly dealing with edge counts, tends to equalise this distribution while relaxing minimising higher count edges. Consequently, higher maximum edge counts are achieved, but fewer edges have high counts and more edges have low non-zero counts. Consequently, individuals are more likely to contain more unique edges (edges with count 1), which is also a mark of highly diverse populations. As Figure~\ref{fig:populations} shows, with small $\alpha$, the populations generated by the ED approach tend to contain duplicated tours and tours without unique edges. In contrast, tours produced by the PD approach tend to exhibit more uniqueness and stand out from the rest. \section{Conclusion} Evolutionary diversity optimisation aims to generate a set of diverse solutions where all solutions meet given quality criteria. We have introduced and examined for the first time evolutionary diversity optimisation for a classical combinatorial optimisation problems. We introduced two diversity measures that can be used for the Traveling Salesperson Problem and evaluated their performance when used for simple population-based elitist evolutionary algorithms. The results show that both measures can be optimized well in the unconstrained case where all tours meet the quality criterion. Furthermore, our investigations for TSPlib instances point out the increase in terms of diversity that can be obtained when relaxing the quality constraint determined by the required approximation ratio. We also highlighted some differences between populations generated by these two approaches. The focus of this paper has been on the introduced diversity measures for diversity optimisation of the TSP and their performance in simple population-based elitist evolutionary algorithms. For future research, it would be interesting to incorporate these measures into state of the art evolutionary algorithms for the TSP and evaluate their performance. \section*{Acknowledgment} This work has been supported by the Australian Research Council (ARC) through grant DP190103894. \bibliographystyle{unsrt}
{'timestamp': '2020-04-21T02:24:47', 'yymm': '2004', 'arxiv_id': '2004.09188', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09188'}
arxiv
\section{Introduction} \label{Introduction} \textbf{Increasing data traffic}. Wireless connectivity is regarded as a fundamental need for our society. Between 2020 and 2030, it is forecast that the data traffic of the global Internet protocol (IP) will increase by 55\% each year, eventually reaching 5,016 exabytes \cite{ITU_2015}, with data rates scaling up to 1 Tb/s \cite{Letaief_AI}. Besides supporting very high data rates, future wireless networks are expected to offer several other heterogeneous services, which include sensing, localization, low-latency and ultra-reliable communications. Fifth-generation (5G) networks are, however, not designed to meet these requirements. As the demands and needs become more stringent, in fact, fundamental limitations arise, which are ultimately imposed by the inherent nature of wireless operation. \textbf{Current network design assumptions}. The first five generations of wireless networks have been designed by adhering to the postulates that the wireless environment between communicating devices (i) is fixed by nature, (ii) cannot be modified, (iii) can be only compensated through the design of sophisticated transmission and reception schemes. After five generations of wireless networks, however, the improvements that can be expected by operating only on the end-points of the wireless environment may not be sufficient to fulfill the challenging requirements of future wireless networks. The sixth generation (6G) of communication networks is, on the other hand, envisioned to require a new architectural platform that performs joint communication, sensing, localization, and computing, while ensuring ultra-high throughput, ultra-low latency, and ultra-high reliability, which need to be flexibly customized in real-time. \textbf{An emerging paradigm: Programming the environment}. Major performance gains can be expected by breaking free from the postulate that regards the wireless environment as an uncontrollable element. For example, a typical base station transmits radio waves of the order of magnitude of Watts while a user equipment detects signals of the order of magnitude of $\mu$Watts. The rest of the power is, in general, wasted in different ways through the environment by, e.g., generating interference to other network elements or creating security threats, since the propagation of radio waves through the wireless channel cannot be controlled and customized after they are emitted from the transmitters and before they are received by the receivers. An intriguing question was recently brought to the attention of the wireless community: \textit{Can this status quo be fundamentally overcome}? \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_1.pdf} \caption{Radio environments vs. smart radio environments.} \label{Fig_1} \end{centering} \end{figure} \textbf{The road to smart radio environments}. At the time of writing, no precise answer to this question can be given. A plethora of research activities have, however, recently flourished in an attempt of tackling and putting this question in the context of the most promising technologies that were developed during the last decades and that are envisioned to constitute the backbone of 5G networks. The current long-term vision for overcoming the limitations of 5G networks consists of turning the wireless environment into an optimization variable, which, jointly with the transmitters and receivers, can be controlled and programmed rather than just adapted to. This approach is widely referred to as smart radio environment (SRE) or, more recently, intelligent radio environment (IRE), or ``Wireless 2.0'' in order to emphasize the conceptual and fundamental difference with the designs and optimization criteria adopted in current and past generations of wireless networks. Conceptually, the vision of SREs is depicted in Fig. \ref{Fig_1}. \textbf{Structure of the paper}. The objective of the present paper is to provide the readers with a comprehensive and critical overview of the fundamental technology enablers, the main operating principles and envisioned potential applications, the current state of research, and the open research challenges of the emerging concept of SREs. To this end, the present paper is organized in six sections. \begin{itemize} \item In Section II, the concept of reconfigurable intelligent surface (RIS), as the technology enabler to realize the vision of SREs, is introduced. \item In Section III, the concept of SREs is introduced in more detail by reporting major examples of application and use cases. \item In Section IV, a communication-theoretic perspective to RIS-empowered SREs is given, with a focus on analytical and computational methods for modeling RISs and their interactions with the radio waves. \item In Section V, a comprehensive survey of the current state of research is given. \item In Section VI, the major open research issues that need to be tackled to realize the vision of SREs are discussed. \item In Section VII, final conclusions are provided. \end{itemize} \section{Reconfigurable Intelligent Surfaces} \label{RISs} \textbf{General definition}. The key enabler to realize the vision of SREs, by making the wireless environment programmable and controllable, is the so-called RIS. Broadly speaking, an RIS can be thought of as an inexpensive adaptive (\textit{smart}) thin composite material sheet, which, similar to a \textit{wallpaper}, covers parts of walls, buildings, ceilings, etc., and is capable of modifying the radio waves impinging upon it in ways that can be programmed and controlled by using external stimuli. A prominent property of RISs is, therefore, the capability of being (re-)configurable after their deployment in a wireless environment. \textbf{General operation}. Based on this general definition, the operation of an RIS can, in general, be split into two phases that are executed periodically based on the coherence time of the environment. \begin{itemize} \item \textbf{\textit{Control and programming phase}}. During this phase, the necessary environmental information for configuring the operation of the RIS is estimated, and it is configured for subsequent operation. \item \textbf{\textit{Normal operation phase}}. During this phase, the RIS is configured already and assists the transmission of other devices throughout the network. \end{itemize} In further text, we elaborate on different implementations of this general working operation, which include centralized, distributed, and hybrid network architectures, and encompass the control/programming and normal operation phases. \subsection{Two Practical Examples of Reconfigurable Intelligent Surfaces} \label{Examples_RISs} \textbf{Two examples of RISs}. Although the current state of research may be far from realizing RISs according to the just mentioned definition, several researchers are working towards the realization of smart surfaces that behave, conceptually, as a programmable thin \textit{wallpaper} and as a programmable thin \textit{glass}, which are capable of manipulating the radio waves as desired. Two recent examples of these research activities are illustrated in Figs. \ref{Fig_2} and \ref{Fig_3}. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_2.pdf} \caption{MIT's RFocus prototype (photo: Jason Dorfman, CSAIL).} \label{Fig_2} \end{centering} \end{figure} \textbf{MIT's RFocus prototype}. In Fig. \ref{Fig_2}, the RFocus prototype, recently designed by researchers of the Massachusetts Institute of Technology (MIT), USA, is depicted \cite{RFocus}. The RFocus prototype is made of 3,720 inexpensive antennas arranged on a six square meter surface. At scale, each antenna element is expected to have a cost of the order of a few cents or less. The structure operates in a nearly-passive mode, since the surface itself does not emit new radio waves, but it can be adaptively configured by means of low power electronic circuits in order to beamform and to focus the impinging radio waves towards specified direction and locations, respectively. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_3.pdf} \caption{NTT DOCOMO's prototype (photo: NTT DOCOMO).} \label{Fig_3} \end{centering} \end{figure} \textbf{NTT DOCOMO's prototype}. In Fig. \ref{Fig_3}, a prototype of smart glass, recently designed by researchers of NTT DOCOMO, Japan, is depicted \cite{Docomo_Glass}. The manufactured smart glass is an artificially engineered thin layer (i.e., a metasurface) that comprises a large number of sub-wavelength unit elements placed in a periodic arrangement on a two-dimensional surface covered with a glass substrate. By moving the glass substrate slightly, it is possible to dynamically control the response of the impinging radio waves in three modes: (i) full penetration of the incident radio waves; (ii) partial reflection of the incident radio waves; and (iii) full reflection of all radio waves. The smart glass is highly transparent and, hence, is suitable for unobtrusive use. For example, it can manipulate the radio waves in accordance with the specific installation environment, particularly in locations that are not suited for installing base stations, such as in built-up areas or in indoor areas where the reception of signals needs to be blocked selectively, (e.g., high-security areas). In addition, the transparent substrate does not interfere aesthetically or physically with the surrounding environment or with the line-of-sight of people, thus making the structure suitable for use within buildings and on vehicles or billboards. \subsection{Nearly-Passive Reconfigurable Intelligent Surfaces} \label{NearlyPassive_RISs} \textbf{Different kinds of RISs}. Different kinds of RISs are currently under research and design. These include smart surfaces that are or are not capable of amplifying and performing signal processing operations on the impinging radio waves (active vs. passive surfaces), as well as surfaces whose functions cannot or can be modified after being manufactured and deployed (static vs. dynamic/reconfigurable surfaces). A detailed classification of these options is provided in further text. For ease of writing, however, we feel important to mention that in the present paper we refer, unless otherwise stated, to RISs that can be broadly classified as nearly-passive and dynamic. \textbf{Definition of nearly-passive RISs}. We define an RIS as nearly-passive and dynamic (or simply reconfigurable) if the following three conditions are fulfilled simultaneously. \begin{enumerate} \item No power amplification is used after configuration (during the normal operation phase). \item Minimal digital signal processing capabilities are needed only to configure the surface (during the control and programming phase). \item Minimal power is used only to configure the surface (during the control and programming phase). \end{enumerate} Based on this definition, the next sub-section reports the conceptual architecture of a nearly-passive RIS. Then, the subsequent sub-section presents a broader classification of RISs for which the above-mentioned three conditions may not be fulfilled simultaneously. The relevance and broad interest in nearly-passive RISs is elaborated at the end of this section. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_4.pdf} \caption{Conceptual structure of a reconfiguration intelligent surface.} \label{Fig_4} \end{centering} \end{figure} \subsection{Conceptual Structure of Reconfigurable Intelligent Surfaces} \label{RIS_Structure} \textbf{Reference structure}. The two examples in Figs. \ref{Fig_2} and \ref{Fig_3} indicate that an RIS can be realized by employing different technologies and that it can be designed based on conceptually different approaches. Regardless of the specific design methods and engineering implementations, a conceptual schematic representation of an RIS, which can be employed for analyzing and synthesizing it, is reported in Fig. \ref{Fig_4}. \textbf{Two-dimensional structure}. The RIS in Fig. \ref{Fig_4} is modeled as a two-dimensional structure of man-made material, whose transverse size is much larger than its thickness. Usually, the transverse size of an RIS is much larger than the wavelength of the radio waves (e.g., a few tens or a few hundreds times larger than the wavelength depending on the functions to realize), and its thickness is much smaller than the wavelength of the radio waves. For this reason, an RIS is often referred to as a \textit{zero-thickness sheet of electromagnetic material}. The two-dimensional structure in Fig. \ref{Fig_4} makes RISs easier to design and to deploy, less lossy, and less expensive to realize, as compared with their three-dimensional counterpart whose thickness is not negligible. \textbf{Composite material layers of unit cells}. The RIS in Fig. \ref{Fig_4} is constituted by composite material layers that are made of metallic or dielectric patches printed on a grounded dielectric substrate. Each patch can be modeled as a passive scattering element and it is often referred to as \textit{unit cell} or scattering particle. The microscopic design of each unit cell determines the macroscopic response of the RIS to the impinging radio waves. This includes the material with which the unit cells are made of, the size of the unit cells, and the inter-distance among the unit cells. As detailed in further text, the size and inter-distance of the unit cells can be either of the order of the wavelength (usually half the wavelength) or can be smaller than the wavelength (usually 5-10 times smaller than the wavelength). We anticipate that an RIS can be either locally passive or locally active, even if it is globally nearly-passive, i.e., the sum of the reflected and transmitted powers is equal to the incident power. If the response of an RIS is locally active in some parts of the metasurface structure and is locally passive in some other parts of the metasurface structure, this implies that some surface waves may exist and that they may travel along the metasurface structure so as to transfer energy from the (virtual) passive regions to the (virtual) active regions. In other terms, the metasurface may transform the incident electromagnetic (EM) fields into desired EM fields through appropriate, locally distributed, balanced absorptions and gains. This design ensures that no active elements are employed during the normal operation phase and that the metasurface structure is globally passive. An example of a metasurface structure that realizes perfect anomalous reflection based on this design principle is analyzed in Section IV. \textbf{Configuration network}. The dynamic operation of the RIS in Fig. \ref{Fig_4}, i.e., its reconfigurability, is ensured by low power tunable electronic circuits, e.g., positive intrinsic negative (PIN) diodes or varactors. By appropriately configuring the on/off state of the PIN diodes or the bias voltage of the varactors, one can control and program the (macroscopic) transformations that are applied to the impinging radio waves. Let us consider, for example, that the RIS is made of two PIN diodes and that the unit cells are designed to simply rotate the phase of the impinging radio wave of 0, 90, 180, and 270 degrees. Then, the rotation phase can be controlled by coding it into the four possible states of the two PIN diodes, which need only two bits for being configured. In general terms, the specific design of the unit cells (their size, their inter-distance, the material they are made of, etc.), and the inter-cell communication network, which define the microscopic behavior of the RIS, determine the functions that the RIS can apply, at the macroscopic level, to the impinging radio waves. \textbf{Communication with the external world}. In order to be controlled and programmed remotely, Fig. \ref{Fig_4} highlights that RISs need to be equipped with at least one gateway (with transmit and receive capabilities), which constitutes the interface of the RIS with the external world. In addition, a micro-controller and a wireless or wired (on-chip) inter-cell communication network, which enables the transfer of information from the gateway throughout the surface, are needed. As mentioned, nearly-passive RISs have minimal power requirements and signal processing capabilities. These are needed, only during the control and programming phase, for: (i) operating the low power tunable electronic circuits that ensure the reconfigurability of the RIS; and (ii) communicating with the external world, e.g., to receive the control and configuration signals. \textbf{On-board sensing capabilities}. The nearly-passive RIS depicted in Fig. \ref{Fig_4} may or may not be equipped with low power sensing elements, whose role is to help estimating the channel (or, more in general, the environmental) state information that is necessary for optimizing the operation of the RIS based on some key performance indicators, e.g., the desired signal-to-noise ratio at a given location. Equipping RISs with low power sensors increases the cost and the power consumption of the entire surface. Dispensing RISs with low power sensors makes, on the other hand, more challenging the estimation of the necessary environmental state information, since the RISs cannot sense and learn the environment on their own. The vast majority of current research activities rely on the assumption that nearly-passive RISs are not equipped with sensing elements, and, therefore, different algorithms and protocols are under analysis for efficiently estimating the channel state information that is needed for optimizing their operation. These research activities are discussed in Section V. \subsection{Surfaces vs. Smart Surfaces} \label{Surfaces_vs_SmartSurfaces} Having defined the conceptual structure of a nearly-passive RIS, one may wonder what the difference between a conventional surface (e.g., a wall) and a smart surface (e.g., a smart wall) like the one sketched in Fig. \ref{Fig_4} is. \textbf{Conventional surfaces}. In general terms, a radio wave that impinges upon a conventional wall induces some surface currents that determine the radio waves that are scattered off. The surface currents are determined by the boundary conditions at the interface of the wall, which depend on the permittivity and permeability of the material that the wall is made of, its thickness, and the wavelength of the radio waves. \textbf{Smart surfaces}. When the same radio wave impinges upon a smart wall, the distribution of the surface currents is, in general, different, and is determined by the characteristics of the unit cells (their size, their inter-distance, the material they are made of, etc.) and the status of the electronic circuits that constitute the configuration network. The different surface currents result in different radio waves that are scattered off. In general, an RIS can be approximately modeled by specific boundary conditions at the interface of a smart wall, which define discontinuities of the electric and magnetic fields in the close vicinity of the surface. For this reason, an RIS is often referred to as an electromagnetic discontinuity in space. This concept is further elaborated and discussed in Section IV. \textbf{A simple example: Specular vs. anomalous reflection}. A typical example to understand this difference is the relation between specular reflection and anomalous reflection. When a radio wave impinges upon a uniform surface, the angle of incidence and the angle of reflection (with respect to the normal of the surface) are the same. This is dictated by the boundary conditions at the surface and the corresponding surface currents that are induced by the impinging radio waves. When a radio wave impinges upon a smart surface, on the other hand, the unit cells and the configuration network can be designed to make the angle of incidence and the angle of reflection different. This is obtained because the design of the unit cells is realized in a way that the induced surface currents generate radio waves that are reflected, predominantly, in a specified direction that may be different from the direction of incidence (with respect to the normal of the surface). \subsection{Metamaterials-Based Reconfigurable Intelligent Surfaces} \label{Metasurfaces} The architecture of the smart surface illustrated in Fig. \ref{Fig_4} is general enough for accommodating different practical implementations of nearly-passive RISs. At the time of writing, the vast majority of researchers in wireless communications have focused their attention on two main practical implementations. \begin{itemize} \item \textbf{\textit{Smart surfaces made of discrete tiny antenna elements}}. This implementation is exemplified in the hardware prototype illustrated in Fig. \ref{Fig_2}. In this case, the unit cells depicted in Fig. \ref{Fig_4} can be regarded as tiny antenna elements whose size and inter-distance are usually equal to half of the wavelength of the radio waves. Conceptually, each unit cell is often considered as a reflecting element that modifies the phase of the impinging radio wave. Since the unit cell are spaced by half of the wavelength, the mutual coupling among them is usually ignored and each unit cell is designed independently of the others. \item \textbf{\textit{Smart metasurfaces}}. This implementation is exemplified in the hardware prototype illustrated in Fig. \ref{Fig_3}. In this case, the unit cells depicted in Fig. \ref{Fig_4}, which can be full or slotted patches, straight or curves strips, etc., are arranged in non-uniform repeating patterns. The repeating pattern of the unit cells is referred to as \textit{super-cell}, and it determines the period of the structure. The unit cells that constitute the super-cell have, usually, different geometric shapes and sizes, and are jointly optimized in order to realize the specified functions. This implies that the mutual coupling among the unit cells of a super-cell cannot be ignored and need to be carefully engineered. These two concepts are further elaborated in Section IV. If the unit cells of a smart metasurface are made of a reconfigurable material, the tunable elements depicted in Fig. \ref{Fig_4} may not be needed anymore, since the reconfigurability of the surface is ensured through the material of the unit cells itself. The metasurface structure needs, however, to be equipped with a configuration network in order to ensure its control and programmability. \end{itemize} \textbf{Key properties of metasurfaces}. The prefix \textit{meta} is a Greek word whose meaning is, among others, ``beyond''. In the context of metamaterials and metasurfaces, it refers to a three-dimensional and a two-dimensional structure that exhibits some kind of exotic properties that natural materials and surfaces, respectively, do not usually posses. By definition, a metasurface has the following properties \cite{Book_SurfaceElectromagnetics}: (i) it is \textit{electrically thin}, i.e., its thickness is considerably smaller than the wavelength; (ii) it is \textit{electrically large}, i.e., its transverse size is relatively large as compared with the wavelength; (iii) it is \textit{homogenizable}, i.e., the distance between adjacent unit cells is much smaller than the wavelength; and (iv) it is a \textit{sub-wavelength structure}, i.e., the size of each unit cell is much smaller than the wavelength. \textbf{Impact of the sub-wavelength thickness}. The deeply sub-wavelength thickness of the surface ensures that the propagation or resonance effects in the direction perpendicular to the surface can be safely ignored in the process of synthesis and analysis of the surface. This implies that the EM field on the transmission side of the surface (e.g., $z=0^+$) depends only on the EM field on the incidence and reflection side (e.g., $z=0^-$) of the surface, and that the surface can be effectively modeled as a sheet of induced surface electric and magnetic currents. In other words, the effects of the EM fields within the substrate of sub-wavelength thickness can be averaged out and ignored. This specific property allows one to define a metasurface as a local entity, as a zero-thickness sheet, or as a sheet discontinuity. \textit{It is worth mentioning that the term local entity needs not to be interpreted as the absence of spatial coupling among the unit cells, which, on the other hand, cannot be ignored due to the sub-wavelength inter-distance among the unit cells of the metasurface}. \textbf{Impact of the sub-wavelength inter-distance}. The sub-wavelength inter-distance among the unit cells make the metasurface equivalent to a sub-wavelength particle lattice that can be locally homogeneized, and, therefore, can be described through \textit{continuous} mathematical tensor functions that are, in general, simpler to handle as compared with the actual physical structure of the metasurface. Analytical models for the metasurfaces are detailed in Section IV, where the difference between microscopic and macroscopic modeling is discussed, along with the analytical convenience, especially for wireless applications, of macroscopic models. \subsection{Nomenclature and Classification} \label{Nomenclature_and_Classification} In the present paper, we have adopted the term RIS in order to refer to any kind of smart surfaces, as those depicted in Figs. \ref{Fig_2} and \ref{Fig_3}, which have the capability of being reconfigurable after their deployment in the network. In Fig. \ref{Fig_4}, in addition, we have sketched the conceptual architecture of nearly-passive RISs, which can be representative of different practical implementations of RISs. \textbf{RISs and friends}. In the literature, however, several other terms and acronyms are often employed to refer to smart surfaces. The most widely used are briefly discussed as follows. \begin{itemize} \item \textbf{\textit{Large intelligent surfaces (LISs)}}. The term LIS is referred to surfaces that are viewed as the next step beyond massive multiple-input-multiple-output (MIMO) technology. LISs are typically defined as active surfaces whose individual antenna elements are equipped with dedicated radio frequency (RF) chains, power amplifiers, and signal processing capabilities. Conceptually, their architecture is similar to that shown in Fig. \ref{Fig_4}. However, each unit element may have a complete RF chain and an independent baseband unit. \item \textbf{\textit{Intelligent reflecting surfaces (IRSs)}}. The term IRS is typically referred to surfaces that operate as reflectors and that are made of individually tunable unit elements whose phase response can be individually adjusted and optimized for beamsteering, focusing, and other similar functions. Usually, the unit elements are assumed not to be capable of amplifying the impinging radio waves, so that only their phase response can be modified (not their amplitude response). \item \textbf{\textit{Digitally controllable scatterers (DCSs)}}. The term DCS is the most similar to RIS, and it is typically employed to emphasize the possibility of controlling, in a digital manner, the behavior of objects and devices coated or made of smart surfaces. In this case, the emphasis is put on the individual elements of the smart surface that are viewed as local scatterers. DCSs are often made of passive elements that cannot amplify the received signals. If made of passive elements, the operation of DCSs is based on the mutual coupling among the elements, and, hence, there exists a high spatial correlation among the unit cells depicted in Fig. \ref{Fig_4}. \item \textbf{\textit{Software controllable surfaces (SCSs)}}. The term SCS is typically employed when the emphasis is to be given to the capability of the smart surfaces of being controlled and optimized by using software-defined networking technologies. The term SCS is often employed when the unit elements of the smart surface are equipped with a nano-communication network for enabling the communication among the unit cells. The smart surface is often equipped with low power sensors for environmental monitoring. The joint functionality of sensing and communication provides the smart surface with the capability of performing simple local operations, thus making it more autonomous. This may, however, affect the complexity and the power consumption of the entire smart surface. \end{itemize} \textbf{Formal classification of metasurfaces}. A comprehensive classification of electromagnetic surfaces is available in \cite[Fig. 1.10]{Book_SurfaceElectromagnetics}. As far as smart surfaces with general (passive or nearly-passive) functions are concerned, which is the main interest of the present paper, three main definitions can be found in \cite[Fig. 1.10]{Book_SurfaceElectromagnetics}. \begin{itemize} \item \textit{\textbf{Huygens's surfaces}}. These are defined as smart surfaces that manipulate the wavefront of incident radio waves in ways that a secondary wavefront with the desired features can be obtained. \item \textit{\textbf{Metasurfaces}}. These are defined as any artificial smart surfaces with unconventional features. \item \textit{\textbf{Reconfigurable surfaces and programmable metasurfaces}}. These are defined as smart surfaces that are equipped with active control devices, such as PIN diodes, micro electro mechanical systems (MEMS) switches, and varactors, which are integrated into the smart surface in order to provide real-time control of the surface properties. \end{itemize} Based on the classification in \cite[Fig. 1.10]{Book_SurfaceElectromagnetics} and the names usually adopted by researchers working in wireless communications and networks, we evince that the acronym RIS can be considered to be the most suitable definition for the conceptual architecture of smart surface depicted in Fig. \ref{Fig_4}. This justifies and corroborate the adoption of the term RIS in the present paper. \subsection{Macroscopic Functions of Reconfigurable Intelligent Surfaces} \label{MacroscopicFunctions} \textbf{Microscopic and macroscopic views}. Based on the conceptual architecture depicted in Fig. \ref{Fig_4}, it is apparent that the functions that an RIS is capable of applying, at the macroscopic level, to the impinging radio waves can be synthesized by appropriately optimizing its operation at the microscopic level, i.e., by appropriately designing the unit cells and the configuration network made of low power electronic circuits. Simple examples on how to optimize the unit cells of a phase-gradient RIS in order to synthesize specified macroscopic functions are reported in Section IV. \textbf{Classification of macroscopic functions}. In general terms, the functions realized by RISs for application to wireless networks can be classified into two main categories. \begin{itemize} \item \textbf{\textit{EM-based design of RISs}}. These functions correspond to elementary transformations of the radio waves that can be directly specified at the EM level. Under this design paradigm, an RIS is optimized in order to realize some fundamental manipulations of the radio waves, which may be employed in wireless networks. According to this design paradigm, communication engineers view RISs as black boxes in which some parameters (knobs) can be optimized for improving the network performance. \item \textbf{\textit{Communication-based design of RISs}}. The functions realized by RISs under a communication-based design paradigm may not necessarily correspond to elementary EM-based manipulations of the radio waves. For a communication engineer, a fundamental question may, for example, be: \textit{What is the optimal design or use of an RIS in order to maximize the channel capacity}? According to this design paradigm, the functions of RISs are not specified a priori, but they are the result of an optimization problem and, therefore, may be different depending on the performance metric of interest. For example, RISs may be employed for realizing advanced modulation and coding schemes by directly operating at the EM level. \end{itemize} Some representative examples of these two design approaches are given in the following two sub-sections. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_5.pdf} \caption{Electromagnetic-based elementary functions.} \label{Fig_5} \end{centering} \end{figure} \subsubsection{EM-Based Design of RISs} In Fig. \ref{Fig_5}, we report some examples of EM-based elementary functions that may be applied by RISs and that may have useful applications in wireless communications. These elementary functions are briefly discussed as follows. \begin{itemize} \item \textbf{\textit{Reflection}}. This function consists of reflecting an impinging radio wave towards a specified direction that may not necessarily coincide with the direction of incidence. \item \textbf{\textit{Transmission/refraction}}. This function consists of refracting an impinging radio wave towards a specified direction that may not necessarily coincide with the direction of incidence. \item \textbf{\textit{Absorption}}. This function consists of designing a smart surface that nulls, for a given incident radio wave, the corresponding radio waves that are reflected and refracted. \item \textbf{\textit{Focusing/beamforming}}. This function consists of focusing (i.e., concentrating the energy of) an impinging radio wave towards a specified location. \item \textbf{\textit{Polarization}}. This function consists of modifying the polarization of an incident radio wave (e.g., the impinging radio wave is transverse electric polarized and the reflected radio wave is transverse magnetic polarized). \item \textbf{\textit{Collimation}}. This function is the complementary of focusing. \item \textbf{\textit{Splitting}}. This function consists of creating multiple reflected or refracted radio waves for a given incident radio wave. \item \textbf{\textit{Analog processing}}. This function consists of realizing mathematical operations directly at the EM level. For example, the radio wave refracted by a smart surface may be the first-order derivative or the integral of the impinging radio wave. \end{itemize} \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_6.pdf} \caption{Communication-based (modulation and encoding) design of reconfigurable intelligent surfaces.} \label{Fig_6} \end{centering} \end{figure} \subsubsection{Communication-Based Design of RISs} In addition to functions that directly pertain the manipulation of the impinging radio waves at the EM level, an RIS can be employed for operations and applications that capitalize on EM-based manipulations of the radio waves but go beyond them. For example, a conceptual block diagram that depicts the application of RISs for implementing different types of transmitter designs is illustrated in Fig. \ref{Fig_6}. In this case, an RIS is viewed as an integral part of a transmitter. Other communication-based designs, applications, and examples beyond transmit-related operations (i.e., modulation and encoding) are described in further text. \textbf{Metasurface-based transmitters}. Figure \ref{Fig_6} shows an RIS that is realized based on the conceptual architecture reported in Fig. \ref{Fig_4}. From a communication-design perspective, a number of super-cells (it can be even a single super-cell depending on the function to be realized and the technology employed) are grouped together to form a macro-cell. A macro-cell can be thought of as the atomic element to realize RIS-based transmitters. As a concrete example, one may think of a macro-cell as a physical structure that allows one to mimic a phase shift keying (PSK) modulation. If an 8-PSK modulation is of interest, the macro-cell needs to be capable of realizing eight distinct phase shifts that correspond to those of a PSK modulation employed by conventional modulators. In practice, this is realized by jointly designing the unit cells and the super-cells that constitute the macro-cell, as elaborated in Section IV. The metasurface structure is illuminated by a feeder that is located in close proximity of the RIS. The feeder emits only an un-modulated signal. The modulation is, in fact, realized uniquely by the RIS through appropriate reflections of the signal emitted by the feeder. To modulate data, the RIS is controlled by an encoder, which outputs two data streams that are employed for configuring the RIS. The first data stream is employed to set the reflection coefficient (R1, R2, ...) of each macro-cell. Continuing with our example, each reflection coefficient corresponds to one phase shift of an 8-PSK modulation. It may, however, be an arbitrary reflection coefficient that is chosen based on any design criteria. The second data stream corresponds to conventional modulation symbols. The two data streams are employed to simultaneously control the macro-cells that are activated for transmission at a given time instance (the macro-cells in blue color in Fig. \ref{Fig_6}), and the modulated signals that they emit (the beams in purple color in Fig. \ref{Fig_6}). The transmitter architecture sketched in Fig. \ref{Fig_6} is general enough to realize multiple practical implementations. Three examples are described as follows. \begin{itemize} \item \textbf{\textit{RIS-based modulation}}. Let us assume that the data stream that corresponds to the state of the RIS controls only whether a macro-cell is either activated (ON state) or not activated (OFF state). This implies that the reflection coefficient of each macro-cell is only one or zero, respectively. Let us consider, in particular, that only a single macro-cell is activated at any transmission instance. Let us assume, in addition, that the data stream of the modulation symbols contains a single PSK symbol. Then, the RIS-based transmitter scheme in Fig. \ref{Fig_6} can be employed to realize a metasurface-based version of spatial modulation and index modulation, in which the transmitted data is encoded into the activated macro-cell and the PSK-modulated symbol \cite{MDR_SM_COMMAG}, \cite{MDR_SM_PIEEE}, \cite{MDR_SM_CST2015}, \cite{MDR_SM_CST2016}, \cite{MDR_SM_MILCOM}, \cite{MDR_IM_Access}, \cite{MDR_SM_JSAC}. This specific implementation of spatial modulation is attractive because of the large number of macro-cells that may be deployed on an RIS, and, therefore, the large number of bits that can be modulated onto the ON-OFF states of the macro-cells. For example, the RIS prototype in Fig. \ref{Fig_2} is made of 3,720 inexpensive individually tunable antennas and the RIS prototype in \cite{Wankai_PathLoss} is made of 10,000 unit cells. This implies that tens of bits per channel use may be modulated by using this approach, while using a single feeder. Ultimately, however, the achievable rate depends on the speed at which the macro-cells can be configured. \item \textbf{\textit{RIS-based multi-stream transmitter}}. Let us assume that the data stream that corresponds to the state of the RIS controls the reflection coefficient of each macro-cell so as to mimic a PSK modulation. Let us assume, in addition, that the data stream of the modulation symbols is not enabled, i.e., the RIS is not fed with any bits through this control signal. Then, the RIS-based transmitter scheme in Fig. \ref{Fig_6} can be employed to realize a metasurface-based version of multi-antenna spatial multiplexing, in which the number of data streams that are simultaneously transmitted depend on the number of macro-cells that are activated at any transmission instance. If all the macro-cells are activated simultaneously, the RIS-based transmitter scheme in Fig. \ref{Fig_6} is capable of emitting twelve data streams simultaneously. In general, the larger the number of data streams is, the higher the complexity of the control and configuration network of the RIS is. Examples of existing prototypes for RIS-based multi-stream transmitters can be found in \cite{Wankai_ElectronLetterEditor}, \cite{Wankai_ElectronLetter}, \cite{Wankai_ChinaCommun}, \cite{Wankai_WCM}, \cite{Wankai_JSAC}. This specific implementation of spatial multiplexing is attractive because multiple data streams are transmitted simultaneously, while employing a single feeder, i.e., a single power amplifier and a single RF chain. \item \textbf{\textit{RIS-based encoding}}. Let us assume that the data stream that corresponds to the state of the RIS controls the reflection coefficient of each macro-cell so as to mimic a discrete set of values. For generality, let us consider that all the macro-cells are activated at the same time. Let us assume, in addition, that the data stream of the modulation symbols contains a single symbol that belongs to a given constellation diagram. Then, the RIS-based transmitter scheme in Fig. \ref{Fig_6} can be employed to realize a transmitter that jointly encodes data onto the modulation symbol $x$ and the set of reflection coefficients R1, R2, ... of the macro-cells. This implementation has recently been studied, from an information-theoretic standpoint, in \cite{MDR_ISIT2020}. Therein, it is proved that jointly encoding information on the modulation symbol and the configuration of an RIS, as a function of the channel state information, provides a better channel capacity as compared with the baseline scheme in which the configuration of the RIS is not exploited for data modulation. This result is important because it proves that maximizing the received power is not necessarily optimal from an information-theoretic point of view. \end{itemize} Several other transmitter designs may be realized, based on these three examples, which capitalize on the possibility of shaping the radio waves emitted by an RIS through a simple RF feeder and an encoder that controls the configuration network sketched in Fig. \ref{Fig_4}. \subsection{Distinctive Peculiarities of Reconfigurable Intelligent Surfaces} \label{DistinctivePeculiarities} \textbf{RISs vs. competing technologies}. As mentioned in previous text, some instances of RISs with active unit elements (usually referred to as LISs) are often viewed as the next step beyond massive MIMO. Similarly, nearly-passive RIS that are implemented by using surfaces made of discrete tiny antenna elements with inter-distances equal to half of the wavelength are often compared to multi-antenna relays with no power amplification capabilities or to reflectarrays that are illuminated by a feeder that is not located in close proximity of the surface. Comparative studies on the differences and similarities between RISs, massive MIMO, relays, and other technologies are reported and discussed in Section V. \textbf{The main reasons that make RISs different}. In this sub-section, we are interested in elaborating on some fundamental aspects that, in our opinion, make nearly-passive RISs different from currently available technologies, and that, at the same time, offer opportunities for innovative solutions that have never been in the mainstream of wireless communications before. More specifically, the following aspects are considered to be distinctive and peculiar features of nearly-passive RISs. \begin{itemize} \item \textbf{\textit{Unique design constraints}}. The nearly-passive nature of RISs introduces challenging design constraints, e.g., the impossibility of performing channel estimation directly on the smart surface and on the way that the radio waves can be manipulated by the smart surface. \item \textbf{\textit{Communication without new waves}}. The nearly-passive nature of RISs offers unique opportunities for redefining the notion of communication, in which information can be exchanged without producing new EM signals but by recycling existing radio waves. This may be highly beneficial for reducing the EM pollution and for decreasing the level of EM exposure of human beings, which is usually increased by deploying additional network infrastructure and by using more spectrum. This may be extremely relevant for the successful deployment of wireless technologies in EM-sensitive environments (e.g., in hospitals). \item \textbf{\textit{Sustainable wireless by design}}. The use of innovative eco-friendly metamaterials in order to realize and manufacture nearly-passive RISs opens the possibility for building future wireless networks that are sustainable by design. The materials that are employed to realize the smart surfaces can be chosen to be cost-effective, to have a light environmental footprint, and to be highly recyclable. This, in turn, may impose some design constraints on the functions that the RISs may be able to realize. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_7.pdf} \caption{Fraunhofer's distance at sub-6 GHz (a) and millimeter-wave (b) frequencies ($D$ is fixed).} \label{Fig_7} \end{centering} \end{figure} \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_8.pdf} \caption{Fraunhofer's distance at sub-6 GHz (a) and millimeter-wave (b) frequencies ($D$ depends on $\lambda$).} \label{Fig_8} \end{centering} \end{figure} \item \textbf{\textit{Beyond the far-field regime}}. The RISs may be made of geometrically large surfaces of the order of a few square meters. Figure \ref{Fig_2} reports an example of smart surface whose size is of the order of six square meters. A recent prototype of metasurface reported in \cite{Wankai_PathLoss} has a size of one square meter and operates at 10.5 GHz. If one assumes that the far-field of the smart surface can be defined in a similar manner as for conventional antenna arrays, the far-field propagation regime for such an RIS may start at tens of meters far away from the smart surface. This implies that such a smart surface may operate in the near-field in some relevant scenarios, e.g., in indoor environments. The use of geometrically large RISs opens, therefore, the possibility of building new wireless networks that operate in the near-field regime, which is not a conventional design assumption in wireless communications. As an illustrative example, Figs. \ref{Fig_7} and \ref{Fig_8} reports the Fraunhofer distance that is usually employed for identifying the limit between the radiative near-field and the far-field, i.e., $d_F = 2D^2/\lambda$, where $D$ is the largest dimension of the RIS under analysis and $\lambda$ is the wavelength of the radio wave. It is apparent that, depending on the setup, the radiative near-field operating regime may be sufficiently large for typical indoor and mobile outdoor communication systems. \item \textbf{\textit{Dense deployment of scatterers}}. If RISs are made of smart metasurfaces, they comprise a large number of sub-wavelength unit cells. Such envisioned sub-wavelength dense deployments of tiny sub-wavelength scattering elements is not commonly employed in wireless communications, where the mutual coupling among the radiating elements is often avoided by design, i.e., by ensuring that the scattering elements are sufficient distant from each other. This paves the way for developing new signal and propagation models that may affect the ultimate performance limits of wireless networks, and for introducing new design paradigms according to which communication systems and networks are engineered to be mutual-coupling-aware and mutual-coupling-robust. \item \textbf{\textit{High focusing capabilities in the radiative near-field}}. As illustrated in Figs. \ref{Fig_7} and \ref{Fig_8}, RISs may have a sufficiently large size and the operating wavelength may be sufficiently small that the radiative near-field region may not be ignored in typical wireless applications. This operating regime is not usual in wireless communications, and may pave the way for realizing near-field focused RISs that highly concentrate the EM power in small spot regions \cite{NearFieldFocused_Antennas}. This high focusing capability may have multiple applications, e.g., (i) for enabling interference-free communication in areas with high densities of devices; (ii) for making possible the precise radio localization of users and mapping of environments; and (iii) for recharging the batteries of low power devices via wireless power transfer methods. \end{itemize} \subsection{Beyond Planar Reconfigurable Intelligent Surfaces: Conformal Smart Surfaces} \label{ConformalSurfaces} \textbf{RISs are not necessarily planar structures}. We close this section by mentioning that the present paper is focused on RISs that are made of smart surfaces that are planar. This assumption originates from the ease of deployment of such surfaces on, e.g., the internal walls of indoor environments, the external facades of buildings, and the glasses of windows. The same principles apply, however, to free-form conformal bi-dimensional smart surfaces, which are not necessarily planar. These structures may have several applications in wireless communications, e.g., for coating objects that are not planar and for shaping the radio waves in ways that planar smart surfaces many not be capable of. \section{Smart Radio Environments} \label{SREs} \textbf{Designing wireless networks today: The environment is fixed by nature}. Current methods to design wireless networks usually rely on the optimization of the so-called end-points of communication links, e.g., transmitters and receivers. Over the last decades, therefore, many advanced techniques have been proposed for improving the performance of wireless networks, which encompass advanced modulation/encoding schemes and protocols based on using, e.g., multiple antennas at the transmitters, powerful transmission and retransmission protocols, and robust demodulation and decoding methods at the receivers. The wireless environment has, on the other hand, been conventionally modeled as an exogenous entity that cannot be controlled but can only be adapted to. According to this design paradigm, communication engineers usually design the transmitters, the receivers, and the transmission protocols based on the specific properties of the wireless channels and in order to achieve the desired performance. For example, transmitters equipped with multiple radiating elements may be configured differently as a function of the specific characteristics of the wireless channel where they operate, in order to achieve the desired trade-off in terms of spatial multiplexing, spatial diversity, and beamforming gains. \textbf{SREs: The environment is generated by nature but is programmable by design}. The overarching paradigm that characterizes the design of current wireless networks consists, therefore, of pre-processing the signals at the transmitters and/or post-processing the signals at the receivers, in order to compensate the effect of the wireless channel and/or in order to capitalize on specific features and characteristics of the wireless channel. RISs provide wireless researchers with more opportunities for designing and optimizing wireless networks, which are built upon a different role played by the wireless environment. RISs are, in fact, capable of shaping the radio waves that impinge upon them, after the radio waves are emitted by the transmitters and before they are observed by the receivers, in ways that the wireless environment can be customized, in principle as one desires, in order to fulfill specific system requirements. The wireless environment is, therefore, not treated as a random uncontrollable entity, but as part of the network design parameters that are subject to optimization for supporting diverse performance metrics and quality of service requirements. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_9.pdf} \caption{Communication-theoretic models for radio environments and smart radio environments (with and without joint encoding).} \label{Fig_9} \end{centering} \end{figure} \textbf{Revisiting communication-theoretic models}. The concept of SREs introduces, therefore, a new communication-theoretic view of wireless systems and offers new opportunities for optimization. In Fig. \ref{Fig_9}, the conceptual block diagram of a conventional point-to-point communication system and the corresponding block diagram under a SRE-based framework are illustrated. Under the conventional communication-theoretic framework, the system is modeled through transition probabilities that are not considered to be optimization variables. Under the SRE-based communication-theoretic framework, on the other hand, the system is modeled through transition probabilities that can be customized, thanks to the deployment of RISs throughout the environment and thanks to the possibility of controlling and programming the functions that RISs apply to the impinging radio waves. Therefore, the system model itself becomes an optimization variable, which can be jointly optimized with the transmitter and the receiver: Rather than optimizing the input signal for a given system model, one can now jointly optimize the input signal and the system. \textbf{SREs with and without joint encoding and modulation at the transmitter and at the RIS}. In Fig. \ref{Fig_9}, in particular, three system models are illustrated. The first communication-theoretic model is referred to a conventional radio environment in which, via a feedback channel that provides the encoder with channel state information, the transmitter and receiver are jointly optimized, e.g., by designing appropriate transmit and receive channel-aware vectors. The second communication-theoretic model is referred to an RIS-empowered SRE in which the feedback channels from the receiver and the environment (e.g., the RIS) are exploited for optimizing the setup (i.e., configuration, state, or action) of the RIS besides the transmit and receive channel-aware vectors. In this case, therefore, the transition probabilities that describe the wireless environment can be customized by appropriately optimizing the state of the RIS. These first two communication-theoretic models are analyzed and compared in \cite{MDR_OverheadAware}. The third communication-theoretic model is referred to an RIS-empowered SRE in which the state of the RIS is employed for customizing the wireless environment while at the same time encoding information jointly with the transmitter. In this setup, in particular, the transition probabilities of the wireless environment depend on both the state of the RIS, which affects the wireless channel, and the data $s$ encoded by the transmitter on the state of the RIS. This setup is analyzed in \cite{MDR_ISIT2020}, where it is proved that performing joint transmitter-RIS encoding yields, in general, a better channel capacity. \textbf{Communication model with state-dependent channels}. From an information-theoretic standpoint, broadly speaking, the conventional block diagram in Fig. \ref{Fig_9} is described by the conditional probability law of the channel output given the channel input. For example, a binary symmetric channel is a model for describing the communication of binary data in which the noise may cause random bit-flips with a fixed probability. In the context of SREs, the conditional probability law of the channel output given the channel input can be customized by using RISs. The wireless environment can be programmed to evolve through multiple states (or configurations) that depend on how the RISs shape the impinging radio waves. The possibility of controlling the possible states of operation of the wireless environment jointly with the operation of the transmitter and the receiver offers opportunities for enhancing the overall communication performance. The resulting communication-theoretic model well fits, therefore, the transmission of information through state-dependent wireless environments (or simply channels) that are generated by nature but that are controlled and affected by the communication system. The block diagram in Fig. \ref{Fig_9} illustrates the case study in which the transmitter takes actions (i.e., it configures the operation of the RISs distributed throughout the environment) that affect the formation of the states of the environment. In general, the specific state of the wireless environment can be controlled by the transmitter, the receiver, or by an external controller that oversees the operation of portions or the entire network. In general, in fact, the operating state of the wireless environment depends on the configuration of all the RISs distributed throughout it, which can be jointly optimized for achieving superior performance. The block diagram of SREs well fits, therefore, a communication model with state-dependent channels, whose states are directly controlled by the communication system rather than being generated and being dependent only by nature \cite{TIT_StateDependentChannels}. \textbf{Overcoming fundamental limitations of wireless networks design}. The possibility of creating wireless systems with state-dependent channels, which are generated by nature but are controlled by communication designers, opens new opportunities for overcoming some fundamental limitations in designing current wireless networks. Four of them are the following. \begin{itemize} \item \textbf{\textit{The ultimate performance limits of wireless networks may not have been reached yet}}. Recent research works have proved that by jointly optimizing the transmitter, the receiver, and the environment, the channel capacity of a point-to-point wireless communication system can be further improved \cite{MDR_ISIT2020}. In particular, the channel capacity can be increased by capitalizing on RISs as a means for encoding and modulating additional information besides the transmitters. \item \textbf{\textit{Customizing and controlling the wireless environment may open new opportunities for network optimization}}. In some application scenarios, the transmitters and receivers may not be equipped with multiple antenna-elements because of the challenges that their practical realization entail. For example: (i) devices such as sensors and handhelds are usually small in size, and multiple antennas cannot be accommodated; (ii) connecting each antenna to an independent RF chain and transmit/receive circuitry increases the cost and power consumption; and (iii) multiple-antenna structures are often bulky and are not easy to deploy even at the base stations. Recent results have shown that these challenges can be overcome by capitalizing on RISs and by moving the operations that are typically executed by multiple-antenna transmitters directly to the radio environment \cite{RFocus}. An example is the RFocus prototype illustrated in Fig. \ref{Fig_2}. \item \textbf{\textit{The radio waves may be used more efficiently}}. When reflected or refracted by an object, for example, the energy of the impinging radio waves is scattered towards unwanted directions, thus reducing the efficiency of utilization of the emitted power. The possibly large size of RISs and their fine ability of controlling the radio wave thanks to their sub-wavelength structure offer the opportunity for realizing smart surfaces that are capable of increasing, in the radiative near-field of the surface, the EM power density in spot regions of very limited size \cite{NearFieldFocused_Antennas}. Therefore, very high focusing capabilities may be obtained by focusing the energy only where it is needed and by avoiding to create interference in unwanted locations. \item \textbf{\textit{The spatial capacity density may be increased}}. Recent results in \cite{Dardari_DegreesFreedom} have proved that RISs offer opportunities for increasing the available degrees of freedom of wireless communications, by creating large numbers of orthogonal communication links per square meter. These communication channels, which are orthogonal at the EM level, can be employed to simplify the wireless access in multiple-access systems, by realizing communication functionalities directly at the EM level, i.e., the ``layer-0'' of the protocol stack. Based on these findings, RISs may be employed for achieving spatial multiplexing gains in wireless environments in which conventional multiple-antenna schemes cannot, e.g., in environments without a sufficiently rich multipath scattering. These results can find applications in scenarios with high densities of devices that can be simultaneously served over the EM-orthogonal channels, thus offering, in principle, very high capacity densities. \end{itemize} \textbf{SREs: Centralized vs. distributed}. RIS-empowered SREs offer, therefore, several opportunities for improving the performance of wireless networks and, possibly, for further moving ahead the fundamental limits of wireless communications. RISs can turn wireless networks into SREs in multiple ways. Broadly speaking, \textit{one could think of wireless networks in which users and devices interact with the environment anytime that they are in close vicinity of a smart surface}, so as to either enhance the communication performance or to reduce the utilization of resources. SREs can be realized in a centralized, distributed, or hybrid manner. \begin{itemize} \item \textbf{\textit{Centralized implementation}}. In this case, it is assumed that a central controller exists and that it coordinates the activity of a network neighborhood. In a centralized implementation, RISs can be realized as simple as possible, since they are not required to be equipped with significant on-board, sensing, signal processing, and communication capabilities. RISs could be realized based on nearly-passive implementations, which need to be only able to receive the configuration signals and to set the configuration network depicted in Fig. \ref{Fig_4} accordingly. In a centralized implementation, however, the central controller needs to be able to gather the channel state information without relying on any on-board sensing and signal processing capabilities at the RISs. Therefore, appropriate protocols to obtain this information are needed, and the associated channel estimation overhead needs to be taken into account for the optimal design and operation of RISs \cite{MDR_OverheadAware}. \item \textbf{\textit{Distributed implementation}}. In this case, a central controller is not necessarily needed. RISs need, however, to have the required functionalities for autonomously identifying the optimal function to apply based on the environmental state information and on the network topology, e.g., the locations of users and access points. It may be difficult, as a consequence, to employ nearly-passive RISs in a distributed implementation, since they need to be able to sense the channel, to extract the necessary channel state information, and to communicate this information throughout the structure of the smart surface. This may be realized by employing low power sensors that are possibly equipped with energy harvesting capabilities and nano-communication protocols for enabling the self-configuration of the unit cells. The higher implementation complexity of the RISs is the price to pay for dispensing SREs from the need of a central controller and the associated signaling and channel estimation overhead. \item \textbf{\textit{Hybrid implementation}}. This can be viewed as an intermediate network realization of SREs, where RISs with different capabilities may be deployed in the network in order to strike a balance between (i) the higher implementation complexity and power consumption of RISs in distributed implementations, and (ii) the higher channel estimation and signaling overhead that are necessary to feed the central controller and to report the environmental information to other network elements. \end{itemize} \textbf{Potential applications and scenarios}. In the next two sub-sections, we report some applications of RISs and some scenarios for SREs. For ease of representation, the illustrations are given without explicitly referring to a centralized, distributed, or hybrid implementation. In principle, the three approaches can be realized with their advantages and limitations. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_10.pdf} \caption{Potential applications of reconfigurable intelligent surfaces in smart radio environments.} \label{Fig_10} \end{centering} \end{figure} \subsection{Potential Applications of Reconfigurable Intelligent Surfaces in Smart Radio Environments} \label{RISs_Applications} In this section, we briefly describe some potential applications of RISs. Some of them are illustrated in Fig. \ref{Fig_10} as examples. \begin{itemize} \item \textbf{\textit{Coverage enhancement}}. An RIS can be configured in order to create configurable non-line-of-sight links in dead-zone (or low coverage) areas in which line-of-sight communication is not possible or it is not sufficient. \item \textbf{\textit{Interference suppression}}. An RIS can be configured to steer signals towards specified directions or locations not only for enhancing the signal quality, but for suppressing unwanted signals that may interfere with other communication systems. \item \textbf{\textit{Security enhancement}}. This application is similar to interference suppression, with the difference that an RIS can be configured to worsen the signal detected by eavesdroppers by either creating destructive interference or by altering the reflection of signals towards locations not occupied by unauthorized users. \item \textbf{\textit{Channel rank enhancement}}. The spatial multiplexing gain that can be achieve in multiple-antenna systems depends on how well conditioned the channel matrix is. An RIS can be appropriately configured in order shape the wireless environment in a way that the channel matrix has a high rank and a condition number close to one, so as to increase the channel capacity. \item \textbf{\textit{Focusing enhancement}}. An RIS of large geometric size (in further text referred to as electrically large RIS) can operate in the radiative near-field at transmission distances up to a few tens of meters, as illustrated in Figs. \ref{Fig_7} and \ref{Fig_8}. Therefore, the scattered radio waves can be focused towards spatial spots of narrow size, so as to capillary serve dense deployments of users without creating mutual interference. \item \textbf{\textit{Radio localization enhancement}}. The high focusing capabilities of RISs of large geometric size can be capitalized for finely estimating the location of mobile terminals and devices, so as to support high-precision ranging, radio localization, and mapping applications. \item \textbf{\textit{Information and power transfer}}. The high focusing capabilities of RISs of large geometric size can be exploited for concentrating the energy towards tiny and energy-autonomous sensor nodes, so that the radio waves can be employed, simultaneously, to recharge the sensors and to transmit information. \item \textbf{\textit{Ambient backscattering}}. Consider a low power sensor node that is embedded into a smart surface for environmental monitoring. Any time that a radio wave impinges upon the smart surface, the RIS may be configured to modulate/encode the data sensed by the low power sensor into the scattered signal, e.g., by transmitting the sensed data through the time-domain scattered waveform (see Fig. \ref{Fig_5}). This enables low power sensors to piggyback information into ambient radio waves without creating new radio signals and, de facto, by recycling existing radio waves for communication \cite{ORANGE_BackScattering_1}, \cite{ORANGE_BackScattering_2}. \end{itemize} Other applications, such as RIS-based modulation, RIS-based multi-stream transmission, and RIS-based encoding are depicted in Fig. \ref{Fig_6} and are described in Section \ref{MacroscopicFunctions}. \begin{figure*}[!t] \begin{centering} \includegraphics[width=2\columnwidth]{Fig_11.pdf} \caption{Potential scenarios of smart radio environments: A world of nearly-passive reconfigurable intelligent surfaces.} \label{Fig_11} \end{centering} \end{figure*} \subsection{Potential Scenarios of Smart Radio Environments} \label{SREs_Scenarios} Several potential scenarios can benefit from the concept of SREs. Some promising case studies are briefly discussed as follows, and a sub-set of them is illustrated in Fig. \ref{Fig_11}. \begin{itemize} \item \textbf{\textit{Smart cities}}. In cities, the facades of large buildings may be coated with RISs of large geometric size. This offers opportunities for, e.g., enhancing the coverage, increasing the spectral efficiency, and reducing the exposure to the EM radiation in outdoor environments, since the deployment of RISs may reduce the amount of network infrastructure (e.g., based stations) to deploy. \item \textbf{\textit{Smart homes}}. In homes, the interior walls may be coated with RISs of different sizes for enhancing the local connectivity of several kinds of handlers (mobile phones, tablets, etc.) and other devices that rely on wireless connectivity for operation. \item \textbf{\textit{Smart buildings}}. In buildings, large windows may be made of special glasses that can selectively enable indoor-to-outdoor and outdoor-to-indoor connectivity. This may be suitable for enhancing the connectivity at high transmission frequencies. \item \textbf{\textit{Smart factories}}. In factories, the presence of large metallic objects usually result in harsh wireless propagation environments. RISs constitute a suitable approach for turning strong reflections of radio waves into a benefit for enhancing the coverage and the transmission rate. \item \textbf{\textit{Smart hospitals}}. Hospitals are EM-sensitive environments, where the intensity of the radio waves needs to be kept at a low level. RISs can be employed in order to enhance the local coverage without the need of increasing the transmitted power. \item \textbf{\textit{Smart university campuses}}. In university campuses, large buildings, offices, classrooms, etc. can be coated with RISs that can offer the desired high-speed connectivity without the need of installing several access points. \item \textbf{\textit{Smart undergrounds}}. In undergrounds, the coverage of wireless signals is usually negatively affected by the complex topology of the radio environment. RISs can be deployed in, e.g., ceilings, billboards, and walls, so as to provide the necessary connectivity to a large number of users simultaneously. \item \textbf{\textit{Smart train stations}}. In train stations, several users may be waiting on the platforms before the arrival of trains. RISs can be deployed for illuminating areas of the platforms in order to enhance the received signals of individual users or clusters of users. \item \textbf{\textit{Smart airports}}. In airports, large numbers of users may make take different directions when disembarking from airplanes. RISs can be employed for steering different beams towards different hallways, so as to enhance the quality of the received signals. Also, RISs may be used to enhance the signals in high-speed download areas, e.g., Internet areas in close proximity of the gates. \item \textbf{\textit{Smart billboards}}. Billboards may constitute a promising approach for deploying RISs of different geometric size in a simple and effective manner, both in indoor and outdoor environments. \item \textbf{\textit{Smart glasses}}. In urban areas, large portions of the surface of buildings are made of glass. The example in Fig. \ref{Fig_3} shows that smart glasses realized with metasurfaces can be built and can effectively control the propagation of radio waves. These smart glasses can be employed for enhancing the coverage in, e.g., dead-zone areas. \item \textbf{\textit{Smart clothing}}. Clothing can be realized with metamaterials and several embedded smart sensors in order to create wearable body networks for monitoring the health of people. \item \textbf{\textit{Smart cars}}. The glasses and the roof of cars may be coated with RISs that can provide reliable communications within the car itself, as well as can serve as moving nearly-passive relays for enhancing vehicle-to-vehicle and vehicle-to-infrastructure communications. \item \textbf{\textit{Smart trains}}. The interior of trains may be coated with RISs in order to provide a better signal coverage and to reduce the levels of EM radiation and the exposure of passengers to EM fields. \item \textbf{\textit{Smart airplanes}}. The overhead bins inside airplanes may be coated with RISs that may provide high-speed Internet to passengers while reducing their EM field exposure and/or decreasing the power consumption. \end{itemize} \textbf{Aesthetically-friendly environments}. In our everyday life, in conclusion, RISs may offer countless opportunities to realize SREs. One of the advantages of metasurfaces is that they can be built, e.g., by using the smart glass in Fig. \ref{Fig_3}, so as not to interfere aesthetically or physically with the surrounding environment or people line-of-sight, making them ideal for use within buildings and on vehicles or billboards. RISs can be deployed every time and in locations that are not suited for the installation of base stations, such as built-up areas or in indoor areas in which the reception of signals needs to be blocked selectively (e.g., in high-security areas). \subsection{On the Role of Machine Learning in Smart Radio Environments} \label{SREs_ML} \textbf{Awareness of the surrounding environment}. In order to realize a ``truly smart'' SRE, it is not sufficient to be able to customize the radio environment as desired. It is necessary, in addition, to optimally configure the most appropriate operation of spatially distributed RISs, in order to provide the users with the best communication performance and quality of experience. RISs necessitate, therefore, full awareness of the complex and non-stationary surrounding environments in which they are deployed. This requires efficient and on-demand network intelligence to cope with complex deployment planning, real-time programmability for optimization, and dynamic control for service provisioning. Machine learning and artificial intelligence (AI) may constitute efficient approaches for leveraging the potential benefits of RIS-empowered SREs, especially because the computational complexity of deploying, programming, and controlling SREs rises significantly with the increase of the network-to-infrastructure and user-to-network interactions. \textbf{AI is the answer}. Therefore, machine learning computational methods may be suitable enablers for optimizing and operating SREs. AI-enabled machines, in particular, can be designed to perform ``intelligent'' tasks without being programmed to accomplish any single (repetitive) task, but by adapting themselves to different environments. To this end, AI provides methods for designing networks that autonomously interact with the environment, in ways that humans consider intelligent, including the characteristics of human cognitive abilities, i.e., planning, perceiving, reasoning, learning, and problem solving. AI defines general frameworks for knowledge manipulation (building new knowledge and exploiting already gained knowledge) through perception, reasoning (specifying what is to be done, but not how) and acting. SREs may be designed by leveraging and capitalizing on AI-based reasoning, acting, planning, and learning. Further information on the application of machine learning and AI to SREs can be found in \cite{MDR_AI_VTM}, \cite{MDR_AM_TCOM}, \cite{MDR_AI_RIS}. \section{RISs in Wireless Networks -- A Macroscopic Homogenized Communication-Theoretic Approach} \label{CommTheory} \textbf{Communication-theoretic modeling and analysis}. This section introduces analytical methods and methodologies for modeling RISs that are made of metasurfaces, and for computing the EM field scattered by metasurfaces. To this end, this section is split in two main parts. \begin{itemize} \item \textit{\textbf{Modeling metasurfaces}}. In the first sub-section, we move from a physics-based \textit{microscopic} description of a metasurface and introduce a \textit{macroscopic} representation for it, which is shown to be suitable for application in wireless communications. In particular, a metasurface is represented by using continuous inhomogeneous functions that allow one to describe the signal transformations applied by a metasurface directly on the EM fields. The use of continuous functions is allowed, even though the (conceptual) physical structure of the metasurface in Fig. \ref{Fig_4} is made of discrete unit cells (scatterers), because a metasurface can be homogenized. Therefore, its EM properties can be completely described through macroscopic parameters, in analogy with volumetric materials that can be completely described through their effective permittivity and permeability parameters. The homogenized macroscopic representation of a metasurface based on continuous inhomogeneous functions is shown to be useful for the \textit{synthesis} (i.e., to design a metasurface based on specified/desired signal transformations) and for the \textit{analysis} (i.e., to compute the reflected and refracted EM fields in close proximity of a metasurface, for a given incident EM field and the physical structure of the metasurface) of RISs. \item \textit{\textbf{Modeling radio waves}}. In the second sub-section, we consider the interaction between the radio waves emitted by a source and a metasurface. We introduce an analytical approach, based on the \textit{theory of diffraction} and the \textit{Huygens-Fresnel principle}, which allows us to compute the EM field at any point of a given volume that contains the metasurface. In particular, we show that the EM field at any point of the volume can be formulated in terms of the EM field in close proximity of the metasurface (i.e., on its surface), as specified in the first sub-section. \end{itemize} \textbf{Modeling radio waves in the presence of metasurfaces}. It is apparent, therefore, that the next two sub-sections are intertwined, and are both needed for designing, analyzing, and optimizing RISs in wireless networks. In particular, the first sub-section introduces the analytical tools for modeling the discontinuity of the EM field at the incidence-reflection side and refraction side of a metasurface. The second sub-section, on the other hand, departs from the latter surface EM fields and introduces the analytical tools for calculating the EM field at any point of a volume, which, for example, allows one to unveil how the EM fields scale as a function of the transmission distance, the size of the metasurface, and the physical structure of the metasurface. \subsection{Surface Electromagnetics} \label{SEM} Before introducing the details of the concept of homogenized modeling for metasurfaces, we feel important to briefly acquaint the readership of the present paper with the research discipline of surface electromagnetics (SEM), which is the enabling tool for modeling, analyzing, and synthesizing metasurfaces. The content of this sub-section is, in particular, based on the textbook \cite{Book_SurfaceElectromagnetics}, to which interested readers are referred for further information. \textbf{Definition of SEM}. Electromagnetics is a fundamental discipline of sciences that describes the temporal and spatial behavior of the electric and magnetic fields. Broadly speaking, electromagnetics can be defined as the theory of EM fields and waves. SEM is a sub-discipline of electromagnetics. From the temporal point of view, electromagnetics is usually classified into different categories according to the oscillation frequency of the EM fields, such as direct current (DC), RF, microwaves, terahertz (THz), optics, X-rays, and beyond. The definition of SEM can be traced back to the classification of electromagnetics from the spatial point of view. Four regimes can be identified in the space domain, and each of them is usually modeled through \textit{effective parameters}, which are viewed as an adequate simplification of Maxwell's equations under the corresponding spatial regime \cite[Chapter 1]{Book_SurfaceElectromagnetics}. \begin{itemize} \item \textit{\textbf{Zero-dimensional EM phenomena}}. This regime occurs when the spatial variations of a device or an EM phenomenon are much smaller than the wavelength of the radio waves in all three spatial dimensions. \textit{Circuit theory} is considered to be an accurate and efficient approach for modeling zero-dimensional EM phenomena. The effective parameters that are usually employed in circuit theory are the resistor, the inductor, and the capacitor. \item \textit{\textbf{One-dimensional EM phenomena}}. This regime occurs when the longitudinal dimension and the transverse dimensions of a device or an EM phenomenon are comparable to and much smaller than, respectively, the wavelength of the radio waves. In this regime, circuit theory is no longer valid and it is replaced by \textit{transmission line theory}. The effective parameters that are usually employed in transmission line theory are the characteristic impedance and the propagation constant. \item \textit{\textbf{Two-dimensional EM phenomena}}. This regime occurs when the longitudinal dimension and the transverse dimensions of a device or an EM phenomenon are much smaller than and comparable to, respectively, the wavelength of the radio waves. This is the regime of interest of this paper and it will be comprehensively elaborated in further text through its corresponding effective (surface-averaged homogenized) parameters. \item \textit{\textbf{Three-dimensional EM phenomena}}. This is the most general regime in which the variations of the EM fields are comparable to the wavelength of the radio waves in all three spatial dimensions. Maxwell's equations are usually employed to analyze this regime. The effective parameters that are employed in this regime are the electric permittivity and magnetic permeability of the volumetric material. \end{itemize} \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_Book_1.pdf} \caption{Classification of electromagnetics in the spatial domain (reproduced from \cite{Book_SurfaceElectromagnetics}).} \label{Fig_Book_1} \end{centering} \end{figure} A graphical comparison among these four operating spatial regimes is sketched in Fig. \ref{Fig_Book_1}, which is reproduced from \cite{Book_SurfaceElectromagnetics}. Broadly speaking, effective parameters allow one to (approximately) model natural and artificial structures and EM phenomena as a whole, instead of modeling their many constituent elements individually. Therefore, they are a convenient tool for studying complex EM phenomena and structures from the macroscopic point of view. \textbf{From uniform to quasi-periodic metasurfaces}. In the context of SEM research and development, it is important to distinguish three milestones that characterize the evolution of the spatial variations along the transverse dimensions of a metasurface. \begin{itemize} \item \textit{\textbf{Uniform metasurfaces}}. By definition, (natural) surfaces are uniform surfaces. They are characterized by variations of the properties of the medium, which surrounds the surface, along the longitudinal direction. The properties of the surface does not change, on the other hand, along the tangential directions, i.e., on the surface itself ($z=0$ in Fig. \ref{Fig_4}). \item \textit{\textbf{Periodic metasurfaces}}. In contrast to uniform surfaces, periodic surfaces exhibit spatial variations along the tangential directions. Concretely, this implies that the unit cells in Fig. \ref{Fig_4} are arranged in a periodic lattice and each unit cell has the same geometry and size. \item \textit{\textbf{Quasi-periodic metasurfaces}}. Similar to periodic surfaces, quasi-periodic surfaces exhibit spatial variations along the tangential directions. In contrast to periodic surfaces, the unit cells are still arranged in a periodic lattice, but each unit cell differs from the others in terms of, e.g., geometrical variations, shape, size, orientation angle, etc. This is the configuration reported in Fig. \ref{Fig_4}. \end{itemize} \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_Book_2.pdf} \caption{The road to quasi-periodic metasurfaces (reproduced from \cite{Book_SurfaceElectromagnetics}).} \label{Fig_Book_2} \end{centering} \end{figure} \textbf{Similarity with modulated signals}. The evolution from the uniform, periodic, and quasi-periodic feature of the transverse dimensions of a metasurface can be considered to be equivalent to the evolution of the analysis of signals in circuits, i.e., from DC signals, to alternate current (AC) signals, and eventually to modulated signals. A graphical comparison among the uniform, periodic, and quasi-periodic design structures is reported in Fig. \ref{Fig_Book_2}, which is reproduced from \cite{Book_SurfaceElectromagnetics}. The quasi-periodic structure of the smart surface in Fig. \ref{Fig_4} is, therefore, apparent and completely justified. \textbf{Naive interpretation of quasi-periodic metasurfaces}. The core concept behind the development and widespread utilization of quasi-periodic metasurfaces lies in their more versatile, unprecedented, and exotic capabilities of manipulating EM waves. Naively, the operating principle of quasi-periodic metasurfaces can be thought of as a two-step manipulation of the radio waves: (i) first, each unit cell manipulates the incident radio waves locally and individually; and (ii) next, the spatial distribution of the obtained wave manipulations collectively alters the wavefront of the incident radio waves, leading to extraordinary EM responses and transformations of EM fields. \subsection{Theoretical Foundation of Surface Electromagnetics} \label{SEM_Theory} \textbf{Volumetric (bulk) vs. surface effective parameters}. The behavior and the properties of metamaterials, which are volumetric engineered structures, are determined by the electric and magnetic properties of its constituent scatterers. The traditional and most convenient approach for modeling metamaterials is the \textit{effective medium theory} (EMT). EMT pertains to the theoretical and analytical models and methods for describing the macroscopic properties of composite materials. At the constituent level, composite materials can be viewed as a micro-inhomogeneous medium. The precise calculation and analysis of the many elements that constitute a composite material is a nearly impossible task. EMT provides one with a set of effective parameters that describe, approximately, a composite material as a whole. These parameters are, e.g., the effective electric permittivity and the effective magnetic permeability of the composite material, which are obtained by averaging (over a small volume) the response of the multiple constituents that compose the material. More precisely, the notions of electric permittivity and magnetic permeability result from the volumetric averaging of microscopic electric and magnetic currents over volumes that are small compared to the wavelength of the radio waves. A similar bulk-parameters representation is, in general, not appropriate for metasurfaces \cite[Chapter 3]{Book_SurfaceElectromagnetics}. In this case, surface-averaged effective parameters are a more physically sound and accurate choice, as compared with volumetric-averaged effective parameters that account for an arbitrary non-zero thickness parameter in order to model the sub-wavelength thickness of metasurfaces. If a metasurface is, in particular, modeled by using an effective permittivity and and effective permittivity, then these two parameters have to be infinite. This is because the reflection coefficient from a material slab tends to zero when the its thickness tends to zero. Therefore, a model based on effective permittivities and permeabilities implies the need of having a surface of finite (non-zero) thickness. In detail, surface-averaged effective parameters result from the surface averaging of microscopic currents over a surface area of the order of the wavelength. This implies that the conventional notions of electric permittivity and magnetic permeability lose their meaning because there is no volume over which the EM fields and their corresponding induced currents can be averaged out. Surface averaging methods lead to the introduction of effective surface parameters, which include surface susceptibility functions and sheet impedances. These parameters are formally introduced in further text along with the concept of homogenized models for metasurfaces. We anticipate that surface-averaged effective parameters constitute an essential notion for developing macroscopic models and representations of metasurfaces. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_Book_3.pdf} \caption{Illustration of the surface equivalent theorem applied to the scattering of volumetric electromagnetic sources (a) and to the concept of metamaterials (b) (reproduced from \cite{Book_SurfaceElectromagnetics}).} \label{Fig_Book_3} \end{centering} \end{figure} \textbf{The surface equivalence theorem}. The surface equivalence theorem can be regarded as the physics-based foundation of SEM \cite{Book_SurfaceElectromagnetics}. The basic idea of the surface equivalence theorem originates from the \textit{Huygens's principle}, which states that ``each point on a primary wavefront can be considered to be a new source of a secondary spherical wave, and that a secondary wavefront can be constructed as the envelope of these secondary spherical waves'', and from the \textit{uniqueness theorem}, which, in the context of this paper, can be stated as ``if the tangential electric and magnetic fields are completely known over a closed surface, the fields in the source-free region can be determined'' \cite[Chapter 1]{Book_SurfaceElectromagnetics}. The surface equivalence theorem is illustrated in Fig. \ref{Fig_Book_3}, which is reproduced from \cite[Chapter 2]{Book_SurfaceElectromagnetics}. Let us consider a volume $V$ that is filled with arbitrary sources of EM radiation, e.g., some charges $q_i$ and some currents $\mathbf{J}_i$. These sources create an electric field, $\mathbf{E}$, and a magnetic induction field, $\mathbf{B}$, outside the volume $V$. According to the Huygens principle, the system of scatterers can be replaced by an arbitrarily thin layer of specific electric currents, $\mathbf{J}_{\rm{eV}}$, and magnetic currents, $\mathbf{J}_{\rm{mV}}$, that encloses the volume $V$. The thickness of the layer can be electrically small but non-zero since magnetic currents can be generated only via loops of electric currents with finite thickness. The equivalent (surface) currents $\mathbf{J}_{\rm{eV}}$ and $\mathbf{J}_{\rm{mV}}$ scatter EM fields only outward of the volume $V$, and these EM fields are the same as those created by the original system of sources. Such currents, which scatter EM fields only in one side, are referred to as Huygens's surfaces or Huygens's sources. This concept can be applied to metamaterials. Let us consider an arbitrary volumetric metamaterial sample that is excited by an arbitrary external EM wave whose wavevector is $\mathbf{k}_i$. The external wave induces some charges $q_i$ and currents $\mathbf{J}_i$ in the inclusions (or unit cells) of the sample, which irradiate secondary EM fields $\mathbf{E}_{\rm{out}}$ and $\mathbf{B}_{\rm{out}}$ into the space outside the volume $V$ that encloses the metamaterial sample. According to the Huygens principle, one can replace the bulky metamaterial sample with induced polarization charges and currents by equivalent surface currents $\mathbf{J}_{\rm{eV}}$ and $\mathbf{J}_{\rm{mV}}$ that scatter the same EM fields $\mathbf{E}_{\rm{out}}$ and $\mathbf{B}_{\rm{out}}$ outside the volume $V$. By knowing these equivalent currents, one can determine appropriate topologies of unit cells (meta-atoms in the figure), which are placed along the surface of the volume $V$ and generate, if illuminated by an external EM wave with wavevector $\mathbf{k}_i$, the same currents $\mathbf{J}_{\rm{eV}}$ and $\mathbf{J}_{\rm{mV}}$ as those of the original volumetric setup. The resulting arrangement of unit cells is the metasurface structure that yields the same EM response as that of the original metamaterial sample. Broadly speaking, therefore, the surface equivalence theorem states that volumetric metamaterials can be replaced by electrically thin and, in general, curved metasurfaces, i.e., structures whose surface is engineered to provide field transformation capabilities. The surface equivalence theorem is, therefore, the core tenet behind the development and evolution from metamaterials to metasurfaces. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_Book_4.pdf} \caption{Illustration of homogenization: A metasurface consisting of arbitrary sub-wavelength unit cells is modeled as a continuous sheet of surface-averaged (over the unit cell) currents (reproduced from \cite{Book_SurfaceElectromagnetics}).} \label{Fig_Book_4} \end{centering} \end{figure} \textbf{Homogenized modeling of metasurfaces}. As anticipated in previous text, a metasurface can be homogenized owing to the sub-wavelength inter-distance among its constituent sub-wavelength unit cells. Concretely, this implies that the EM properties of a metasurface can be completely described by using macroscopic effective (surface) parameters, similar to the macroscopic effective (volumetric) parameters that describe three-dimensional materials, e.g., the effective permittivity and permeability. Knowledge of the macroscopic effective (surface) parameters of a metasurface allows one to formulate its EM response to arbitrary (in terms of wavefront, incidence angle, and polarization) impinging EM waves. This implies that macroscopic models for metasurfaces, which are described in the next sub-sections, do not assume that the impinging EM fields are plane wave. It is necessary, however, that the incident EM fields do not change significantly over the scale of one unit cell. This condition is usually fulfilled in metasurface structures whose unit cells have sub-wavelength inter-distances and sub-wavelength sizes. It is worth mentioning that, on the other hand, it is not possible to introduce effective macroscopic parameters for non-homogenizable structures, even if such structures are electrically thin. Constructing a homogenization model corresponds (i) to determine the effective parameters that can appropriately describe the response of a metasurface to incident EM fields and (ii) to identify such effective parameters from the physical and EM properties of the unit cells. The last step can be performed by using experimental data or simulations of the metasurface response as well. Homogenization is a fundamental prerequisite for understanding, modeling, and designing metasurfaces. By using effective parameters, the complexity of the problem is remarkably reduced, since modeling the collective response of many individually small unit cells is a complex brute-force numerical optimization problem. In (volumetric) metamaterials, as mentioned, homogenized models are obtained through effective parameters that are averaged over small volumes that contain many unit cells. Due to the sub-wavelength thickness of metasurfaces, homogenized models are obtained through effective parameters that are averaged over small surface areas (whose dimensions are of the order of one wavelength) that contain several unit cells. If the impinging EM fields are plane waves, surface averaging over the area of one unit cell is usually sufficient. The concept of homogenized equivalent of a metasurface is sketched in Fig. \ref{Fig_Book_4}, which is reproduced from \cite[Chapter 2]{Book_SurfaceElectromagnetics}. The figure depicts a metasurface that consists of an array of sub-wavelength unit cells. Since the inter-distance between adjective unit cells is sufficiently small compared to the wavelength of the impinging EM fields, the incident radio waves can be assumed to be uniform or homogeneous along the size of a single unit cell. The impinging EM fields induce electric and magnetic currents in each unit cell. In homogenized models, the position-dependent induced electric and magnetic currents in each unit cell are replaced by surfaced-averaged (hence macroscopic) effective parameters. By using homogenization, therefore, a metasurface is modeled as a planar thin sheet of electric and magnetic surface-averaged current densities or, as described in further text, polarization surface densities. This implies that the modeling and analysis of the scattering from a metasurface that is made of finite-size (or discrete) unit cells is turned into the modeling and analysis of the scattering from an equivalent continuous sheet of electric and magnetic currents. \subsection{On Modeling Metasurfaces: A Macroscopic Homogenized Approach} \label{MacroscopicApproach} Starting from the introductory material on SEM, this sub-section is focused on reporting tractable analytical models for metasurfaces. Special emphasis is, in particular, put on the theory that leads from a microscopic to a macroscopic representation of metasurfaces through surface-averaged homogenized effective parameters. \textbf{From a microscopic to a macroscopic representation}. We consider an RIS made of a metasurface according to the definition given in Section II, i.e., the smart surface is electrically thin, electrically large, homogenizable, and has a sub-wavelength structure. Under these assumptions, we begin our development by introducing a microscopic description of a metasurface that is based on and accounts for the spatial coupling between adjacent unit cells, which is due to their sub-wavelength inter-distance. The obtained physics-based model may not, however, be sufficiently flexible for designing and analyzing complex metasurfaces. Subsequently, for this reason, we introduce a macroscopic description of a metasurface, which is based on continuous tensor functions, that yields a more suitable representation of a metasurface, especially for application to wireless networks. The macroscopic approach, however, still allows us to obtain a direct connection with the material parameters, i.e., the surface susceptibility of the smart surface. Based on the introduced macroscopic description of a metasurface, finally, we discuss its synthesis and analysis. \textbf{Reconciling communication and electromagnetism}. It is worth mentioning that the approach reported in this sub-section is widely employed in the fields of electromagnetism and metamaterials, and our treatise is mainly based on the theories available in \cite{Holloway_Oct2003}, \cite{Holloway_Nov2005}, \cite{Caloz_GSTCs2015}, \cite{Caloz_Synthesis2018}, \cite{Caloz_Computational2018}. These methods are, however, not necessarily known to wireless researchers. The main objective of this sub-section is to fill this gap of knowledge in a simple but rigorous manner, and with the aid of some examples and case studies. \subsubsection{EM-Based Model of a Metasurface} Our departing point is the EM-based model of a metasurface reported in \cite{Holloway_Oct2003}, \cite{Holloway_Nov2005}. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_12.pdf} \caption{Example of induced electric dipole moment and electric polarization density ($\mathbf{P}$) in volumetric materials.} \label{Fig_12} \end{centering} \end{figure} \textbf{A metasurface as a surface distribution of electrically small resonant scatterers}. In the most general sense, a metasurface (also called a metafilm in \cite{Holloway_Oct2003}, \cite{Holloway_Nov2005}) is viewed as a surface distribution of electrically small resonant scatterers, and it is characterized by electric and magnetic surface polarization densities. In simple terms, the electrically small scatterers are the unit cells in Fig. \ref{Fig_4}. In volumetric, three-dimensional materials, the electric polarization density is a vector field that expresses the density of permanent or induced electric dipole moments in a dielectric material. When a dielectric is placed in an external electric field, its molecules gain electric dipole moment and the dielectric is said to be polarized. The electric dipole moment induced per unit volume of the dielectric material is referred to as the electric polarization of the dielectric. The electric polarization density describes how a material responds to an applied electric field and how the material changes the electric field. More precisely, an external electric field that is applied to a dielectric material causes a displacement of bound charged elements, which are elements bound to molecules and, hence, are not free to move around the material. Positive charged elements are displaced in the direction of the electric field and negative charged elements are displaced in the opposite direction of the field. The molecules may remain neutral in charge, but an electric dipole moment is formed. The electric polarization density corresponds to the induced dipole moment per unit volume of the material. For ease of understanding, this concept is sketched in Fig. \ref{Fig_12}. Similarly, the magnetic polarization density describes how a material responds to an applied magnetic field. To model metasurfaces as sheets of electrically negligible thickness, the concept of electric and magnetic surface polarization densities is used. The electric (magnetic) surface polarization density is the electric (magnetic) dipole moment per unit area of the surface, while the usual volumetric electric (magnetic) polarization density is the electric (magnetic) dipole moment per unit volume. \textbf{A metasurface as an array of polarizable unit cells}. A metasurface can be broadly defined as an array of polarizable unit cells that induce discontinuities of the electric and magnetic fields at the two sides of the surface, i.e., at $z=0^+$ and $z=0^-$ in Fig. \ref{Fig_4}. The objective of a macroscopic description of a metasurface consists of formulating and expressing the discontinuities of the electric and magnetic fields as a function of surface-averaged electric and magnetic surface polarization densities. Since a metasurface is homogenizable, i.e., the distance between adjacent unit cells is much smaller than the wavelength of the radio waves, the approach consists of replacing the discrete distribution of unit cells with a continuous distribution, which, in turn, results in a continuous function of electric and magnetic surface polarization densities. It is worth nothing that the unit cells may be of arbitrary shape and are not infinitely thin. Their thickness is only required to be small in comparison with the wavelength of the radio waves. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_13.pdf} \caption{Equivalent analytical representation of a metasurface: A zero-thickness material sheet whose EM properties are modeled through surface susceptibility functions that introduce EM discontinuities (or ``jumps'') quantified by the generalized sheet transition conditions.} \label{Fig_13} \end{centering} \end{figure} \textbf{Towards a macroscopic description}. A macroscopic description of a metasurface consists of replacing the actual spatial distribution of the unit cells on the smart surface with analytical relations between the electric and magnetic fields at the two sides of the metasurface (at $z=0^+$ and $z=0^-$ in Fig. \ref{Fig_4}). Conceptually, this equivalence is illustrated in Fig. \ref{Fig_13}. The size, the shape, and the physical characteristics of the unit cells are directly incorporated into these analytical relations through the homogenized (continuous) electric and magnetic surface polarization densities. The analytical relations that express the electric and magnetic fields at the two sides of a metasurface as functions of the homogenized (continuous) electric and magnetic surface polarization densities are referred to as \textit{generalized sheet transition conditions (GSTCs)}. It is worth anticipating that the EM fields and the effective parameters that appear in a macroscopic formulation of the GSTCs are surface-averaged quantities, i.e., they are averaged over small areas of the order of a wavelength. \textbf{Generalized sheet transition conditions}. As far as the GSTCs are concerned, three remarks are worth mentioning. \begin{itemize} \item \textit{\textbf{The tangential components of the EM fields are sufficient}}. The electric and magnetic fields that appear in the GSTCs involve only their tangential (or transverse) components across the surface. In other words, the cartesian or longitudinal component of the EM fields along the $z$-axis in Fig. \ref{Fig_4} does not explicitly appear. This is because they can be uniquely determined by the transverse components by virtue of the uniqueness theorem \cite{Caloz_GSTCs2015}. \item \textit{\textbf{The EM fields have variations on scales larger than the wavelength}}. The electric and magnetic fields that appear in the GSTCs do not exhibit variations on a length scale that is comparable with the dimension of the unit cells and with their inter-distance. They only exhibit variations on a length scale that is larger than the wavelength of the radio waves. In the present paper, however, the corresponding model is still referred to as microscopic because it requires an appropriate definition of the spatial coupling between adjacent unit cells \cite{Holloway_Oct2003}. We use the term macroscopic modeling to identify similar analytical relations in which this coupling is implicitly taken into account by using surface-averaged susceptibility tensor functions \cite{Caloz_GSTCs2015}. This concept is better elaborated in further text. \item \textit{\textbf{Generalization of conventional interface conditions}}. The GSTCs, which best characterize a metasurface as an EM discontinuity, constitute a generalization of conventional interface conditions for the EM fields at the interface of two media. For example, it is known that the tangential components of the electric field are continuous at the interface of two media. This is not true if the interface is constituted by a zero-thickness metasurface that acts as an EM discontinuity. The relations between the tangential components of the electric and magnetic fields are, in fact, specified by the GSTCs. In general, the tangential components of the electric and magnetic fields are different at the two sides of a metasurface, i.e., they are discontinuous. It is usual jargon to say that the GSTCs formulate the ``jumps'' (i.e., discontinuities) of the electric and magnetic fields at the two sides of a metasurface. \end{itemize} \begin{table}[!t] \centering \caption{Recurrent notation ($k = 2\pi / \lambda = \omega \sqrt{\mu \varepsilon}$).} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{tabular}{l||l} \hspace{0.15cm} Symbol & \hspace{2.50cm} Definition \\ \hline \hline ${()}^*$ & Complex conjugate \\ ${\mathop{\rm Re}\nolimits} \left\{ \cdot \right\}$ & Real part \\ ${()}^T$ & Matrix transpose \\ ${()}^H$ & Hermitian conjugate \\ ${()}^\dag$ & Pseudo inverse \\ $\cdot$ & Scalar product \\ $\times$ & Vector product \\ $\widehat {()}$ & Unit vector \\ $\lambda$ & Wavelength \\ $\omega$ & Angular frequency \\ $\varepsilon$ & Permittivity in vacuum \\ $\mu$ & Permeability in vacuum \\ $\eta = \sqrt{\mu / \varepsilon}$ & Impedance in vacuum \\ $k$ & Wavenumber \\ $\textbf{P}(x,y)$ & Electric surface polarization density \\ $\textbf{M}(x,y)$ & Magnetic surface polarization density \\ ${{\bf{P}}_{_\parallel }}\left( {x,y} \right)$ & Longitudinal component of $\textbf{P}(x,y)$\\ ${{\bf{M}}_{_\parallel }}\left( {x,y} \right)$ & Longitudinal component of $\textbf{M}(x,y)$\\ $\textbf{E}(x,y,z)$ & Electric field \\ $\textbf{H}(x,y,z)$ & Magnetic field \\ $\textbf{D}(x,y,z)$ & Electric displacement field \\ ${E}_{x,y} (x,y)$ & Tangential components of the electric field \\ ${H}_{x,y} (x,y)$ & Tangential components of the magnetic field \\ $i$, $r$, $t$ & Incident, reflected, transmitted field \\ $\theta_i$, $\theta_r$, $\theta_t$ & Angle of incidence, reflection, transmission \\ ${\overline{\overline \chi } _{{\rm{ab}}}}\left( {x,y} \right)$ & Surface susceptibility dyadics \\ $R(x,y)$ & Surface reflection coefficient \\ \hline \hline \end{tabular} \label{Table_Notation} \end{table} \subsubsection{Microscopic Description of a Metasurface} \textbf{From unit cells to mathematics}. After introducing the general definition of GSTCs and the general meaning of macroscopic homogenized description of a metasurface, we are ready to formulate these two concepts in analytical terms. To this end, we depart from the physical structure of a metasurface and its microscopic representation. The corresponding macroscopic homogenized description is derived in the next sub-section. \textbf{Metasurface structure}. We consider a two-dimensional metasurface that lies on the $xy$-plane at $z=0$. The metasurface is centered at the origin and has a finite size equal to $2L_x$ and $2L_y$ along the $x$-axis and $y$-axis, i.e., $-L_x \le x \le L_x$ and $-L_y \le y \le L_y$, respectively. Without loss of generality, we assume that the incidence-reflection side of the metasurface is $z=0^+$ and the transmission side of the metasurface is $z=0^-$. Also, we assume that the medium surrounding the metasurface is vacuum. The symbols and definition used throughout the present paper are reported in Table \ref{Table_Notation}. Our analytical formulation is mostly based on \cite{Caloz_GSTCs2015}, \cite{Caloz_Synthesis2018}, \cite{Caloz_Computational2018}. For simplicity, we consider the sufficient general case of metasurfaces whose longitudinal components of the electric ($\textbf{P}$) and magnetic ($\textbf{M}$) surfaces polarization densities are equal to zero, i.e., $P_z = 0$ and $M_z = 0$, respectively. We show in further text that this assumption allows one to design metasurfaces that realize EM-based functions that are sufficiently general for wireless applications, e.g., reflection and refraction towards arbitrary directions. The advantage of this assumption is that closed-form analytical expressions for the EM fields are obtained. \textbf{Analytical formulation of GSTCs}. Let us consider an EM field that illuminates a metasurface. Under the assumption $P_z = 0$ and $M_z = 0$, the GSTCs, i.e., the ``jumps'' of the electric and magnetic fields at the two sides of a metasurface, can be formulated as follows: \begin{equation} \label{Eq_GSTCs} \begin{split} \hat z \times \Delta {\bf{H}}\left( {x,y} \right) = j\omega {{\bf{P}}_{_\parallel }}\left( {x,y} \right)\\ \Delta {\bf{E}}\left( {x,y} \right) \times \hat z = j\omega \mu {{\bf{M}}_{_\parallel }}\left( {x,y} \right) \end{split} \end{equation} \noindent where ${{\bf{P}}_{_\parallel }}\left( {x,y} \right)$ and ${{\bf{M}}_{_\parallel }}\left( {x,y} \right)$ are the longitudinal components of the surface-averaged electric and magnetic surface polarization densities, respectively, and $\Delta {\bf{E}}\left( {x,y} \right)$ and $\Delta {\bf{H}}\left( {x,y} \right)$ are the differences between the surface-averaged electric and magnetic fields at the two sides of the metasurface, whose cartesian components can be written, respectively, as follows: \begin{equation} \label{Eq_FieldsDifference} \begin{split} \Delta {\Psi _u}\left( {x,y} \right) &= {\bf{\hat u}} \cdot \left. {\Delta {\bf{\Psi }}\left( {x,y} \right)} \right|_{z = {0^ - }}^{z = {0^ + }}\\ & = \Psi _u^t\left( {x,y} \right) - \left( {\Psi _u^i\left( {x,y} \right) + \Psi _u^r\left( {x,y} \right)} \right) \end{split} \end{equation} \noindent where ${\bf{\Psi }} = \left\{ {{\bf{E}},{\bf{H}}} \right\}$, $u = \left\{ {x,y,z} \right\}$, and the superscripts $i$, $r$ and $t$ denote the incident, reflected, and transmitted components of the fields, respectively. \textbf{Computing $\textbf{P}$ and $\textbf{M}$}. The GSTCs depend on the longitudinal components of the electric and magnetic surface polarization densities. In order to formulate and compute them, we need to investigate the working operation of a metasurface at the microscopic level and we need to introduce the concept of acting (or local) fields. \textbf{Acting (or local) field: Excitation field at the location of an individual unit cell}. At the microscopic level, a metasurface is viewed as an array of electrically small polarizable unit cells. When an EM field illuminates a metasurface, the unit cells get polarized and, since they are small (sub-wavelength) in size, the induced polarizations of each individual unit cell can be modeled through induced electric and magnetic dipole moments (see Fig. \ref{Fig_12}). Since the unit cells are arranged in a dense array, i.e., the inter-distance between adjacent unit cells is sub-wavelength, knowing the polarization induced on a single unit cell is not sufficient to determine the response of the entire metasurface. This is because the EM field that excites a unit cell that occupies a specific location, which is referred to as the acting or local EM field, is given by the summation of the incident EM field and the, so-called, interaction EM field, which is the field created by the induced electric and magnetic dipoles of all the unit cells of the metasurface with the exception of the unit cell under analysis. \textbf{Acting field: Modeling the mutual coupling among unit cells}. By definition, therefore, the acting electric and magnetic fields account for the contribution of all the unit cells of a metasurface with the exception of the given unit cell under consideration. This implies that they account for the mutual (spatial) coupling among the unit cells of a metasurface and that they yield a microscopic description of a metasurface, since the acting fields are referred to individual unit cells. If the acting fields are known, the electric ($\textbf{P}$) and magnetic ($\textbf{M}$) surfaces polarization densities in \eqref{Eq_GSTCs} can be formulated as follows \cite{Holloway_Oct2003}: \begin{equation} \label{Eq_PolarizationMicro__P} \begin{split} {\bf{P}}\left( {x,y} \right) &= \varepsilon N\langle {\overline{\overline \alpha } _{{\rm{ee}}}}\left( {x,y} \right)\rangle {{\bf{E}}_{{\rm{act}}}}\left( {x,y} \right) \\ &+ \sqrt {\mu \varepsilon } N\langle {\overline{\overline \alpha } _{{\rm{em}}}}\left( {x,y} \right)\rangle {{\bf{H}}_{{\rm{act}}}}\left( {x,y} \right) \end{split} \end{equation} \begin{equation} \label{Eq_PolarizationMicro__M} \begin{split} {\bf{M}}\left( {x,y} \right) & = \sqrt {{\varepsilon \mathord{\left/ {\vphantom {\varepsilon \mu }} \right. \kern-\nulldelimiterspace} \mu }} N\langle {\overline{\overline \alpha } _{{\rm{me}}}}\left( {x,y} \right)\rangle {{\bf{E}}_{{\rm{act}}}}\left( {x,y} \right) \\ &+ N\langle {\overline{\overline \alpha } _{{\rm{mm}}}}\left( {x,y} \right)\rangle {{\bf{H}}_{{\rm{act}}}}\left( {x,y} \right) \end{split} \end{equation} \noindent where $N$ is the number of unit cells per unit area, and $\langle {\overline{\overline \alpha } _{{\rm{ab}}}}\left( {x,y} \right)\rangle$, for $a = \left\{ {\rm{e},\rm{m}} \right\}$ and $b = \left\{ {\rm{e},\rm{m}} \right\}$, are the average (electric-electric, electric-magnetic, magnetic-electric, and magnetic-magnetic) polarizability dyadics of the unit cell in which the electric and magnetic surface polarization densities are computed. In particular, the average $\langle \cdot \rangle$ is calculated over the unit cells in the vicinity of the unit cell being considered and where the electric and magnetic surfaces polarization densities are evaluated. The polarizability dyadics depend on the physics and EM properties of the unit cells. As far as the present paper is concerned, it is sufficient to know that they can be obtained from analysis, simulations, or measurements. \textbf{Relating local (microscopic) fields to average (macroscopic) fields}. Based on \eqref{Eq_PolarizationMicro__P} and \eqref{Eq_PolarizationMicro__M}, the electric and magnetic surface polarization densities can be formulated in terms of the acting electric (${{\bf{E}}_{{\rm{act}}}}\left( {x,y} \right)$) and magnetic (${{\bf{H}}_{{\rm{act}}}}\left( {x,y} \right)$) fields at the position of a given unit cell. By definition, the acting fields can be formulated as follows \cite{Holloway_Oct2003}: \begin{equation} \label{Eq_ActingField} \begin{split} & {{\bf{E}}_{{\rm{act}}}}\left( {x,y} \right) = {{\bf{E}}_{{\rm{av}}}}\left( {x,y} \right) - {\bf{E}}_{{\rm{scattering}}}^{{\rm{unit \; cell}}}\left( {x,y} \right)\\ & {{\bf{H}}_{{\rm{act}}}}\left( {x,y} \right) = {{\bf{H}}_{{\rm{av}}}}\left( {x,y} \right) - {\bf{H}}_{{\rm{scattering}}}^{{\rm{unit \; cell}}}\left( {x,y} \right) \end{split} \end{equation} \noindent where ${{\bf{E}}_{{\rm{av}}}}\left( {x,y} \right)$ and ${{\bf{H}}_{{\rm{av}}}}\left( {x,y} \right)$ are the average electric and magnetic fields, respectively, at the two sides of the metasurface, which are defined as follows: \begin{equation} \label{Eq_AverageField} \begin{split} & {E_{{\rm{av}},u}}\left( {x,y} \right) = \frac{{E_u^t\left( {x,y} \right) + \left( {E_u^i\left( {x,y} \right) + E_u^r\left( {x,y} \right)} \right)}}{2}\\ & {H_{{\rm{av}},u}}\left( {x,y} \right) = \frac{{H_u^t\left( {x,y} \right) + \left( {H_u^i\left( {x,y} \right) + H_u^r\left( {x,y} \right)} \right)}}{2} \end{split} \end{equation} \noindent where $u = \left\{ {x,y,z} \right\}$, and ${\bf{E}}_{{\rm{scattering}}}^{{\rm{unit \; cell}}}\left( {x,y} \right)$ and ${\bf{H}}_{{\rm{scattering}}}^{{\rm{unit \; cell}}}\left( {x,y} \right)$ are the electric and magnetic fields scattered by the single unit cell under consideration, respectively. \textbf{Contribution of a single unit cell}. In practice, the contribution of a single unit cell can be calculated by expressing the unit cell as a combination of electric and magnetic dipoles that are contained within a small disk of a given radius. The electric and magnetic fields scattered by the resulting small disk are, by definition, ${\bf{E}}_{{\rm{scattering}}}^{{\rm{unit \; cell}}}\left( {x,y} \right)$ and ${\bf{H}}_{{\rm{scattering}}}^{{\rm{unit \; cell}}}\left( {x,y} \right)$. \textbf{Surface-averaged fields}. It is worth emphasizing that \eqref{Eq_ActingField} relates local, hence microscopic, fields to average, hence macroscopic, fields. More specifically, ${{\bf{E}}_{{\rm{av}}}}\left( {x,y} \right)$ and ${{\bf{H}}_{{\rm{av}}}}\left( {x,y} \right)$ in \eqref{Eq_AverageField} are surface-averaged fields, where the average is computed over a small surface area of the order of the wavelength (including one or more unit cells depending on the setup). In other words, the rapid variations of the EM fields over distances of the order of the typical separation between adjacent unit cells along the surface are eliminated (i.e., averaged out) in macroscopic EM fields. This is not the case for microscopic EM fields. \textbf{The need for a macroscopic representation}. By inserting \eqref{Eq_PolarizationMicro__P} and \eqref{Eq_PolarizationMicro__M} into \eqref{Eq_GSTCs}, one can obtain the analytical relations between the transverse components of the electric and magnetic fields at the two sides of a metasurface. The issue with this approach is that the acting electric and magnetic fields need to be estimated, which depend on a specific unit cell, i.e., ${\bf{E}}_{{\rm{scattering}}}^{{\rm{unit \; cell}}}\left( {x,y} \right)$ and ${\bf{H}}_{{\rm{scattering}}}^{{\rm{unit \; cell}}}\left( {x,y} \right)$, and may not be easy to deal with. This issue is overcome next, by introducing an explicit macroscopic description of a metasurface, which depends only on the average (macroscopic) fields. \subsubsection{Macroscopic Description of a Metasurface} \textbf{Explicit macroscopic formulation}. In \cite{Holloway_Oct2003}, the authors succeed in calculating a closed-form expression for ${\bf{E}}_{{\rm{scattering}}}^{{\rm{unit \; cell}}}\left( {x,y} \right)$ and ${\bf{H}}_{{\rm{scattering}}}^{{\rm{unit \; cell}}}\left( {x,y} \right)$. Based on their analytical formulation, the electric and magnetic surface polarization densities in \eqref{Eq_PolarizationMicro__P} and \eqref{Eq_PolarizationMicro__M} can be formulated in terms of the average electric and magnetic fields in \eqref{Eq_AverageField}, which, in contrast with the acting fields, yield a macroscopic description of a metasurface that is viewed as an electromagnetic discontinuity in space. This is because the average fields do not exclude the fields generated by individual unit cells. \textbf{Surface-averaged susceptibility functions: The effective parameters of metasurfaces}. More specifically, a macroscopic description of a metasurface, which depends only on average (macroscopic) electric and magnetic fields, can be obtained by formulating the electric and magnetic surface polarization densities in terms of \textit{susceptibility tensors} rather than in terms of polarizabilities. Similar to the average fields, the susceptibility tensors are macroscopic surface-averaged parameters. They can can be viewed as the effective parameters of metasurfaces, in analogy with the electric permittivity and magnetic permeability of volumetric metamaterials, and they depend on the topology and geometry of the unit cells, the inter-distance among the unit cells, the properties of the material, and the wavelength. In particular, the following relations hold true \cite{Caloz_GSTCs2015}: \begin{equation} \label{Eq_PolarizationMacro__P} \begin{split} {\bf{P}}\left( {x,y} \right) &= \varepsilon {\overline{\overline \chi } _{{\rm{ee}}}}\left( {x,y} \right){{\bf{E}}_{{\rm{av}}}}\left( {x,y} \right) \\ & + \sqrt {\mu \varepsilon } {\overline{\overline \chi } _{{\rm{em}}}}\left( {x,y} \right){{\bf{H}}_{{\rm{av}}}}\left( {x,y} \right) \end{split} \end{equation} \begin{equation} \label{Eq_PolarizationMacro__M} \begin{split} {\bf{M}}\left( {x,y} \right) &= \sqrt {{\varepsilon \mathord{\left/ {\vphantom {\varepsilon \mu }} \right. \kern-\nulldelimiterspace} \mu }} {\overline{\overline \chi } _{{\rm{me}}}}\left( {x,y} \right){{\bf{E}}_{{\rm{av}}}}\left( {x,y} \right) \\& + {\overline{\overline \chi } _{{\rm{mm}}}}\left( {x,y} \right){{\bf{H}}_{{\rm{av}}}}\left( {x,y} \right) \end{split} \end{equation} \noindent where ${\overline{\overline \chi } _{{\rm{ab}}}}\left( {x,y} \right)$, for $a = \left\{ {\rm{e},\rm{m}} \right\}$ and $b = \left\{ {\rm{e},\rm{m}} \right\}$, are the (electric-electric, electric-magnetic, magnetic-electric, and magnetic-magnetic) surface-averaged (or simply surface) susceptibility dyadics, which are the macroscopic quantities of interest for a simple but accurate synthesis and analysis of metasurfaces. \textbf{GSTCs: A macroscopic algebraic formulation}. With the aid of the analytical formulation of the electric and magnetic surface polarization densities as a function of only macroscopic fields and surface susceptibility dyadics, one can obtain an explicit analytical (algebraic) formulation of the GSTCs. More specifically, by inserting \eqref{Eq_PolarizationMacro__P} and \eqref{Eq_PolarizationMacro__M} into \eqref{Eq_GSTCs}, the following explicit relation can be obtained (for ease of notation, the dependency on $\left( {x,y} \right)$ for all fields and susceptibility dyadics is explicitly omitted but implied): \begin{equation} \label{Eq_GSTCs_Explicit_H} \begin{split} & \left[ {\begin{array}{*{20}{c}} { - H_y^t + H_y^i + H_y^r}\\ {H_x^t - H_x^i - H_x^r} \end{array}} \right]\\ & \hspace{1cm} = \frac{{j\omega \varepsilon }}{2}\left[ {\begin{array}{*{20}{c}} {\chi _{{\rm{ee}}}^{xx}}&{\chi _{{\rm{ee}}}^{xy}}\\ {\chi _{{\rm{ee}}}^{yx}}&{\chi _{{\rm{ee}}}^{yy}} \end{array}} \right]\left[ {\begin{array}{*{20}{c}} {E_x^t + E_x^i + E_x^r}\\ {E_y^t + E_y^i + E_y^r} \end{array}} \right]\\ & \hspace{1cm} + \frac{{j\omega \sqrt {\mu \varepsilon } }}{2}\left[ {\begin{array}{*{20}{c}} {\chi _{{\rm{em}}}^{xx}}&{\chi _{{\rm{em}}}^{xy}}\\ {\chi _{{\rm{em}}}^{yx}}&{\chi _{{\rm{em}}}^{yy}} \end{array}} \right]\left[ {\begin{array}{*{20}{c}} {H_x^t + H_x^i + H_x^r}\\ {H_y^t + H_y^i + H_y^r} \end{array}} \right] \end{split} \end{equation} \begin{equation} \label{Eq_GSTCs_Explicit_E} \begin{split} & \left[ {\begin{array}{*{20}{c}} {E_y^t - E_y^i - E_y^r}\\ { - E_x^t + E_x^i + E_x^r} \end{array}} \right]\\ & \hspace{1cm} = \frac{{j\omega \mu }}{2}\left[ {\begin{array}{*{20}{c}} {\chi _{{\rm{mm}}}^{xx}}&{\chi _{{\rm{mm}}}^{xy}}\\ {\chi _{{\rm{mm}}}^{yx}}&{\chi _{{\rm{mm}}}^{yy}} \end{array}} \right]\left[ {\begin{array}{*{20}{c}} {H_x^t + H_x^i + H_x^r}\\ {H_y^t + H_y^i + H_y^r} \end{array}} \right]\\ & \hspace{1cm} + \frac{{j\omega \sqrt {\mu \varepsilon } }}{2}\left[ {\begin{array}{*{20}{c}} {\chi _{{\rm{me}}}^{xx}}&{\chi _{{\rm{me}}}^{xy}}\\ {\chi _{{\rm{me}}}^{yx}}&{\chi _{{\rm{me}}}^{yy}} \end{array}} \right]\left[ {\begin{array}{*{20}{c}} {E_x^t + E_x^i + E_x^r}\\ {E_y^t + E_y^i + E_y^r} \end{array}} \right] \end{split} \end{equation} \noindent where, for $a = \left\{ {\rm{e},\rm{m}} \right\}$ and $b = \left\{ {\rm{e},\rm{m}} \right\}$, we have introduced the notation: \begin{equation} \label{Eq_SusceptibilityMatrix} {\overline{\overline \chi } _{{\rm{ab}}}}\left( {x,y} \right) = \left[ {\begin{array}{*{20}{c}} {\chi _{{\rm{ab}}}^{xx}\left( {x,y} \right)}&{\chi _{{\rm{ab}}}^{xy}\left( {x,y} \right)}\\ {\chi _{{\rm{ab}}}^{yx}\left( {x,y} \right)}&{\chi _{{\rm{ab}}}^{yy}\left( {x,y} \right)} \end{array}} \right] \end{equation} \textbf{GSTCs: A mathematical tool for analysis and synthesis}. The analytical expressions in \eqref{Eq_GSTCs_Explicit_H} and \eqref{Eq_GSTCs_Explicit_E} provide one with the necessary equations for designing metasurfaces, which are capable of applying specified transformations to the impinging radio waves, and for analyzing the performance of wireless networks in the presence of metasurfaces. These two important issues are discussed in the next two sub-sections. Before tackling them, we close this sub-section by emphasizing four important properties of the constitutive relations in \eqref{Eq_GSTCs_Explicit_H} and \eqref{Eq_GSTCs_Explicit_E}: (i) the constitutive relations are formulated only in terms of macroscopic surface-averaged EM fields and macroscopic surface-averaged effective parameters; (ii) the analysis of the surface-averaged susceptibility functions allows one to understand whether the metasurface is locally lossy, i.e., their imaginary part is always negative, or whether some local gains are needed, i.e., their imaginary part takes positive values; (iii) even though the constitutive relations offer a macroscopic description of a metasurface, they inherently account for the mutual coupling among the unit cells, since they originate from a microscopic description of a metasurface. In particular, the mutual coupling between adjacent unit cells is implicitly taken into account in the surface-averaged susceptibility matrices in \eqref{Eq_SusceptibilityMatrix}. This point will be further clarified in the next sub-section; and (iv) the constitutive relations in \eqref{Eq_GSTCs_Explicit_H} and \eqref{Eq_GSTCs_Explicit_E} can be applied to formulate the EM response of a metasurface to arbitrary (in terms of wavefront, incidence angle, and polarization) impinging EM waves. This implies that \eqref{Eq_GSTCs_Explicit_H} and \eqref{Eq_GSTCs_Explicit_E} do not assume that the impinging EM fields are plane waves. It is necessary, however, that the incident EM fields do not change significantly over the scale of one unit cell. This condition is usually fulfilled in metasurface structures whose unit cells have sub-wavelength inter-distances and sub-wavelength sizes. \textbf{Main takeaway}. In summary, the main takeaway message is that, from an analytical point of view, a metasurface can be approximately replaced by its corresponding constitutive relations in \eqref{Eq_GSTCs_Explicit_H} and \eqref{Eq_GSTCs_Explicit_E}, which are sufficient for the analysis and design of wireless networks (see Fig. \ref{Fig_13}). \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_SurfaceImpedances.pdf} \caption{Homogenization modeling of a metasurface based on surface-averaged impedances (reproduced from \cite{Book_SurfaceElectromagnetics}).} \label{Fig_SurfaceImpedances} \end{centering} \end{figure} \textbf{Equivalent representation in terms of surface-averaged impedances}. An alternative homogenization model for a metasurface can be obtained by establishing an analogy between the propagation of radio waves in vacuum and the propagation of signals in transmission lines \cite[Chapter 2]{Book_SurfaceElectromagnetics}. In this analogy, more precisely, the electric and magnetic fields of a radio wave that propagates in vacuum are matched to the voltages and currents of a signal that propagates in an equivalent transmission line, respectively. The impedances that determine the equivalent transmission line constitute a macroscopic surface-averaged representation of a metasurface, which is equivalent to the representation of a metasurface in terms of surface-averaged susceptibility functions. An example of representation of a metasurface in terms of transmission line equivalent is reported in Fig. \ref{Fig_SurfaceImpedances}, which is reproduced from \cite[Chapter 2]{Book_SurfaceElectromagnetics}. The T-circuit transmission line in Fig. \ref{Fig_SurfaceImpedances} ensures, in particular, that there exist ``jumps'' (discontinuities) of both the electric and magnetic fields, i.e., the voltages and currents represented in the figure, in agreement with the GSTCs in \eqref{Eq_GSTCs}. By applying Kirchhoff's circuit laws to the equivalent transmission line representation of the metasurface, and by inserting the resulting equations in \eqref{Eq_GSTCs_Explicit_H} and \eqref{Eq_GSTCs_Explicit_E}, one can compute analytical relations between the surface-averaged susceptibility functions and the surface-averaged impedances of the transmission line equivalent in Fig. \ref{Fig_SurfaceImpedances}. An example of this computation and an explicit relation between the two representations for a metasurface can be found in \cite[Appendix]{ComputationImpedances}. The homogenization model formulated in terms of surface-averaged impedances provides one with useful engineering insights on the properties of a metasurface structure. For example, a metasurface is capacitive and inductive if the imaginary part of the impedances is negative and positive, respectively, and a metasurface is lossy and active if the real part of the impedances is positive and negative, respectively. As remarked in \cite{ComputationImpedances}, more in general, a representation of a metasurface in terms of circuital parameters, i.e., surface-averaged impedances, may be potentially more useful to engineering-oriented communities, while a representation of a metasurface in terms of surface-averaged susceptibility functions may be more widely used in physics-oriented communities. Both representations are, however, homogenized, macroscopic, and equivalent with each other. An example of application of the homogenized modeling of metasurfaces based on surface-averaged impedances is given in the next sub-section. \subsubsection{Synthesis of a Metasurface} \textbf{How to build my own metasurface}? The synthesis of a metasurface corresponds to the following problem formulation: \textit{Given some specified radio wave transformations, i.e., the incident, reflected, and transmitted electric and magnetic fields are known, identify the corresponding susceptibility matrices in \eqref{Eq_SusceptibilityMatrix} that realize them, and then map the susceptibility matrices into physical structures that are made of specific arrangements of unit cells}. Therefore, this is a two-part design problem. We elaborate the details of both sub-problems in this sub-section, first in general terms and then with the aid of an example that elucidates some important details. \\ \noindent \underline{\textbf{\textit{Computation of susceptibility functions}}}. Given $E_v^{\xi}(x,y)$ and $H_v^{\xi}(x,y)$ for $v = \left\{ x,y \right\}$ and $\xi = \left\{ i,r,t \right\}$, the surface susceptibility functions in \eqref{Eq_SusceptibilityMatrix} can be obtained by solving the two systems of intertwined equations in \eqref{Eq_GSTCs_Explicit_H} and \eqref{Eq_GSTCs_Explicit_E}. \textbf{An undetermined system of equations}. The combined system of \eqref{Eq_GSTCs_Explicit_H} and \eqref{Eq_GSTCs_Explicit_E} is constituted by four equations and sixteen unknowns. Therefore, it is an undetermined system of equations that admits, in general, an infinite number of solutions. In practical terms, this implies that there exist many different combinations of surface susceptibility functions in \eqref{Eq_SusceptibilityMatrix} that realize the same transformations of the incident electric and magnetic fields into the reflected and transmitted electric and magnetic fields. A simple approach for overcoming the undetermined nature of the system of equations in \eqref{Eq_GSTCs_Explicit_H} and \eqref{Eq_GSTCs_Explicit_E} is to reduce to four the number of independent surface susceptibility functions in \eqref{Eq_SusceptibilityMatrix}. For example, some of them may be set equal to zero, provided that the resulting metasurface admits a physical structure that can be realized in practice. \textbf{A simple example}. To better understand, let us consider the case study in which the constraints ${\overline{\overline \chi } _{{\rm{em}}}}\left( {x,y} \right) = {\overline{\overline \chi } _{{\rm{me}}}}\left( {x,y} \right) = 0$ and $\chi _{{\rm{ee}}}^{xy}\left( {x,y} \right) = 0$, $\chi _{{\rm{ee}}}^{yx}\left( {x,y} \right) = 0$, $\chi _{{\rm{mm}}}^{xy}\left( {x,y} \right) = 0$, $\chi _{{\rm{mm}}}^{yx}\left( {x,y} \right) = 0$ are imposed to the surface susceptibility functions. From a physical standpoint, this implies that the metasurface structure is monoanisotropic (i.e., its physical properties exhibit variations along one direction) and uniaxial (i.e., it has a single direction of symmetry), and, therefore, it is reciprocal. Under these assumptions, the following analytical expressions for the remaining surface susceptibility functions can be obtained from \eqref{Eq_GSTCs_Explicit_H} and \eqref{Eq_GSTCs_Explicit_E}: \begin{equation} \label{Eq_SusceptibilityExample} \begin{split} & \chi _{{\rm{ee}}}^{xx}\left( {x,y} \right) = - \frac{2}{{j\omega \varepsilon }}\frac{{H_y^t\left( {x,y} \right) - H_y^i\left( {x,y} \right) - H_y^r\left( {x,y} \right)}}{{E_x^t\left( {x,y} \right) + E_x^i\left( {x,y} \right) + E_x^r\left( {x,y} \right)}}\end{split} \end{equation} \begin{equation} \nonumber \begin{split} & \chi _{{\rm{ee}}}^{yy}\left( {x,y} \right) = \frac{2}{{j\omega \varepsilon }}\frac{{H_x^t\left( {x,y} \right) - H_x^i\left( {x,y} \right) - H_x^r\left( {x,y} \right)}}{{E_y^t\left( {x,y} \right) + E_y^i\left( {x,y} \right) + E_y^r\left( {x,y} \right)}}\\ & \chi _{{\rm{mm}}}^{xx}\left( {x,y} \right) = \frac{2}{{j\omega \mu }}\frac{{E_y^t\left( {x,y} \right) - E_y^i\left( {x,y} \right) - E_y^r\left( {x,y} \right)}}{{H_x^t\left( {x,y} \right) + H_x^i\left( {x,y} \right) + H_x^r\left( {x,y} \right)}}\\ & \chi _{{\rm{mm}}}^{yy}\left( {x,y} \right) = - \frac{2}{{j\omega \mu }}\frac{{E_x^t\left( {x,y} \right) - E_x^i\left( {x,y} \right) - E_x^r\left( {x,y} \right)}}{{H_y^t\left( {x,y} \right) + H_y^i\left( {x,y} \right) + H_y^r\left( {x,y} \right)}} \end{split} \end{equation} \textbf{The case of perfect anomalous reflection}. Given the explicit expressions of the incident, reflected, and transmitted fields, \eqref{Eq_SusceptibilityExample} yields a metasurface that can realize both anomalous reflection and anomalous transmission. If, for example, perfect reflection is of interest, i.e., $E_x^t\left( {x,y} \right) = E_y^t\left( {x,y} \right) = 0$ and $H_x^t\left( {x,y} \right) = H_y^t\left( {x,y} \right) = 0$, then one obtains $\chi _{{\rm{ee}}}^{xx}\left( {x,y} \right)\chi _{{\rm{mm}}}^{yy}\left( {x,y} \right) = - {4 \mathord{\left/ {\vphantom {4 {{k^2}}}} \right. \kern-\nulldelimiterspace} {{k^2}}}$ and $\chi _{{\rm{ee}}}^{yy}\left( {x,y} \right)\chi _{{\rm{mm}}}^{xx}\left( {x,y} \right) = - {4 \mathord{\left/ {\vphantom {4 {{k^2}}}} \right. \kern-\nulldelimiterspace} {{k^2}}}$, where $k = \omega \sqrt {\mu \varepsilon }$. If a perfect reflector needs to be realized, therefore, only one independent surface susceptibility function is needed. This case study is elaborated in more detail in further text. \\ \noindent \underline{\textbf{\textit{Realization of physical lattices of unit cells}}}. Once the analytical expressions of the surface susceptibility functions are obtained, e.g., the formulas in \eqref{Eq_SusceptibilityExample}, the next step is to map these functions into a physical structure of unit cells that can be realized and manufactured. This latter step is, in particular, the most difficult one to implement. \textbf{Periodicity of a metasurface}. Before introducing the corresponding procedure, it is worth mentioning that the surface susceptibility functions that are obtained from \eqref{Eq_GSTCs_Explicit_H} and \eqref{Eq_GSTCs_Explicit_E} may or may not be periodic functions in $\left( {x,y} \right)$. If they are periodic functions, the periodicity of a metasurface coincides with the period of the surface susceptibility functions, which is usually expressed in terms of number of wavelengths. If the incident, reflected, and transmitted radio waves are plane waves, for example, the surface susceptibility functions are periodic functions in $\left( {x,y} \right)$. If more advanced functionalities are needed, e.g., focusing, aperiodical metasurfaces are usually needed, and the corresponding surface susceptibility functions are not periodic functions $\left( {x,y} \right)$. As far as periodic metasurfaces are concerned, it is worth mentioning that the period of the surface susceptibility functions is usually greater than the wavelength. The periodic feature of the surface susceptibility functions is clarified in further text with an example. In the rest of the present paper, for simplicity, we will assume that the surface susceptibility functions are periodic functions in $\left( {x,y} \right)$. \textbf{Step-by-step procedure}. The procedure that is usually adopted for mapping the surface susceptibility functions into metasurface structures can be summarized, in general terms, as follows \cite{CalozSergei_Mar2018}. \begin{enumerate} \item \textbf{Identifying the super-cell}. The continuous surface susceptibility functions are discretized (or sampled) in unit cells whose size and inter-distance are sub-wavelength. Thanks to the periodic nature of the surface susceptibility functions, this operation is executed for a single period. The discretization is performed by ensuring that a sufficient number of unit cells per period is obtained in agreement with the Nyquist theorem. This step yields the discretized version of \eqref{Eq_SusceptibilityMatrix}, i.e., ${\overline{\overline \chi } _{{\rm{ab}}}}\left( {{x_p},{y_q}} \right)$, for $p=1,2,\ldots,N_p$ and $q=1,2,\ldots,N_q$, where $N_p$ and $N_q$ are the numbers of unit cells, in one period, along the $x$-axis and $y$-axis, respectively. The obtained $N_p \times N_q$ unit cells correspond to the \textit{super-cell} depicted in Fig. \ref{Fig_4}. We anticipate that the entire metasurface is obtained as the periodic repetition of the super-cell structure. \item \textbf{Optimizing the super-cell}. Once the super-cell structure made of $N_p \times N_q$ unit cells is identified, the geometry of each unit cell of the super-cell needs to be optimized. In general, in fact, the unit cells of the super-cell may have a different geometry (size and shape). This optimization is executed by using a full-wave simulator that allows one to solve Maxwell's equations numerically. In general, this implies that the $N_p \times N_q$ unit cells of the super-cell are \textit{jointly optimized} in this step. To perform this optimization by using a full-wave simulator, first a generic structure and geometry for the unit cell are selected. This choice takes into account the fact that the structure and geometry of the unit cells need to be appropriate in order to synthesize the entire phase and amplitude range of the discretized surface susceptibility functions. In \cite{CalozSergei_Mar2018}, for example, the authors employ a dog-bone-shaped geometry for the generic unit cell, which has four optimization parameters ($G$, $L$, $S$, $W$), as depicted in Fig. \ref{Fig_14}. In \cite{CalozSergei_Mar2018}, the super-cell is constituted by $N_p \times N_q$ unit cells that are all dog-bone-shaped. Each unit cell of the super-cell is, however, characterized by a different quadruplet of parameters ($G$, $L$, $S$, $W$). \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_14.pdf} \caption{Dog-bone-shaped unit cell and super-cell structure (example and illustration are reproduced from \cite{CalozSergei_Mar2018}).} \label{Fig_14} \end{centering} \end{figure} \item \textbf{Metasurfaces: A periodic repetition of super-cells}. Finally, as anticipated, the metasurface is obtained as the periodic repetition of the optimized super-cell structure. This is allowed thanks to the periodicity of the surface susceptibility functions, provided that the super-cell is appropriately defined by taking the exact period into account. \end{enumerate} \textbf{Rationale behind the super-cell structure}. As far as the optimization of the structure and geometry of the super-cell (the above-mentioned second step) is concerned, three remarks are dutiful. \begin{itemize} \item \textit{\textbf{Periodic boundary conditions}}. The optimization of the geometry and structure of the entire super-cell is executed by enforcing \textit{periodic boundary conditions} in a full-wave simulator. This is a plausible choice thanks to the periodicity of the surface susceptibility functions, whose period is, by design, entirely covered by the super-cell. More specifically, the super-cell constitutes the so-called representative surface (or, in general, volume) element of the periodic structure that determines a metasurface. Therefore, it is sufficient, under periodic boundary conditions, to account for the behavior of the entire metasurface. It is important to mention, however, that this approximation is appropriate if the size of the metasurface is large as compared with the wavelength of the radio waves and if the area of the surface contains many periods. With this approximation, in particular, edge effects are ignored. \item \textit{\textbf{Mutual (spatial) coupling}}. The joint optimization of the $N_p \times N_q$ unit cells of the super-cell and the application of the periodic boundary conditions when solving Maxwell's equations with a full-wave simulator allow one to effectively account for the mutual coupling among the unit cells. The mutual coupling is, in fact, needed in order to synthesize, in practice, the desired discretized surface susceptibility functions. The resulting structure of the metasurface is locally aperiodic, since it is made of different adjacent unit cells, but the the super-cell structure enforces the required periodicity across the entire metasurface. \item \textit{\textbf{Efficient optimization}}. The joint optimization of the unit cells of the super-cell may not be computationally affordable. For example, a super-cell with only ten unit cells, each of which has four parameters to be optimized, necessitates the joint optimization of forty variables. To circumvent this issue and to efficiently design metasurfaces of practical use, iterative and often sub-optimal methods may be employed. For example, one may first optimize the geometry and size of each unit cell of the super-cell individually, by enforcing periodic boundary conditions to each unit cell. Since a single unit cell does not cover an entire period of the surface susceptibility functions, the resulting design is an approximation. The obtained sub-optimal design may, however, be subsequently used as the starting point for jointly optimizing all the unit cells of the super-cell. For example, one may iteratively optimize one unit cell by keeping the others fixed, and then iterate the procedure until convergence (under some error tolerance). \end{itemize} \textbf{The mutual coupling among the unit cells is taken into account by design}. The actual realization of a metasurface into a physical lattice of unit cells may not necessarily be the main objective of researchers working in wireless communications. It is, however, constructive to be aware of and to understand the general procedure employed by researchers working on the actual implementation of metasurfaces, in order to appreciate the fact that the mutual coupling among local neighbors of unit cells is taken into account by design through the periodic repetition of super-cells and the periodic nature of the surface susceptibility functions. \\ \noindent \underline{\textbf{\textit{Constructive Example -- Perfect anomalous reflection}}}. In order to elucidate the procedures for the synthesis and analysis of a metasurface, we consider a single example that allows us to highlight some aspects that play an important role for the analysis and optimization of RIS-empowered wireless networks. \textbf{Setup and assumptions}. The chosen example corresponds to the design of a metasurface that realizes perfect anomalous reflection (zero transmission). For ease of description, in addition, the incident and reflected electric and magnetic fields are assumed to be transverse electric plane waves with an arbitrary angle of incidence and an arbitrary angle of reflection. \textbf{Transverse electric plane waves}. Under the assumption of transverse electric plane waves, the tangential electric and magnetic fields can be formulated as follows \cite{Holloway_Nov2005}: \begin{equation} \label{Eq_FullReflection_PlaneWave} \begin{split} & E_x^i\left( {x,y} \right) = E_x^r\left( {x,y} \right) = 0\\ & E_y^i\left( {x,y} \right) = \sqrt {{2 \eta P_0}} \exp \left( { - jk\sin \left( {{\theta _i}} \right)x} \right)\\ & E_y^r\left( {x,y} \right) = \sqrt {{2 \eta P_0}} {A_r}\exp \left( { - jk\sin \left( {{\theta _r}} \right)x} \right)\\ & H_x^i\left( {x,y} \right) = \left(\sqrt {{2P_0}/ {\eta}}\right)\cos \left( {{\theta _i}} \right)\exp \left( { - jk\sin \left( {{\theta _i}} \right)x} \right)\\ & H_x^r\left( {x,y} \right) = - \left(\sqrt {{2P_0}/ {\eta}} \right){A_r}\cos \left( {{\theta _r}} \right)\exp \left( { - jk\sin \left( {{\theta _r}} \right)x} \right)\\ & H_y^i\left( {x,y} \right) = H_y^r\left( {x,y} \right) = 0 \end{split} \end{equation} \noindent where: (i) $\eta = \sqrt {{\mu \mathord{\left/ {\vphantom {\mu \varepsilon }} \right. \kern-\nulldelimiterspace} \varepsilon }}$ is the intrinsic impedance in vacuum; (ii) $P_0$ is the average power density (i.e., the average power per unit area) of the incident EM field; (iii) $\theta_i$ and $\theta_r$ are the angles of incidence and reflection, respectively, with respect to the $z$-axis; and (iv) $A_r$ is the amplitude of the reflected radio wave, which is a scaling factor independent of $(x,y)$. For simplicity, $A_r$ is assumed to be a real positive number. The amplitude $A_r$ can be chosen according to different criteria. In the present paper, we focus our attention on setups for $A_r$ that account for the power flows (obtained from the Poynting vector) of the incident and reflected EM fields. This choice allows us to analyze the power efficiency of a metasurface, i.e., the amount of power that is reflected towards the desired direction given the amount of power that is incident from a given direction, and the design guidelines and constraints for engineering metasurfaces with high power efficiency. The details about the conditions for balancing the incident and reflected power flows are discussed in the next paragraphs. It is worth nothing that, given the assumption of transverse electric plane waves, the surface EM fields are independent of $y$, i.e., $E_y^i\left( {x,y} \right) = E_y^i\left( x \right)$, $E_y^r\left( {x,y} \right) = E_y^r\left( x \right)$, $H_x^i\left( {x,y} \right) = H_x^i\left( x \right)$, and $H_x^r\left( {x,y} \right) = H_x^r\left( x \right)$. \textbf{Benchmark EM fields transformation}. The analytical formulation of the EM fields in \eqref{Eq_FullReflection_PlaneWave} is referred to as \textit{benchmark} or \textit{desired} fields transformation, since it provides one with the ideal function that a perfect anomalous reflector is intended to realize: The metasurface transforms a single incident plane wave into a single reflected plane wave, without any spurious reflections or transmissions towards other (undesired) directions. The EM fields in \eqref{Eq_FullReflection_PlaneWave} constitute a theoretical tool that is used for the synthesis of a perfect anomalous reflector. In further text, we discuss different possibilities for representing the resulting metasurface structure, which are convenient to use in wireless communications and electromagnetics. \textbf{Surface susceptibility function}. Based on \eqref{Eq_SusceptibilityExample}, the metasurface structure that realizes the desired EM fields transformation can be obtained by an appropriate design of the surface susceptibility functions. Under the considered assumptions, in particular, a single surface susceptibility function needs to be studied, e.g., $\chi _{{\rm{ee}}}^{yy}\left( {x,y} \right)$, since the other surface susceptibility functions can be obtained from it. In particular, the following holds true: \begin{equation} \label{Eq_FullReflection_Susceptibility} \chi _{{\rm{ee}}}^{yy}\left( {x,y} \right) = - \frac{2}{{j\omega \varepsilon }}\frac{{H_x^i\left( {x,y} \right) + H_x^r\left( {x,y} \right)}}{{E_y^i\left( {x,y} \right) + E_y^r\left( {x,y} \right)}} \end{equation} \noindent where it is taken into account that zero transmission implies $E_x^t\left( {x,y} \right) = E_y^t\left( {x,y} \right) = 0$ and $H_x^t\left( {x,y} \right) = H_y^t\left( {x,y} \right) = 0$. \textbf{Explicit analytical formulation and period of a metasurface structure}. By inserting \eqref{Eq_FullReflection_PlaneWave} in \eqref{Eq_FullReflection_Susceptibility}, the surface susceptibility function can be formulated as follows: \begin{equation} \label{Eq_FullReflection_Susceptibility__ClosedFormReflection} \chi _{{\rm{ee}}}^{yy}\left( x \right) = \frac{{2j}}{k}\frac{{\cos \left( {{\theta _i}} \right) - {A_r}\cos \left( {{\theta _r}} \right)\Phi \left( x \right)}}{{1 + {A_r}\Phi \left( x \right)}} \end{equation} \noindent where $\Phi \left( x \right) = \exp \left( { - jk\left( {\sin \left( {{\theta _r}} \right) - \sin \left( {{\theta _i}} \right)} \right)x} \right)$ is a shorthand notation. By direct inspection of \eqref{Eq_FullReflection_Susceptibility__ClosedFormReflection}, we evince that $\chi _{{\rm{ee}}}^{yy}\left( x \right)$ is a periodic function in $x$, i.e., $\chi _{{\rm{ee}}}^{yy}\left( x \right) = \chi _{{\rm{ee}}}^{yy}\left( x + \Pi \right)$, where $\Pi$ is the period. In particular, the period is determined by the function $\Phi \left( x \right)$ and it is equal to: \begin{equation} \label{Eq_FullReflection_Period} \Pi = \frac{{2\pi }}{{k\left( {\sin \left( {{\theta _r}} \right) - \sin \left( {{\theta _i}} \right)} \right)}} \end{equation} It is worth mentioning that \eqref{Eq_FullReflection_Susceptibility__ClosedFormReflection} provides one with a general analytical representation of a metasurface structure that operates as a perfect anomalous reflector. The specific properties of the resulting metasurface, including its power efficiency and implementation complexity, highly depend on the particular choice of the parameter $A_r$. The impact of $A_r$ is elaborated in the next paragraphs. \textbf{Net power flow of the metasurface structure}. One of the main features of nearly-passive metasurfaces consists of being passive during the normal operation phase. This implies that the power flow entering the metasurface structure (incoming power flow) needs to be less than or equal to the power flow leaving the metasurface structure (outgoing power flow). The two power flows coincide if the metasurface structure has unitary power efficiency. Given the (desired) analytical formulation of the EM fields in \eqref{Eq_FullReflection_PlaneWave}, the balance between the incoming and outgoing power flows can be ensured by appropriately optimizing the parameter ${A_r}$. Since the metasurface structure is periodic, the net power flow can be formulated for a single period. More precisely, the net power flow, i.e. the sum of the incoming and outgoing power flows, per unit period of the metasurface structure can be obtained from the Poynting vector, as follows: \begin{equation} \label{Eq_PowerBudget__1} \begin{split} & {P_{{\rm{net}}}}\left( x \right) = - \left( {{1 \mathord{\left/ {\vphantom {1 2}} \right. \kern-\nulldelimiterspace} 2}} \right){\mathop{\rm Re}\nolimits} \left\{ {{E_\parallel }\left( x \right)H_\parallel ^*\left( x \right)} \right\}\\ & {P_{{\rm{net}}}} = \frac{1}{\Pi} \int\nolimits_0^\Pi {{P_{{\rm{net}}}}\left( x \right)dx} \end{split} \end{equation} \noindent where ${E_\parallel }\left( {x} \right) = {E_\parallel }\left( {x,y} \right) = E_y^i\left( {x,y} \right) + E_y^r\left( {x,y} \right)$ and ${H_\parallel }\left( {x} \right) = {H_\parallel }\left( {x,y} \right) = H_x^i\left( {x,y} \right) + H_x^r\left( {x,y} \right)$ are the tangential components of the electric and magnetic field, respectively. It is worth mentioning that it is sufficient to consider a single period because the size of a metasurface is usually set equal to an integer number of periods and the net power flow is usually normalized to the total size of the metasurface structure. By inserting \eqref{Eq_FullReflection_PlaneWave} in \eqref{Eq_PowerBudget__1}, and computing the resulting integral, we obtain the following expression: \begin{equation} \label{Eq_PowerBudget__2} \begin{split} &{P_{{\rm{net}}}}\left( x \right) = {P_0}A_r^2\cos \left( {{\theta _r}} \right) - {P_0}\cos \left( {{\theta _i}} \right)\\ & \hspace{1.15cm} + {P_0}{A_r}\left( {\cos \left( {{\theta _r}} \right) - \cos \left( {{\theta _i}} \right)} \right)\cos \left( {\phi \left( x \right)} \right)\\ & {P_{{\rm{net}}}} = {P_0}\left( {A_r^2\cos \left( {{\theta _r}} \right) - \cos \left( {{\theta _i}} \right)} \right) \end{split} \end{equation} \noindent where $\phi \left( x \right) = k\left( {\sin \left( {{\theta _r}} \right) - \sin \left( {{\theta _i}} \right)} \right)x$ is a shorthand notation. \textbf{Locally and globally passive metasurfaces}. The net power flow of a metasurface structure can be defined in a local and global sense. From a local standpoint, one is interested in analyzing the surface power flow ${P_{{\rm{net}}}}\left( x \right)$. From a global standpoint, on the other hand, one is interested in analyzing the integral power flow ${P_{{\rm{net}}}}$. More specifically, the local and global power flows in \eqref{Eq_PowerBudget__1} can be negative and positive. If they are negative, it implies that the incident power flow is greater than the reflected power flow. If they are positive, on the other hand, the opposite holds true. The physical meaning of negative and positive power flows can be understood by introducing the definition of locally and globally passive metasurfaces. A metasurface is defined to be locally passive if ${P_{{\rm{net}}}}\left( x \right) \le 0$ for every $x$. Likewise, a metasurface is defined to be globally passive if ${P_{{\rm{net}}}} \le 0$. It is worth mentioning that a locally non-passive metasurface, i.e., ${P_{{\rm{net}}}}\left( x \right) \ge 0$ for some $x$, can be globally passive, i.e., ${P_{{\rm{net}}}} \le 0$. This occurs if the metasurface is characterized by regions where there are power absorptions and regions where there are power gains that compensate each other along the entire metasurface structure. This concept is elaborated in further text, since it is instrumental for realizing metasurfaces with a high power efficiency. \textbf{Globally passive metasurfaces with unitary power efficiency}. By definition, globally passive metasurfaces with a unitary power efficiency, i.e., the total reflected power coincides with the total incident power, are obtained by imposing the constraint ${P_{{\rm{net}}}}=0$. From \eqref{Eq_PowerBudget__2}, this can be ensured if: \begin{equation} \label{Eq_Ar_1} {A_r} = \sqrt {\frac{{\cos \left( {{\theta _i}} \right)}}{{\cos \left( {{\theta _r}} \right)}}} \end{equation} In further text, the physical meaning that originates by imposing that a perfect anomalous reflector is globally passive by design is discussed. Furthermore, the design guidelines for engineering globally passive metasurface structures that realize perfect anomalous reflectors with unitary power efficiency are elaborated. It is worth nothing that, by setting $A_r$ as in \eqref{Eq_Ar_1}, ${P_{{\rm{net}}}}\left( x \right)$ in \eqref{Eq_PowerBudget__2} is not identically equal to zero for every $x$, but it is an oscillating function in $x$ that takes positive and negative values. This implies that a perfect anomalous reflector may, in general, exhibit absorptions and gains along the surface. It is interesting to note, however, that a perfect specular reflector, i.e., $\theta _r = \theta _i$, can be made locally and globally passive by setting $A_r=1$. In this case, in particular, the incident and reflected power flows coincide and the metasurface structure has a unitary power efficiency. \textbf{Surface-averaged reflection coefficient}. The EM fields in \eqref{Eq_FullReflection_PlaneWave} are necessary and sufficient (benchmark) equations for the synthesis of a metasurface structure with full-reflection capability, which is able of bending a radio wave from a generic direction $\theta_i$ towards a generic direction $\theta_r$. The corresponding surface-averaged susceptibility function is given in \eqref{Eq_FullReflection_Susceptibility__ClosedFormReflection}. In particular, \eqref{Eq_FullReflection_Susceptibility__ClosedFormReflection} is a convenient tool for the synthesis of a metasurface. Often, however, researchers are more used to characterize the properties of structures that behave as reflectors by using the concept of reflection coefficient. It is important to note that the definition of (surface-averaged) reflection coefficient is slightly different and serves for a different purpose in the context of wireless communications and in the context of metasurface design. More precisely, the following two definitions hold true. \begin{itemize} \item \textbf{\textit{Wireless design: Reflection coefficient based on surface EM fields}}. Let us consider that, departing from \eqref{Eq_FullReflection_Susceptibility__ClosedFormReflection}, one has designed and realized the corresponding metasurface structure by using the synthesis procedure described in previous sections. Wireless researchers are interested in introducing equivalent representations of metasurface structures that yield an explicit and direct relation between the incident and reflected radio waves. In this context, the reflection coefficient is defined as the ratio between the reflected electric field and the incident electric field. From an engineering standpoint, it can be viewed as a ``global'' response of the metasurface structure to some incident EM fields. As detailed in further text, this definition of reflection coefficient is useful for evaluating the performance of RIS-empowered wireless networks, since a direct link between incident and reflected EM fields is established. In the present paper, the reflection coefficient defined based on surface EM fields is denoted by ${R_{{\rm{EM}}}}\left( x,y \right) = {R_{{\rm{EM}}}}\left( x \right)$. \item \textbf{\textit{Metasurface design: Reflection coefficient based on surface impedances}}. Let us consider that, departing from \eqref{Eq_FullReflection_Susceptibility__ClosedFormReflection} (or its corresponding surface-averaged impedance, which is the reciprocal of \eqref{Eq_FullReflection_Susceptibility__ClosedFormReflection} in the considered example), one has to design and manufacture the corresponding metasurface structure that realizes the desired anomalous reflection. Metasurface scientists are interested in obtaining initial insights from \eqref{Eq_FullReflection_Susceptibility__ClosedFormReflection}, in order to identify appropriate physical structures that realize the desired functionality. Broadly speaking, the reflection coefficient based on surface EM fields that is usually employed in wireless communications provides one with information on ``what'' needs to be realized, but it does not yield design guidelines on ``how'' to realize it, which is, on the other hand, the main objective of the designers of metasurfaces. To this end, it is more useful to define the reflection coefficient as a parameter that quantifies how different the ``local'' response of a metasurface structure is as compared with a suitable reference. In the context of anomalous reflection, a suitable choice as a reference is a metasurface structure that behaves as a specular reflector. Therefore, the reflection coefficient is more conveniently defined as a parameter that quantifies the mismatch between the surface-averaged impedances of anomalous reflection and specular reflection \cite{Alu_Reflection2016}, \cite{Asadchy_2017}. This concept is detailed in further text. For clarity, we anticipate that the reflection coefficient based on surface impedances cannot be used to related the incident and reflected EM fields. It yields, however, fundamental information on the design of metasurfaces, e.g., how to realize a globally passive metasurface with unitary efficiency but without using active elements. In the present paper, the reflection coefficient defined based on surface impedances is denoted by ${R_{{\rm{Z}}}}\left( x,y \right) = {R_{{\rm{Z}}}}\left( x \right)$. \end{itemize} \textbf{Surface-averaged reflection coefficient: Unified notation}. An objective of the present paper is to analyze and compare against each other the two reflection coefficients ${R_{{\rm{EM}}}}\left( x \right)$ and ${R_{{\rm{Z}}}}\left( x \right)$. To this end, we adopt a unified notation that encompasses both definitions of reflection coefficient and that allows us to unveil the differences and similarities between ${R_{{\rm{EM}}}}\left( x \right)$ and ${R_{{\rm{Z}}}}\left( x \right)$. In the adopted unified notation, we depart from the EM fields in \eqref{Eq_FullReflection_PlaneWave}. We emphasize, once again, that ${R_{{\rm{Z}}}}\left( x \right)$ cannot be used, in general, to directly related the reflected and incident fields. The employed unified notation is, however, useful for unveiling the analytical relation between ${R_{{\rm{EM}}}}\left( x \right)$ and ${R_{{\rm{Z}}}}\left( x \right)$, and for explaining the physical meaning of ${R_{{\rm{Z}}}}\left( x \right)$. In particular, we introduce the following notation and mathematical definition for ${R_{{\rm{EM}}}}\left( x \right)$ and ${R_{{\rm{Z}}}}\left( x \right)$: \begin{equation} \label{Eq_FullReflection_LocalReflectionCoefficient} \begin{split} & E_y^r\left( {x,y} \right) = E_y^r\left( x \right) = R\left( x \right)E_y^i\left( x \right)\\ & H_x^r\left( {x,y} \right) = H_x^r\left( x \right) = - r_{i,r} R\left( x \right)H_x^i\left( x \right) \end{split} \end{equation} \noindent where: \begin{equation} \label{Eq_FullReflection_LocalReflectionCoefficient} {r_{i,r}} = \begin{cases} \frac{{\cos \left( {{\theta _r}} \right)}}{{\cos \left( {{\theta _i}} \right)}}\quad \quad \quad & {\rm{if}} \quad R\left( x \right) = {R_{{\rm{EM}}}}\left( x \right)\\ 1\quad \quad \quad & {\rm{if}} \quad R\left( x \right) = {R_{\rm{Z}}}\left( x \right) \end{cases} \end{equation} In the sequel, thanks to the unified definition in \eqref{Eq_FullReflection_LocalReflectionCoefficient}, the surface-averaged reflection coefficient is denoted by $R\left( x \right)$. \textbf{Reformulation of the EM fields}. As a function of the reflection coefficient in \eqref{Eq_FullReflection_LocalReflectionCoefficient}, the non-zero components of the electric and magnetic fields in \eqref{Eq_FullReflection_PlaneWave} can be written as follows: \begin{equation} \label{Eq_FullReflection_R} \begin{split} & E_y^i\left( {x} \right) = \sqrt {{2 \eta P_0}} \exp \left( { - jk\sin \left( {{\theta _i}} \right)x} \right)\\ & E_y^r\left( {x} \right) = \sqrt {{2 \eta P_0}} R\left( x \right)\exp \left( { - jk\sin \left( {{\theta _i}} \right)x} \right)\\ & H_x^i\left( {x} \right) = \sqrt {\frac{{2{P_0}}}{\eta }} \cos \left( {{\theta _i}} \right)\exp \left( { - jk\sin \left( {{\theta _i}} \right)x} \right)\\ & H_x^r\left( {x} \right) = - \sqrt {\frac{{2{P_0}}}{\eta }} \cos \left( {{\theta _i}} \right)r_{i,r}R\left( x \right)\exp \left( { - jk\sin \left( {{\theta _i}} \right)x} \right) \end{split} \end{equation} It is worth emphasizing that, in contrast with $A_r$ in \eqref{Eq_FullReflection_PlaneWave}, the surface-averaged reflection coefficient $R(x)$ depends on $x$. This is necessary because the reflected EM fields are expressed in terms of incident EM fields. This is consistent with the analytical formulation given in, e.g., \cite{Holloway_Nov2005}. \textbf{$\bf{R_{{\rm{\bf EM}}}}\left( x \right)$ and $\bf{R_{{\rm{\bf Z}}}}\left( x \right)$: Some initial remarks}. By direct inspection of \eqref{Eq_FullReflection_R}, some preliminary remarks can be made. \begin{itemize} \item \textbf{\textit{Reflected electric and magnetic fields}}. From \eqref{Eq_FullReflection_R}, we obtain the following identities: \begin{equation} \label{Comparing_ReflectionCoefficients__1} {R_{{\rm{EM}}}}\left( x \right) = \frac{{E_y^r\left( x \right)}}{{E_y^i\left( x \right)}} \ne - \frac{{H_y^r\left( x \right)}}{{H_y^i\left( x \right)}} \end{equation} \begin{equation} \label{Comparing_ReflectionCoefficients__2} {R_{\rm{Z}}}\left( x \right) = \frac{{E_y^r\left( x \right)}}{{E_y^i\left( x \right)}} = - \frac{{H_y^r\left( x \right)}}{{H_y^i\left( x \right)}} \end{equation} The identity in \eqref{Comparing_ReflectionCoefficients__1} is in agreement with the widely used definition of reflection coefficient as the ratio between the reflected electric field and the incident electric field. With the exception of the special case ${\cos \left( {{\theta _r}} \right) = \cos \left( {{\theta _i}} \right)}$, i.e., specular reflection, the same does not hold true for the corresponding magnetic fields. The identities in \eqref{Comparing_ReflectionCoefficients__2} are, on the other hand, in agreement with the typical definition of reflection coefficient that is employed in electric circuits, according to which the ratio of the reflected and incident voltages (i.e., the electric fields) is, except for a negative sign, equal to the ratio of the reflected and incident currents (i.e., the magnetic fields). \item \textbf{\textit{Impedances of incident and reflected EM fields}}. From \eqref{Eq_FullReflection_R}, we obtain the following identities: \begin{equation} \label{Comparing_ReflectionCoefficients__3} {Z_i} = \frac{{E_y^i\left( x \right)}}{{H_x^i\left( x \right)}} = \frac{\eta }{{\cos \left( {{\theta _i}} \right)}} \end{equation} \begin{equation} \label{Comparing_ReflectionCoefficients__4} {Z_r} = \frac{{E_y^r\left( x \right)}}{{H_x^r\left( x \right)}} = \begin{cases} - \frac{\eta }{{\cos \left( {{\theta _r}} \right)}}\quad & {\rm{if}}\; R\left( x \right) = {R_{{\rm{EM}}}}\left( x \right)\\ - \frac{\eta }{{\cos \left( {{\theta _i}} \right)}}\quad & {\rm{if}}\; R\left( x \right) = {R_{\rm{Z}}}\left( x \right) \end{cases} \end{equation} By leveraging the analogy of the electric and magnetic fields in vacuum with the voltages and currents in transmission lines, respectively, \eqref{Comparing_ReflectionCoefficients__3} and \eqref{Comparing_ReflectionCoefficients__4} give the impedances of the incident radio wave and the reflected radio wave, respectively. By viewing a metasurface as an equivalent electric circuit, \eqref{Comparing_ReflectionCoefficients__3} and \eqref{Comparing_ReflectionCoefficients__4} can be interpreted as the input and output impedance that is viewed by the radio wave entering and leaving the equivalent electric circuit, respectively. Based on the definition of ${{R_{{\rm{EM}}}}\left( x \right)}$, the input and output radio waves view two different impedances. Based on the definition of ${{R_{{\rm{Z}}}}\left( x \right)}$, the input and output radio waves view the same impedance. This is the main difference between the definitions of ${{R_{{\rm{EM}}}}\left( x \right)}$ and ${{R_{{\rm{Z}}}}\left( x \right)}$, which is elaborated in further text. \item \textbf{\textit{Explicit expression for $\bf{R_{{\rm{\bf EM}}}}\left( x \right)$}}. By direct inspection and comparison between \eqref{Eq_FullReflection_PlaneWave} and \eqref{Eq_FullReflection_R}, the following simple expression for ${{R_{{\rm{EM}}}}\left( x \right)}$ can be obtained: \begin{equation} \label{EM_ReflectionCoefficient} {R_{{\rm{EM}}}}\left( x \right) = {A_r}\exp \left( { - jk\left( {\sin \left( {{\theta _r}} \right) - \sin \left( {{\theta _i}} \right)} \right)x} \right) \end{equation} In the considered example of a perfect anomalous reflector, it is, therefore, not difficult to identify an explicit analytical expression for ${{R_{{\rm{EM}}}}\left( x \right)}$. This is, in general, not always the case. By analyzing ${{R_{{\rm{EM}}}}\left( x \right)}$ carefully, we observe that the metasurface structure introduces a phase shift that compensates the difference between the angles of incidence and reflection, as well as it scales the amplitude of the incident and reflected fields by a factor $A_r$. In the literature, it is usually assumed that $A_r = 1$ in order to ensure that the metasurfaces are passive \cite{MDR_OverheadAware}. This is necessary, however, only if one wishes that the metasurface structure is locally passive. In general, $A_r$ can be chosen according to different criteria, and it is, in general, dependent on the angles of incidence and reflection. Based on \eqref{Eq_Ar_1}, for example, this is obtained for a globally passive perfect anomalous reflector with a unitary power efficiency. If one is interested in smart surfaces that are realized through tiny discrete antenna elements, e.g., the RFocus prototype in Fig. \ref{Fig_2}, on the other hand, the concepts of locally and globally passive are (almost) the same, since advanced methods to realize non-locally passive but globally passive metasurfaces without using active elements may not be employed \cite{Asadchy_2017}. This concept is better elaborated in further text. At this point, it is sufficient to keep in mind that globally passive metasurfaces do not necessarily imply that the amplitude of the reflection coefficient ${{R_{{\rm{EM}}}}\left( x \right)}$, i.e., $A_r$ in \eqref{EM_ReflectionCoefficient}, is equal to or less than one. \end{itemize} \textbf{Relating the surface-averaged susceptibility function to the surface-averaged reflection coefficient}. In order to gain deeper understanding of and insight on the specific features of the perfect anomalous reflector under design, the first step consists of finding an explicit relation between the surface susceptibility function and the surface reflection coefficient $R(x)$. The analytical derivation, in particular, applies to ${R_{{\rm{EM}}}}\left( x \right)$ and ${R_{{\rm{Z}}}}\left( x \right)$. The analytical relation is obtained by inserting \eqref{Eq_FullReflection_R} in \eqref{Eq_FullReflection_Susceptibility}, which yields the following: \begin{equation} \label{Eq_FullReflection_Relation1} \chi _{{\rm{ee}}}^{yy}\left( {x,y} \right) = \chi _{{\rm{ee}}}^{yy}\left( x \right) = \frac{{2j}}{k}\cos \left( {{\theta _i}} \right)\frac{{1 - r_{i,j} R\left( x \right)}}{{1 + R\left( x \right)}} \end{equation} \noindent or, equivalently, the following: \begin{equation} \label{Eq_FullReflection_Relation2} R\left( x \right) = \frac{{1 + j\frac{k}{{2\cos \left( {{\theta _i}} \right)}}\chi _{{\rm{ee}}}^{yy}\left( x \right)}}{{r_{i,j} - j\frac{k}{{2\cos \left( {{\theta _i}} \right)}}\chi _{{\rm{ee}}}^{yy}\left( x \right)}} \end{equation} \textbf{Explicit formulation of the surface-averaged reflection coefficient}. An explicit, as a function of the angles of incidence and reflection, relation of the surface-averaged reflection coefficient $R(x)$ can be obtained by inserting \eqref{Eq_FullReflection_Susceptibility__ClosedFormReflection} in \eqref{Eq_FullReflection_Relation2}. The resulting analytical expression is the following: \begin{equation} \label{Eq_FullReflection_ExplicitFormulaReflection} \begin{split} & R\left( x \right) = \frac{{1 - \Gamma \left( x \right)}}{{r_{i,j} + \Gamma \left( x \right)}}\\ & \Gamma \left( x \right) = \frac{{\cos \left( {{\theta _i}} \right) - {A_r}\cos \left( {{\theta _r}} \right)\Phi \left( x \right)}}{{\cos \left( {{\theta _i}} \right)\left( {1 + {A_r}\Phi \left( x \right)} \right)}} \end{split} \end{equation} It is worth mentioning that $A_r$ in \eqref{Eq_FullReflection_ExplicitFormulaReflection} is an arbitrary coefficient that is not necessarily equal to \eqref{Eq_Ar_1}. In the next paragraphs, in particular, we discuss the impact of $A_r$ on the power efficiency and associated implementation complexity for realizing the resulting metasurface structure, e.g., if the structure is locally passive, globally passive, or if it requires specific (advanced) implementation designs. \textbf{Surface-averaged reflection coefficient: Net power flow and conditions for globally passive metasurfaces}. Similar to the analytical formulation for the transformations of the EM fields in \eqref{Eq_FullReflection_PlaneWave}, we are interested in computing the net power flow of a metasurface structure that is given by the analytical reformulation in \eqref{Eq_FullReflection_R}. Also, we are interested in formulating the conditions for ensuring that a metasurface structure is globally passive as a function of the surface-averaged reflection coefficient $R(x)$, and in comparing the two definitions of reflection coefficient ${R_{{\rm{EM}}}}\left( x \right)$ and ${R_{{\rm{Z}}}}\left( x \right)$. In detail, the net power flow can be computed by inserting the EM fields in \eqref{Eq_FullReflection_R} into \eqref{Eq_PowerBudget__1}, which yield the following analytical expressions: \begin{equation} \label{Eq_PowerBudget__3} \begin{split} & {P_{{\rm{net}}}}\left( x \right) = {P_0}\cos \left( {{\theta _i}} \right) \\ & \hspace{1.20cm} \times \left( {{{r_{i,j}\left| {R\left( x \right)} \right|}^2} - 1 - (1-r_{i,j}){\mathop{\rm Re}\nolimits} \left\{ {R\left( x \right)} \right\}} \right)\\ & {P_{{\rm{net}}}} = \frac{{{P_0}r_{i,j}\cos \left( {{\theta _i}} \right)}}{\Pi }\int\nolimits_0^\Pi {{{\left| {R\left( x \right)} \right|}^2}dx} - {P_0}\cos \left( {{\theta _i}} \right) \end{split} \end{equation} Once again, we observe that ${P_{{\rm{net}}}}\left( x \right)$ is, in general, an oscillating function in $x$, which, depending on the parameters, can be positive or negative, and it is not identically equal to zero. It is apparent from \eqref{Eq_PowerBudget__3} that the metasurface structure is locally passive if ${P_{{\rm{net}}}}\left( x \right) \le 0$ for every $x$. Likewise, the metasurface structure can be made globally passive with unitary power efficiency by imposing the design constraint ${P_{{\rm{net}}}} = 0$, which yields: \begin{equation} \label{Eq_PowerBudget__4} \frac{1}{\Pi }\int\nolimits_0^\Pi {{{\left| {R\left( x \right)} \right|}^2}dx} = \frac{1}{r_{i,j}} \end{equation} The difference between ${R_{{\rm{EM}}}}\left( x \right)$ and ${R_{{\rm{Z}}}}\left( x \right)$ can be understood by comparing them in terms of the net power flow given in \eqref{Eq_PowerBudget__3} and in terms of the condition in \eqref{Eq_PowerBudget__4} for the design of globally passive metasurfaces with unitary power efficiency. \textbf{Reflected EM fields and net power flow from $\bf{R_{{\rm{\bf EM}}}}\left( x \right)$}. In this case, $r_{i,j} = {{{\cos \left( {{\theta _r}} \right)} \mathord{\left/ {\vphantom {{\cos \left( {{\theta _r}} \right)} {\cos \left( {{\theta _i}} \right)}}} \right. \kern-\nulldelimiterspace} {\cos \left( {{\theta _i}} \right)}}}$. By inserting $r_{i,r}$ in \eqref{Eq_FullReflection_ExplicitFormulaReflection}, we obtain, as expected, \eqref{EM_ReflectionCoefficient}, since ${1 \mathord{\left/ {\vphantom {1 {{r_{i,j}} = A_r^2}}} \right. \kern-\nulldelimiterspace} {{r_{i,j}} = A_r^2}}$. Therefore, \eqref{Eq_PowerBudget__3} reduces to \eqref{Eq_PowerBudget__2} and \eqref{Eq_PowerBudget__4} is in agreement with \eqref{Eq_Ar_1}. This confirms that ${R_{{\rm{EM}}}}\left( x \right)$ is inherently suitable for applications to wireless communications, since its definition ensures that the reflected EM fields corresponds to physical fields that yield a power budget in agreement with the desired field transformations. \textbf{Reflected EM fields from $\bf{R_{{\rm{\bf Z}}}}\left( x \right)$}. In this case, $r_{i,j} = 1$. Under this setup, we obtain results that are not consistent with the analytical expression of the desired EM fields in \eqref{Eq_FullReflection_PlaneWave}. By inserting $r_{i,j} = 1$ in \eqref{Eq_FullReflection_ExplicitFormulaReflection}, in particular, the resulting reflection coefficient $R(x)={R_{{\rm{Z}}}}\left( x \right)$ would be the following: \begin{equation} \label{Eq_FieldsBack__R} {R_{\rm{Z}}}\left( x \right) = \frac{{{A_r}\left( {\cos \left( {{\theta _r}} \right) + \cos \left( {{\theta _i}} \right)} \right)\Phi \left( x \right)}}{{2\cos \left( {{\theta _i}} \right) - {A_r}\left( {\cos \left( {{\theta _r}} \right) - \cos \left( {{\theta _i}} \right)} \right)\Phi \left( x \right)}} \end{equation} By inserting \eqref{Eq_FieldsBack__R} in \eqref{Eq_FullReflection_R}, we evince that the resulting electric and magnetic reflected fields are different from the desired ones that are given in \eqref{Eq_FullReflection_PlaneWave}. In particular, the EM fields obtained from \eqref{Eq_FieldsBack__R} and \eqref{Eq_FullReflection_R} may not be a solution of Maxwell's equations either. We observe, notably, that ${R_{\rm{Z}}}\left( x \right) = {R_{\rm{EM}}}\left( x \right)$ only if $\theta _r=\theta _i$, i.e., if specular reflection is considered, as remarked in previous text already. \textbf{Net power flow from $\bf{R_{{\rm{\bf Z}}}}\left( x \right)$}. By inserting $r_{i,j} = 1$ in \eqref{Eq_FullReflection_ExplicitFormulaReflection} and by then plugging the resulting reflection coefficient in \eqref{Eq_PowerBudget__4}, in addition, we would obtain the following analytical condition for the design of a globally passive perfect anomalous reflector with unitary power efficiency: \begin{equation} \label{Eq_PowerBudget__5} {\left| {\frac{{{{\left( {1 - \frac{{\cos \left( {{\theta _r}} \right)}}{{\cos \left( {{\theta _i}} \right)}}} \right)}^2}}}{{{{\left( {1 + \frac{{\cos \left( {{\theta _r}} \right)}}{{\cos \left( {{\theta _i}} \right)}}} \right)}^2}}} - \frac{4}{{A_r^2{{\left( {1 + \frac{{\cos \left( {{\theta _r}} \right)}}{{\cos \left( {{\theta _i}} \right)}}} \right)}^2}}}} \right|^{ - 1}} = 1 \end{equation} The design constraint in \eqref{Eq_PowerBudget__5} could be guaranteed by appropriately optimizing the parameter $A_r$ in \eqref{Eq_FullReflection_ExplicitFormulaReflection}. In particular, by solving the equation in \eqref{Eq_PowerBudget__5} as a function of $A_r$, we would obtain the following: \begin{equation} \label{Eq_Ar_2} {A_r} = \sqrt {\frac{2}{{1 + {{\left( {{{\cos \left( {{\theta _i}} \right)} \mathord{\left/ {\vphantom {{\cos \left( {{\theta _i}} \right)} {\cos \left( {{\theta _r}} \right)}}} \right. \kern-\nulldelimiterspace} {\cos \left( {{\theta _r}} \right)}}} \right)}^2}}}} \end{equation} \textbf{$\bf{R_{{\rm{\bf EM}}}}\left( x \right)$ vs. $\bf{R_{{\rm{\bf Z}}}}\left( x \right)$: Comparison in terms of net power flow}. By comparing \eqref{Eq_Ar_2} with \eqref{Eq_Ar_1}, we evince that, in general, two different values for $A_r$ are obtained. The two values of $A_r$ coincide under the assumption of perfect specular reflection, i.e., $\theta _r = \theta _i$. In this case, in fact, both formulas simplify to $A_r=1$. If $r_{i,r}=1$, more in general, the net power flow in \eqref{Eq_PowerBudget__3} is different from the (benchmark) net power flow in \eqref{Eq_PowerBudget__2}. As an example, we can insert \eqref{Eq_Ar_1} in \eqref{Eq_PowerBudget__3} and \eqref{Eq_Ar_2} in \eqref{Eq_PowerBudget__2}, respectively, and can compute the two expressions of the corresponding net power flows. We denote the two resulting formulas by $P_{{\rm{net}}}^{\left( {{\rm{Z}}} \right)}$ and $P_{{\rm{net}}}^{\left( {{\rm{benchmark}}} \right)}$, respectively. It can be readily proved that $P_{{\rm{net}}}^{\left( {{\rm{Z}}} \right)} \ge 0$ and $P_{{\rm{net}}}^{\left( {{\rm{benchmark}}} \right)} \le 0$ for any angle of incidence and for any angle of reflection. In different terms, a metasurface structure that is expected to be globally passive and with unitary power efficiency under the desired field transformations in \eqref{Eq_FullReflection_PlaneWave}, i.e., by setting $A_r$ equal to \eqref{Eq_Ar_1}, turns out to be globally active if ${R_{{\rm{Z}}}}\left( x \right)$ is interpreted as a field reflection coefficient. \textbf{What is the role and meaning of $\bf{R_{{\rm{\bf Z}}}}\left( x \right)$}? The comparison between ${R_{{\rm{EM}}}}\left( x \right)$ and ${R_{{\rm{Z}}}}\left( x \right)$ allows us to conclude that ${R_{{\rm{Z}}}}\left( x \right)$ cannot be employed as a field reflection coefficient and that ${R_{{\rm{EM}}}}\left( x \right)$ is the correct reflection coefficient to use if one is interested in the response of a metasurface structure in terms of input-output EM fields. Therefore, a fundamental point to clarify is what the meaning of ${R_{{\rm{Z}}}}\left( x \right)$ is why it is routinely employed for the design and optimization of metasurfaces (see, e.g., \cite{Alu_Reflection2016}, \cite{Asadchy_2017}). To this end, it is instructive to formulate a perfect anomalous reflector by using the homogenized model based on surface-averaged impedances. \textbf{Anomalous reflection modeled via surface-averaged impedances}. A perfect anomalous reflector can be represented in terms of surface-averaged impedances by applying the equivalent transmission line representation for a metasurface structure that is depicted in Fig. \ref{Fig_SurfaceImpedances}. Based on the desired EM field transformations in \eqref{Eq_FullReflection_PlaneWave}, the following voltages and currents, at the two sides of the metasurface structure, can be obtained: \begin{equation} \label{Eq_Impedances__1} \begin{split} & {v^ + }\left( x \right) = E_y^i\left( x \right) + E_y^r\left( x \right)\\ & {v^\_}\left( x \right) = 0\\ & {i^ + }\left( x \right) = H_x^i\left( x \right) + H_x^r\left( x \right)\\ & {i^\_}\left( x \right) = 0 \end{split} \end{equation} By applying Kirchhoff's circuit laws to the equivalent transmission line in Fig. \ref{Fig_SurfaceImpedances}, the following system of equations can be obtained: \begin{equation} \label{Eq_Impedances__2} \left\{\begin{split} & {v^ + }\left( x \right) = \left( {{Z_1}\left( x \right) + {Z_3}\left( x \right)} \right){i^ + }\left( x \right) + {Z_3}\left( x \right){i^ - }\left( x \right)\\ & {v^ - }\left( x \right) = {Z_3}\left( x \right){i^ + }\left( x \right) + \left( {{Z_2}\left( x \right) + {Z_3}\left( x \right)} \right){i^ - }\left( x \right) \end{split} \right. \end{equation} By inserting \eqref{Eq_Impedances__1} in \eqref{Eq_Impedances__2}, we evince that a solution of the system of equations, i.e., an explicit expression of the surface-averaged impedances as a function of the transformations of the EM fields to be realized, is the following: \begin{equation} \label{Eq_Impedances__3} \begin{split} & {Z_1}\left( x \right) = {{{v^ + }\left( x \right)} \mathord{\left/ {\vphantom {{{v^ + }\left( x \right)} {{i^ + }\left( x \right)}}} \right. \kern-\nulldelimiterspace} {{i^ + }\left( x \right)}}\\ & {Z_2}\left( x \right) = {\rm{any \; function }}\\ & {Z_3}\left( x \right) = 0 \end{split} \end{equation} Therefore, ${Z_1}\left( x \right)$ is the surface-averaged impedance that determines the properties and EM response of the metasurface structure under design. By inserting \eqref{Eq_Impedances__1} in \eqref{Eq_Impedances__3} and using \eqref{Eq_FullReflection_PlaneWave}, in particular, the following benchmark analytical formulation for ${Z_1}\left( x \right)$ can be obtained (for any value of $A_r$): \begin{equation} \label{Eq_Impedances__4} \begin{split} {Z_1}\left( x \right) &= \frac{{E_y^i\left( x \right) + E_y^r\left( x \right)}}{{H_x^i\left( x \right) + H_x^r\left( x \right)}}\\ & \hspace{-0.5cm} = \eta \frac{{1 + {A_r}\Phi \left( x \right)}}{{\cos \left( {{\theta _i}} \right) - {A_r}\cos \left( {{\theta _i}} \right)\Phi \left( x \right)}}\\ & \hspace{-0.5cm} \mathop = \limits^{\left( a \right)} \frac{\eta }{{\sqrt {\cos \left( {{\theta _i}} \right)\cos \left( {{\theta _r}} \right)} }}\frac{{\sqrt {\cos \left( {{\theta _r}} \right)} + \sqrt {\cos \left( {{\theta _i}} \right)} {\Phi}\left( x \right)}}{{\sqrt {\cos \left( {{\theta _i}} \right)} - \sqrt {\cos \left( {{\theta _r}} \right)} {\Phi}\left( x \right)}} \end{split} \end{equation} \noindent where (a) holds true if $A_r$ is set equal to \eqref{Eq_Ar_1}. \textbf{Comparison of homogenized models}. By direct inspection of \eqref{Eq_Impedances__4}, we observe that: (i) ${Z_1}\left( x \right)$ is, except for a scaling factor, the same as the surface-averaged susceptibility function in \eqref{Eq_FullReflection_Susceptibility}. This proves the equivalence of the homogenized models based on susceptibilities and impedances; (ii) ${Z_1}\left( x \right)$ coincides with the analytical formulations reported in \cite{Alu_Reflection2016}, \cite{Asadchy_2017}, \cite{Asadchy_2016}, \cite{Diaz-Rubio_2017}. We note, in particular, that ${Z_1}\left( x \right)$ is consistent with the advanced design in \cite[Eq. (3)]{Diaz-Rubio_2017}, for which a practical implementation of metasurface based on the physical principle of leaky-wave antennas exists; and (iii) ${Z_1}\left( x \right)$ is a complex number whose real part can be positive and negative. This brings to our attention that the resulting metasurface structure is non-locally passive but it can be made globally passive if $A_r$ is set equal to \eqref{Eq_Ar_1}. An example of realization of a non-locally passive but globally passive metasurface that behaves as a perfect anomalous reflector is elaborated in further text based on the recent results reported in \cite{Diaz-Rubio_2017}. \textbf{Definition of $\bf{R_{{\rm{\bf Z}}}}\left( x \right)$ based on surface-averaged impedances}. In the context of designing and engineering metasurfaces, the usual \text{definition} of surface-averaged reflection coefficient is the following \cite{Alu_Reflection2016}, \cite{Asadchy_2017}, \cite{Asadchy_2016}, \cite{Diaz-Rubio_2017}: \begin{equation} \label{Eq_Impedances__R} r\left( x \right) = \frac{{{Z_1}\left( x \right) - \frac{\eta }{{\cos \left( {{\theta _i}} \right)}}}}{{{Z_1}\left( x \right) + \frac{\eta }{{\cos \left( {{\theta _i}} \right)}}}} \mathop = \limits^{\left( a \right)} \frac{{{Z_1}\left( x \right) - {Z_i}\left( x \right)}}{{{Z_1}\left( x \right) + {Z_i}\left( x \right)}} \end{equation} \noindent where (a) is obtained by using \eqref{Comparing_ReflectionCoefficients__3}. By inserting \eqref{Eq_Impedances__4} in \eqref{Eq_Impedances__R}, we obtain $r\left( x \right) = {R_{\rm{Z}}}\left( x \right)$, where ${R_{\rm{Z}}}\left( x \right)$ is the surface-averaged reflection coefficient in \eqref{Eq_FieldsBack__R}. We conclude that ${R_{\rm{Z}}}\left( x \right)$ is the surface-averaged reflection coefficient that is usually found in physics-related papers, and that is typically employed for getting insights for designing metasurface structures with the desired reflection capabilities. Notably, ${R_{\rm{Z}}}\left( x \right)$ fulfills the identities in \eqref{Comparing_ReflectionCoefficients__2}, which are typically employed as a definition of reflection coefficient in the context of circuits design and analysis. \textbf{Physical interpretation and usefulness of $\bf{R_{{\rm{\bf Z}}}}\left( x \right)$}. Even though, as mentioned, ${R_{\rm{Z}}}\left( x \right)$ is not appropriate for relating the reflected EM fields to the incident EM fields, it provides one with important information for designing perfect anomalous reflectors. This can be inferred by a careful analysis of the equality (a) in \eqref{Eq_Impedances__R}. In a nutshell, $r\left( x \right) = {R_{\rm{Z}}}\left( x \right)$ provides one with information on how different the local (or point-wise) responses of a perfect anomalous reflector and a perfect specular reflector are. In general terms, according to \eqref{Comparing_ReflectionCoefficients__3} and \eqref{Comparing_ReflectionCoefficients__4}, the impedances of the incident and reflected EM waves are equal to ${Z_i} = {\eta \mathord{\left/ {\vphantom {\eta {\cos \left( {{\theta _i}} \right)}}} \right. \kern-\nulldelimiterspace} {\cos \left( {{\theta _i}} \right)}}$ and ${Z_r} = {\eta \mathord{\left/ {\vphantom {\eta {\cos \left( {{\theta _r}} \right)}}} \right. \kern-\nulldelimiterspace} {\cos \left( {{\theta _r}} \right)}}$, respectively. The larger the difference between the angle of reflection and the angle of reflection is, therefore, the larger the difference between ${Z_i}$ and ${Z_r}$ is. This implies that the transformation of the EM fields applied by the metasurface structure needs to be more distinct and marked as the difference between the angles of reflection and incidence increases. The reflection coefficient $r\left( x \right) = {R_{\rm{Z}}}\left( x \right)$ is a parameter that quantifies the local distinctive response of the metasurface structure. For a deeper understanding, let us assume that $A_r$ is equal to \eqref{Eq_Ar_1}. The reflection coefficient $r\left( x \right) = {R_{\rm{Z}}}\left( x \right)$ of a specular reflector can be obtained from \eqref{Eq_Impedances__R} by setting ${{\theta _r}}= {{\theta _i}}$, which yields $r\left( x \right) = {R_{\rm{Z}}}\left( x \right) = 1$ for every $x$. For a specular reflector, in other words, $r\left( x \right) = {R_{\rm{Z}}}\left( x \right)$ is constant in $x$. If ${{\theta _r}}\ne {{\theta _i}}$, on the other hand, the amplitude of $r\left( x \right) = {R_{\rm{Z}}}\left( x \right)$, i.e., $\left| {{R_{\rm{Z}}}\left( x \right)} \right|$, exhibits spatial variations in $x$, which becomes more pronounced as the difference between the angle of reflection and the angle of incidence increases. By inspecting $r\left( x \right) = {R_{\rm{Z}}}\left( x \right)$, we obtain information on the mismatch of the local spatial responses of the metasurface structures that correspond to anomalous and specular reflection. The specular reflector is a meaningful reference because it corresponds to the usual response of conventional surfaces and because it is characterized by an $r\left( x \right) = {R_{\rm{Z}}}\left( x \right)$ that is a uniform function in $x$. It is worth noting that the reflection coefficient ${R_{\rm{EM}}}\left( x \right)$ is not capable of unveiling these properties. From \eqref{EM_ReflectionCoefficient}, in particular, we evince that the amplitude of ${R_{\rm{EM}}}\left( x \right)$ exhibits no spatial variations along the metasurface structure, i.e., $\left| {{R_{\rm{EM}}}\left( x \right)} \right| = A_r$ is independent of $x$ for any angles of incidence and reflection. This confirms, once more, that ${R_{\rm{EM}}}\left( x \right)$ and ${R_{\rm{Z}}}\left( x \right)$ have different physical meanings and serve for different purposes. In the next paragraphs, numerical illustrations are used in order to further elucidate the properties, differences, and similarities of ${R_{\rm{EM}}}\left( x \right)$ and ${R_{\rm{Z}}}\left( x \right)$. \textbf{Canonical case: Normal incidence}. In the rest of this sub-section, for simplicity but without loss of generality, we focus our attention on the canonical case of EM fields with normal incidence, i.e., $\theta_i = 0$. In this case, ${R_{\rm{EM}}}\left( x \right)$ in \eqref{EM_ReflectionCoefficient} and ${R_{\rm{Z}}}\left( x \right)$ in \eqref{Eq_FieldsBack__R} reduce, respectively, to the following: \begin{equation} \label{Eq_FullReflection_NormalIncidence__EM} {R_{{\rm{EM}}}}\left( x \right) = {A_r}\exp \left( { - jk\sin \left( {{\theta _r}} \right)x} \right) \end{equation} \begin{equation} \label{Eq_FullReflection_NormalIncidence__Z} {R_{\rm{Z}}}\left( x \right) = \frac{{{A_r}\left( {1 + \cos \left( {{\theta _r}} \right)} \right)\exp \left( { - jk\sin \left( {{\theta _r}} \right)x} \right)}}{{2 + {A_r}\left( {1 - \cos \left( {{\theta _r}} \right)} \right)\exp \left( { - jk\sin \left( {{\theta _r}} \right)x} \right)}} \end{equation} In the following paragraph, as a case study, we describe some numerical illustrations in order to gain important engineering insights on the main features and properties of the reflection coefficients in \eqref{Eq_FullReflection_NormalIncidence__EM} and \eqref{Eq_FullReflection_NormalIncidence__Z} for various system setups and optimization criteria. It is worth emphasizing that \eqref{Eq_FullReflection_NormalIncidence__EM} and \eqref{Eq_FullReflection_NormalIncidence__Z} hold true for general values of $A_r$. The specific choice of $A_r$ determines, however, the ultimate performance, the power efficiency, and the implementation constraints for realizing, in practice, the resulting metasurface structure. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_15a.pdf} \caption{Amplitude of the reflection coefficient $R_{\rm{EM}}(x)$ in \eqref{Eq_FullReflection_NormalIncidence__EM} for $\theta_r = \theta$. Dashed lines: Ray optics approximation (i.e., $A_r=1$).} \label{Fig_15a} \end{centering} \end{figure} \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_15b.pdf} \caption{Phase of the reflection coefficient $R_{\rm{EM}}(x)$ in \eqref{Eq_FullReflection_NormalIncidence__EM} for $\theta_r = \theta$. Dashed lines: Ray optics approximation (i.e., $A_r=1$).} \label{Fig_15b} \end{centering} \end{figure} \textbf{Numerical illustrations: Understanding anomalous reflection}. Based on the closed-form expressions in \eqref{Eq_FullReflection_NormalIncidence__EM} and \eqref{Eq_FullReflection_NormalIncidence__Z}, the amplitude and phase of the surface-averaged reflection coefficient $R_{\rm{EM}}(x)$ are depicted in Figs. \ref{Fig_15a} and \ref{Fig_15b}, and the amplitude and phase of the surface-averaged reflection coefficient $R_{\rm{Z}}(x)$ are depicted in Figs. \ref{Fig_15a_1}-\ref{Fig_15b_2}, respectively, for different values of the angle of reflection $\theta_r$ and for two different values of $A_r$: (i) $A_r=A_1=1$ and (ii) $A_r=A_2$ equal to \eqref{Eq_Ar_1} by setting $\theta_i = 0$ in both cases. The considered case studies are relevant in order to understand the impact of $A_r$ on the design of metasurfaces, and to clarify the differences and similarities between $R_{\rm{EM}}(x)$ and $R_{\rm{Z}}(x)$. By direct inspection of \eqref{Eq_FullReflection_NormalIncidence__EM}, \eqref{Eq_FullReflection_NormalIncidence__Z}, and Figs. \ref{Fig_15a}-\ref{Fig_15b_2}, the following important observations can be made. \begin{itemize} \item \textit{\textbf{Designs based on ray optics are approximated}}. The surface-averaged reflection coefficients $R_{\rm{EM}}(x)$ and $R_{\rm{Z}}(x)$ of a perfect anomalous reflector are complex numbers whose amplitude and phase are, in general, different from those obtained by using ray optics approximation, i.e., $R_{\rm{ray \, optics}}\left( x \right) = \exp \left( { - jk\sin \left( {{\theta _r}} \right)x} \right)$ \cite{Capasso_Science2011}. In general, however, ray optics approximation is sufficiently accurate for low-medium angles of reflection, $\theta_r$, that need to be realized. It is worth nothing, in particular, that $R_{\rm{EM}}(x)$ and $R_{\rm{Z}}(x)$ tends, for every $x$, to one if $\theta _r=0$, i.e., if specular reflection is considered. We observe, however, a distinct difference between $R_{\rm{EM}}(x)$ and $R_{\rm{Z}}(x)$. As far as $R_{\rm{EM}}(x)$ is concerned, Figs. \ref{Fig_15a} and \ref{Fig_15b} show that the phase response of $R_{\rm{EM}}(x)$ coincide with ray optics approximation but the amplitude of $R_{\rm{EM}}(x)$ is different under the assumption that $A_r$ is optimized for achieving unitary power efficiency (in the global sense). We observe, however, that the amplitude of $R_{\rm{EM}}(x)$ exhibits no spatial variations and it is constant in $x$. As far as $R_{\rm{Z}}(x)$ is concerned, Figs. \ref{Fig_15a_1}-\ref{Fig_15b_2} unveil a different behavior as a function of $x$. The main difference stems from the amplitude of $R_{\rm{Z}}(x)$, which exhibits a highly varying spatial response whose fluctuations are more pronounced as the angle of reflection increases (with respect to the angle of incidence). The highly non-uniform local behavior of $R_{\rm{Z}}(x)$ unveils the inherent difficulty of realizing perfect anomalous reflectors with large angles of deflection and high power efficiency. \item \textit{\textbf{Amplitude and phase responses are correlated}}. For a given angle of reflection, $\theta_r$, the amplitude and phase of $R_{\rm{EM}}(x)$ and $R_{\rm{Z}}(x)$ are, in general, not independent of each other. The term ``correlation'' has, however, a different meaning for $R_{\rm{EM}}(x)$ and $R_{\rm{Z}}(x)$. As far as $R_{\rm{EM}}(x)$ is concerned, the term correlation refers to the fact that the amplitude and phase of $R_{\rm{EM}}(x)$ depend on the angle of reflection if $A_r$ is equal to \eqref{Eq_Ar_1}. In order to maximize the power efficiency of a metasurface structure, this implies that the amplitude and phase of $R_{\rm{EM}}(x)$ cannot be set independently of each other. This amplitude-phase interplay is not captured by ray optics approximation. However, no spatial coupling, i.e., as a function of $x$, is observed because the amplitude of $R_{\rm{EM}}(x)$ is independent of $x$. As far as $R_{\rm{Z}}(x)$ is concerned, on the other hand, the amplitude and phase of $R_{\rm{Z}}(x)$ are tightly (spatially) correlated along the surface, i.e., as a function of $x$. It is not possible, in general, to optimize the amplitude and the phase of $R_{\rm{Z}}(x)$ independently of each other. Similar to $R_{\rm{EM}}(x)$, the amplitude and phase of $R_{\rm{Z}}(x)$ depend on the angle of reflection. The highly non-uniform spatial coupling between the amplitude and the phase of $R_{\rm{Z}}(x)$ unveils the inherent difficulty of realizing perfect anomalous reflectors with large angles of deflection and high power efficiency. \item \textit{\textbf{The surface reflection coefficients are periodic functions}}. Figures \ref{Fig_15a}-\ref{Fig_15b_2} confirm the periodicity of the surface-averaged reflection coefficients $R_{\rm{EM}}(x)$ and $R_{\rm{Z}}(x)$ and, therefore, of the corresponding surface-averaged susceptibility function and surface-averaged impedance. This allows one to realize a perfect anomalous reflector based on the periodic repetition of a super-cell structure and to employ periodic boundary conditions for its design and optimization. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_15a_1.pdf} \caption{Amplitude of the reflection coefficient $R_{\rm{Z}}(x)$ in \eqref{Eq_FullReflection_NormalIncidence__Z} for $\theta_r = \theta$ and $A_r = A_1$. Dashed lines: Ray optics approximation.} \label{Fig_15a_1} \end{centering} \end{figure} \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_15b_1.pdf} \caption{Phase of the reflection coefficient $R_{\rm{Z}}(x)$ in \eqref{Eq_FullReflection_NormalIncidence__Z} for $\theta_r = \theta$ and $A_r = A_1$. Dashed lines: Ray optics approximation.} \label{Fig_15b_1} \end{centering} \end{figure} \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_15a_2.pdf} \caption{Amplitude of the reflection coefficient $R_{\rm{Z}}(x)$ in \eqref{Eq_FullReflection_NormalIncidence__Z} for $\theta_r = \theta$ and $A_r = A_2$. Dashed lines: Ray optics approximation.} \label{Fig_15a_2} \end{centering} \end{figure} \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_15b_2.pdf} \caption{Phase of the reflection coefficient $R_{\rm{Z}}(x)$ in \eqref{Eq_FullReflection_NormalIncidence__Z} for $\theta_r = \theta$ and $A_r = A_2$. Dashed lines: Ray optics approximation.} \label{Fig_15b_2} \end{centering} \end{figure} \item \textit{\textbf{Perfect anomalous reflectors exhibit local power absorptions and gains}}. This important property that characterize perfect anomalous reflectors can be unveiled by analyzing $R_{\rm{Z}}(x)$. It is more difficult to unveil it by studying $R_{\rm{EM}}(x)$, since the amplitude of $R_{\rm{EM}}(x)$ is independent of $x$. More specifically, let us study the amplitude of $R_{\rm{Z}}(x)$ as a function of $A_r$. If $A_r = 1$, we observe that a metasurface structure that operates as a perfect anomalous reflector is locally passive, i.e., ${P_{{\rm{net}}}}\left( x \right) \le 0$, since the amplitude of $R_{\rm{Z}}(x)$ is less than or equal to one for every $x$. This implies that the metasurface structure exhibits power absorptions, since the reflected power flow is (locally) less than the incident power flow. If $A_r$ is, on the other hand, equal to the optimal setup for realizing the globally passive metasurface structure according to \eqref{Eq_Ar_1}, we observe that the amplitude of $R_{\rm{Z}}(x)$ cannot be equal to or smaller than one for every $x$. This implies that, if the metasurface structure is made globally passive, a perfect anomalous reflector needs to exhibit (virtual) local power absorptions and (virtual) local power gains along the surface of the metasurface structure. Even though a perfect anomalous reflector is designed to be globally passive, therefore, it is not, in general, locally passive. An simple design approach would consist of using active elements for ensuring $P_{{\rm{net}}} \ge 0$. This is, however, not the best solution if the ultimate target is to realize nearly-passive metasurfaces. Since nearly-passive metasurfaces are not intended to rely on power amplifiers (or active elements) during the normal operation phase, one may wonder how the non-local power gains can be obtained. This is discussed in, e.g., \cite{Asadchy_2017}, \cite{Asadchy_2016}, \cite{Diaz-Rubio_2017}, \cite{Epstein_2016}. The implementation recently reported in \cite{Diaz-Rubio_2017}, which assumes the optimal setup of $A_r$ in \eqref{Eq_Ar_1}, solves this issue by proposing a metasurface design that is realized by exciting evanescent (surface) waves (or leaky modes) that travel along the surface of the metasurface and that carry power from the effectively lossy regions to the effectively active regions of the metasurface structure. In other words, the metasurface design in \cite{Diaz-Rubio_2017} excites auxiliary EM fields, besides the propagating EM fields transformation in \eqref{Eq_FullReflection_PlaneWave}, so that (i) the energy of the impinging radio wave travels along the surface, from the (virtual) lossy regions to the (virtual) active regions; (ii) the metasurface structure is kept globally passive and has (nearly) unitary power efficiency; and (iii) no or minimal spurious reflections are generated towards unwanted directions. Evanescent fields are, more precisely, oscillating electric and magnetic fields that do not propagate but whose energy is spatially concentrated in the vicinity of the surface of the metasurface structure. The evanescent waves decay exponentially and are appropriately designed so as not to interfere with the main functionality of the metasurface structure at distances of a few (typically two or three) wavelengths from the metasurface. As far as the practical implementation in \cite{Diaz-Rubio_2017} is concerned, the fields transformation in \eqref{Eq_FullReflection_PlaneWave} constitutes, therefore, an approximated model, since in the very close vicinity of the metasurface structure the EM fields are not given by the summation of two simple incident and reflected plane waves, but other evanescent EM fields need to be considered. For wireless applications, these evanescent EM fields can be ignored as a first approximation, since the distances of interest are usually larger than two-three wavelengths, both in the radiative near-field and in the far-field. This point is elaborated in further text. Figures \ref{Fig_15a_1}-\ref{Fig_15b_2} show, in particular, that the larger the reflection angle (with respect to the incident angle) is, the larger the (virtual) power absorptions and gains along the metasurface structure need to be. The optimal setup of $A_r$ in \eqref{Eq_Ar_1}, results, in addition, in larger fluctuations of the amplitude of $R_{\rm{Z}}(x)$, which may be more difficult to realize in practice. No power fluctuation along the surface of the metasurface structure is obtained only if the angle of reflection coincides with the angle of incidence. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_16a.pdf} \caption{Normalized net power flow (${P_{{\rm{net}}}}/{P_0}$) in \eqref{Eq_PowerBudget__2} and \eqref{Eq_PowerBudget__3}, by setting $r_{i,r}={\cos \left( {{\theta _r}} \right)}/{\cos \left( {{\theta _i}} \right)}$, for $\theta_r = \theta$ and $A_r = \{A_1, A_2, A_3\}$.} \label{Fig_16a} \end{centering} \end{figure} \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_16b.pdf} \caption{Normalized net power flow (${P_{{\rm{net}}}}/{P_0}$) in \eqref{Eq_PowerBudget__3}, by setting $r_{i,r}=1$, for $\theta_r = \theta$ and $A_r = \{A_1, A_2, A_3\}$.} \label{Fig_16b} \end{centering} \end{figure} \item \textit{\textbf{On the global efficiency of perfect anomalous reflectors}}. The importance of realizing metasurfaces with a surface-averaged reflection coefficient $R_{\rm{EM}}(x)$ whose amplitude is greater than one and with a surface-averaged reflection coefficient $R_{\rm{Z}}(x)$ whose amplitude exhibits local absorptions and gains along the surface can be unveiled by analyzing the normalized net power flows reported in Figs. \ref{Fig_16a} and \ref{Fig_16b} for different values of $A_r$. In particular, Figs. \ref{Fig_16a} and \ref{Fig_16b} are obtained by employing the two analytical formulations of the net power flows in \eqref{Eq_PowerBudget__2} and \eqref{Eq_PowerBudget__3}, respectively, for three different values of $A_r$: $A_r=A_1=1$, $A_r=A_2$ in \eqref{Eq_Ar_1}, and $A_r=A_3$ in \eqref{Eq_Ar_2}. Negative and positive values of the normalized net power flow imply that the metasurface structure exhibits global power absorptions and gains, respectively. Figure \ref{Fig_16a} shows, in particular, that globally passive metasurfaces can be realized, based on \eqref{Eq_PowerBudget__2}, for all considered values of $A_r$. If $A_r$ is set equal to \eqref{Eq_Ar_1}, the metasurface structure is, as expected, globally passive and has a unitary power efficiency. In general, however, the power efficiency decreases as the angle of reflection (with respect to the angle of incidence) increases. From these results, we evince that highly efficient metasurface structures need to be non-locally passive. By setting $A_r=1$, in fact, one can obtain a locally passive metasurface structure but its power efficiency is relatively low, especially for large values of the angle of reflection with respect to the angle of incidence. By analyzing Fig. \ref{Fig_16b}, similar conclusions can be made. However, Fig. \ref{Fig_16b} shows that the normalized net power flow computed with \eqref{Eq_PowerBudget__3} is greater than one if $A_r$ is set equal to \eqref{Eq_Ar_1}. This results confirms that $R_{\rm{Z}}(x)$ is not an appropriate definition for the surface-averaged reflection coefficient if one is interested in calculating the reflected EM fields from the incident EM fields. The corresponding power budget is, for example, not consistent with the benchmark transformation of the EM fields in \eqref{Eq_FullReflection_PlaneWave}, which leads to different formulas for the net power flow, as exemplified by comparing \eqref{Eq_PowerBudget__2} with \eqref{Eq_PowerBudget__3} by setting $r_{i,r} =1$. \end{itemize} \textbf{$\bf{R_{{\rm{\bf EM}}}}\left( x \right)$ vs. $\bf{R_{{\rm{\bf Z}}}}\left( x \right)$: Main takeaway message}. Based on the theoretical analysis and the numerical comparison between ${R_{{\rm{EM}}}}\left( x \right)$ and ${R_{{\rm{Z}}}}\left( x \right)$, it is apparent that they are two different parameters that serve for different purposes. In general, ${R_{{\rm{EM}}}}\left( x \right)={R_{{\rm{Z}}}}\left( x \right)$ only for perfect specular reflectors. ${R_{{\rm{EM}}}}\left( x \right)$ is intended to be used in the of context wireless communications in order to characterize the response of a metasurface structure in terms of the phase and amplitude difference between the incident and reflected EM fields. ${R_{{\rm{Z}}}}\left( x \right)$ is intended to be used in the context of metasurface design in order to characterize the response of a metasurface structure in terms of the mismatch between the impedances of the incident and reflected EM waves. Both ${R_{{\rm{EM}}}}\left( x \right)$ and ${R_{{\rm{Z}}}}\left( x \right)$ are, however, surface-averaged, and, therefore, macroscopic parameters. As a consequence, it is not appropriate to interpret either ${R_{{\rm{EM}}}}\left( x_0 \right)$ or ${R_{{\rm{Z}}}}\left( x_0 \right)$ as the response of an individual unit cell of the metasurface structure that is located in the point $x_0$ on the surface. This is because ${R_{{\rm{EM}}}}\left( x \right)$ and ${R_{{\rm{Z}}}}\left( x \right)$ are defined and calculated based on surface-averaged EM fields and are not based on acting (local) EM fields, as discussed in previous text. \\ \noindent \underline{\textbf{\textit{Takeaway messages for application to wireless networks}}}. \textbf{Contrasting current models for RISs and the synthesis of metasurfaces}. Several recently published papers (see, e.g., \cite{MDR_OverheadAware} and references therein) typically assume that an RIS can be modeled as a structure that is made of a discrete number of individually tunable scatterers whose properties, e.g., the phase and amplitude of the reflection coefficient (i.e., ${R_{{{\rm EM}}}}\left( x \right)$), can be arbitrary and individually controlled. In general, the amplitude of the reflection coefficient of each scatterer is assumed to be unitary in order to ensure that the RIS is nearly-passive. Furthermore, the spatial correlation among the individual scatterers is usually ignored. These assumptions may be considered to be sufficiently accurate if an RIS is made of discrete tiny antenna elements, similar to the prototype in Fig. \ref{Fig_2}, that are sufficiently distant from each other. The procedure for the synthesis of metasurfaces described in this sub-section highlights, however, that these conventional assumptions may not necessarily be appropriate for modeling metasurfaces. \textbf{Key points to remember}. In particular, the following key points need to be kept in mind when designing metasurface-based RIS-empowered wireless networks. \begin{itemize} \item \textit{\textbf{The spatial coupling is not ignored}}. It is general belief that it is possible to individually control the reflection coefficient of each unit cell without taking into accounting the mutual coupling among them. This may not necessarily be correct. The synthesis procedure described in this sub-section unveils that the mutual coupling is not explicitly apparent thanks to the macroscopic description of the metasurfaces through the surface-averaged susceptibility functions (or the surface-averaged impedances). The macroscopic description of metasurfaces originates, however, from a microscopic description that explicitly accounts for the mutual coupling via the local fields. From an implementation standpoint, a metasurface is realized by jointly designing and optimizing the unit cells of the super-cell structure. This procedure inherently accounts for the mutual coupling among the unit cells that constitute the super-cell. \item \textit{\textbf{Globally passive does not imply locally passive}}. Nearly-passive RISs may not necessarily be locally passive. In general, highly-efficient metasurfaces may exhibit some (virtual) absorptions and gains along the surface. \item \textit{\textbf{Amplitude and phase responses are intertwined}}. The amplitude and phase of the radio waves impinging upon an RIS may not be modified independently of each other, but they may be coupled depending on the specific wave transformations to be realized and the constraints imposed to realize locally passive or globally passive metasurface structures. \end{itemize} \textbf{How to use the surface-averaged reflection coefficient}. As mentioned in previous text, the surface reflection coefficient for modeling the scattering from objects is a widespread tool in the context of wireless communications. Therefore, the analytical formulation in \eqref{Eq_FullReflection_R} may be particular convenient to use. In the context of designing wireless communication systems and networks, it is important to emphasize that one is interested in the surface-averaged reflection coefficient ${R_{{\rm{EM}}}}\left( x \right)$, which provides one with the response of a metasurface structure in terms of incident and reflected EM fields. The surface-averaged reflection coefficient ${R_{{\rm{EM}}}}\left( x \right)$ needs, however, not to be confused with the surface-averaged reflection coefficient ${R_{{\rm{Z}}}}\left( x \right)$, which is often used for designing and for gaining insight for implementing metasurface structures. Similar comments may be made if an RIS is employed for perfect anomalous transmission, or if it is designed to realize joint anomalous reflection and transmission. Based on these considerations, it is important to clarify how the surface-averaged reflection coefficient ${R_{{\rm{EM}}}}\left( x \right)$ should be used and should be interpreted in the context of wireless networks design. In this regard, the following comments can be made. \begin{itemize} \item \textit{\textbf{The surface-averaged reflection coefficient $\bf{R_{{\rm{\bf EM}}}}\left( x \right)$ is not a local parameter}}. ${R_{{\rm{EM}}}}\left( x \right)$ is a surface-averaged parameter and, therefore, it is not appropriate to discretize it and to interpret the resulting sampled values as the response of individual unit cells of the metasurface structure. This is because ${R_{{\rm{EM}}}}\left( x \right)$ is defined and calculated based on surface-averaged EM fields and not based on acting (local) EM fields. In this regard, ${R_{{\rm{EM}}}}\left( x \right)$ can be viewed as a ``global'' parameter that can be employed for analyzing RIS-empowered wireless networks. In other words, the representation of an RIS based on ${R_{{\rm{EM}}}}\left( x \right)$ inherently hides the implementation details of the corresponding metasurface structure, but it provides one with a tool to treat RISs as ``black boxes'' that can be used for designing and optimizing complex wireless communication systems and networks. \item \textit{\textbf{$\bf{A_r}$ can be viewed as an optimization variable}}. The analytical formulation of the surface-averaged reflection coefficient ${R_{{\rm{EM}}}}\left( x \right)$ is valid for any values of $A_r$. Therefore, one may restrict the range of values of $A_r$ for the specific application of interest. More precisely, the parameter $A_r$ can be viewed as an optimization parameter that allows one to account for the interplay between power efficiency and implementation complexity. If $A_r=1$, in fact, the metasurface structure is easier to realize as compared with the setup of $A_r$ equal to \eqref{Eq_Ar_1}, since sophisticated metasurface structures that exhibit virtual power losses and virtual power gains are needed in the latter case. It is worth mentioning that $A_r$ is, in general, a function of the angles of incidence and reflection, as confirmed by \eqref{Eq_Ar_1}. It is important to bear in mind, however, that the EM fields in \eqref{Eq_FullReflection_R} needs to be solutions of Maxwell's equations. $A_r$ and the corresponding reflected fields need to obey Maxwell's equations, and, therefore, some (physical) constraints on their choice exist. \item \textit{\textbf{$\bf{A_r}$ can be greater than one}}. Conventional methods for modeling RISs in wireless communications are based on representing an RIS through a diagonal matrix with individually tunable reflecting elements whose amplitudes are all unitary and are independent of the applied phase shifts \cite{MDR_OverheadAware}. This modeling approach corresponds to using ${R_{{\rm{EM}}}}\left( x \right)$ in \eqref{EM_ReflectionCoefficient} by setting $A_r=1$. The resulting metasurface structure is inherently locally passive but sub-optimal from the power efficiency point of view. In general, $A_r$ is greater than one in globally passive metasurfaces and it depends on the angles of incidence and reflection. \end{itemize} \textbf{``Black box'' modeling of a perfect anomalous reflector}. Based on the described synthesis procedure and recipe for application to wireless networks, therefore, we can model an RIS that is designed to operate as a perfect anomalous reflector as a ``black box'' whose output field is obtained by multiplying the input field and the surface-averaged reflection coefficient ${R_{{\rm{EM}}}}\left( x \right)$ in \eqref{EM_ReflectionCoefficient}, as formulated in \eqref{Eq_FullReflection_R}. This simple procedure allows one to account for several practical aspects of a metasurface, which include the mutual coupling among individual unit cells and the fact that, with the exception of the configuration network, the RIS is globally passive even though it is not necessarily locally passive. Further details on the analysis of general metasurfaces are given in the next sub-section. It is worth anticipating, however, that modeling a perfect anomalous reflector by means of a surface reflection coefficient relies on the assumption that the incident EM fields can be approximated to be locally-plane waves at the scale of an individual unit cell (not necessarily at the scale of the entire metasurface). Usually, this can be considered to be true at distances from the metasurface structure that are greater than a few (two or three) wavelengths. From the physics standpoint, this is necessary since the surface reflection coefficient defined in the present paper does not account for the evanescent EM waves in close vicinity of the metasurface, which may be needed to realize non-local passive structures. This concept is illustrated in Fig. \ref{Fig_18} and it is further elaborated in the next sub-section. \textbf{Relevance of the surface-averaged reflection coefficient for wireless applications}. The analytical formulation in terms of surface-averaged reflection coefficient ${R_{{\rm{EM}}}}\left( x \right)$ is especially useful for wireless applications. The reason is that wireless researchers are used to model systems as black boxes that perform some specific functions, but, at the same time, they wish to hide unnecessary details related to the practical implementation and realization of the systems themselves. This is necessary for analytical tractability, in order to model and optimize complex wireless networks, in which a single metasurface is one of the many network elements. With this in mind, the representation of EM fields as a function of surface-averaged susceptibility functions, surface-averaged impedances, or surface-averaged reflection coefficient ${R_{{\rm{Z}}}}\left( x \right)$ do not yield an explicit analytical formulation of the output fields as a function of the input fields. These latter homogenized representations, however, explicitly depend on the physical structure of the metasurface itself. This is useful for the synthesis of metasurfaces, since important insights on practical structures of unit cells can be explicitly obtained, and design guidelines on realizing practical structures can be obtained (e.g., from ${R_{{\rm{Z}}}}\left( x \right)$). The representation in terms of surface-averaged reflection coefficient ${R_{{\rm{EM}}}}\left( x \right)$ provides, on the other hand, information only on the function realized by a metasurface from the global point of view while hiding implementation-related details. Concretely, ${R_{{\rm{EM}}}}\left( x \right)$ provides one with an explicit relation that depends only on the angle of incidence and reflection of the radio waves, while hiding the physical structure of the metasurface. At the same time, the analytical formulation of ${R_{{\rm{EM}}}}\left( x \right)$ in \eqref{EM_ReflectionCoefficient} overcomes the limitations of current models used for wireless applications, according to which ${R_{{\rm{EM}}}}\left( x_1 \right)$ and ${R_{{\rm{EM}}}}\left( x_2 \right)$ are optimized independently of each other for any $x_1 \ne x_2$ \cite{MDR_OverheadAware}. \subsubsection{Analysis of a Metasurface} \textbf{EM fields scattered by a given metasurface}. In the previous sub-section, we have reported a general procedure for the synthesis of a metasurface that needs to realize some specified transformations on the impinging radio waves. In this sub-section, on the other hand, we consider that the metasurface is given and we are interested in computing a general and explicit expression of the reflected and transmitted electric and magnetic fields for some given incident electric and magnetic fields. In particular, we focus our attention on the EM fields that are at the two sides of a metasurface, i.e., at $z=0^+$ and $z=0^-$, which are the result of the EM discontinuity introduced by the metasurface structure. They are referred to as \textit{surface EM fields}. The computation of the electric and magnetic fields at any arbitrary point of a given volume where a metasurface is deployed are, on the other hand, discussed in the next sub-section. \textbf{Surface EM fields}. The analytical expressions of the surface EM fields that we are interested in calculating can be obtained from the GSTCs in \eqref{Eq_GSTCs_Explicit_H} and \eqref{Eq_GSTCs_Explicit_E}. In order to obtain an explicit expression of every tangential component of the electric and magnetic fields, we introduce the following matrices (for ease of writing, the dependency on $(x,y)$ is not explicitly reported): \begin{equation} \label{Eq_Analysis__Def1} \begin{split} &{\textbf{\textsf A}}\left( {x,y} \right) = \left[ {\begin{array}{*{20}{c}} {{{\rm{A}}_1}}&{{{\rm{A}}_2}}\\ {{{\rm{A}}_3}}&{{{\rm{A}}_4}} \end{array}} \right] = \frac{{j\omega \varepsilon }}{2}\left[ {\begin{array}{*{20}{c}} {\chi _{{\rm{ee}}}^{xx}}&{\chi _{{\rm{ee}}}^{xy}}\\ {\chi _{{\rm{ee}}}^{yx}}&{\chi _{{\rm{ee}}}^{yy}} \end{array}} \right] \\ & {\textbf{\textsf B}}\left( {x,y} \right) = \left[ {\begin{array}{*{20}{c}} {{{\rm{B}}_1}}&{{{\rm{B}}_2}}\\ {{{\rm{B}}_3}}&{{{\rm{B}}_4}} \end{array}} \right] = \frac{{j\omega \sqrt {\mu \varepsilon } }}{2}\left[ {\begin{array}{*{20}{c}} {\chi _{{\rm{em}}}^{xx}}&{\chi _{{\rm{em}}}^{xy}}\\ {\chi _{{\rm{em}}}^{yx}}&{\chi _{{\rm{em}}}^{yy}} \end{array}} \right]\\ & {\textbf{\textsf C}}\left( {x,y} \right) = \left[ {\begin{array}{*{20}{c}} {{{\rm{C}}_1}}&{{{\rm{C}}_2}}\\ {{{\rm{C}}_3}}&{{{\rm{C}}_4}} \end{array}} \right] = \frac{{j\omega \mu }}{2}\left[ {\begin{array}{*{20}{c}} {\chi _{{\rm{mm}}}^{xx}}&{\chi _{{\rm{mm}}}^{xy}}\\ {\chi _{{\rm{mm}}}^{yx}}&{\chi _{{\rm{mm}}}^{yy}} \end{array}} \right]\\ & {\textbf{\textsf D}}\left( {x,y} \right) = \left[ {\begin{array}{*{20}{c}} {{{\rm{D}}_1}}&{{{\rm{D}}_2}}\\ {{{\rm{D}}_3}}&{{{\rm{D}}_4}} \end{array}} \right] = \frac{{j\omega \sqrt {\mu \varepsilon } }}{2}\left[ {\begin{array}{*{20}{c}} {\chi _{{\rm{me}}}^{xx}}&{\chi _{{\rm{me}}}^{xy}}\\ {\chi _{{\rm{me}}}^{yx}}&{\chi _{{\rm{me}}}^{yy}} \end{array}} \right] \end{split} \end{equation} \begin{equation} \label{Eq_Analysis__Def2} {\textbf{\textsf Z}} = {\left[ {\begin{array}{*{20}{l}} {E_x^r}&{E_x^t}&{E_y^r}&{E_y^t}&{H_x^r}&{H_x^t}&{H_y^r}&{H_y^t} \end{array}} \right]^T} \end{equation} \begin{equation} \label{Eq_Analysis__Def3} {\textbf{\textsf M}} = \left[ {\begin{array}{*{20}{c}}{{{{\textbf{\textsf M}}}_1}}&{{{{\textbf{\textsf M}}}_2}}\end{array}} \right] \end{equation} \begin{equation} \nonumber \begin{split} & {{\textbf{\textsf M}}_1} = \left[ {\begin{array}{*{20}{c}} {{{\rm{A}}_1}}&{{{\rm{A}}_1}}&{{{\rm{A}}_2}}&{{{\rm{A}}_2}}\\ {{{\rm{A}}_3}}&{{{\rm{A}}_3}}&{{{\rm{A}}_4}}&{{{\rm{A}}_4}}\\ {{{\rm{D}}_1}}&{{{\rm{D}}_1}}&{{{\rm{D}}_2} + 1}&{{{\rm{D}}_2} - 1}\\ {{{\rm{D}}_3} - 1}&{{{\rm{D}}_3} + 1}&{{{\rm{D}}_4}}&{{{\rm{D}}_4}} \end{array}} \right] \\ & {{\textbf{\textsf M}}_2} = \left[ {\begin{array}{*{20}{c}} {{{\rm{B}}_1}}&{{{\rm{B}}_1}}&{{{\rm{B}}_2} - 1}&{{{\rm{B}}_2} + 1}\\ {{{\rm{B}}_3} + 1}&{{{\rm{B}}_3} - 1}&{{{\rm{B}}_4}}&{{{\rm{B}}_4}}\\ {{{\rm{C}}_1}}&{{{\rm{C}}_1}}&{{{\rm{C}}_2}}&{{{\rm{C}}_2}}\\ {{{\rm{C}}_3}}&{{{\rm{C}}_3}}&{{{\rm{C}}_4}}&{{{\rm{C}}_4}} \end{array}} \right] \end{split} \end{equation} \begin{equation} \label{Eq_Analysis__Def4} {\textbf{\textsf W}} = \left[ {\begin{array}{*{20}{c}} { - {{\rm{A}}_1}}&{ - {{\rm{A}}_2}}&{ - {{\rm{B}}_1}}&1-{{\rm{B}}_2}\\ { - {{\rm{A}}_3}}&{ - {{\rm{A}}_4}}&-1-{{\rm{B}}_3} &{ - {{\rm{B}}_4}}\\ { - {{\rm{D}}_1}}&-1-{{\rm{D}}_2}&{ - {{\rm{C}}_1}}&{ - {{\rm{C}}_3}}\\ 1-{{\rm{D}}_3}&{ - {{\rm{D}}_4}}&{ - {{\rm{C}}_3}}&{ - {{\rm{C}}_4}} \end{array}} \right] \end{equation} \begin{equation} \label{Eq_Analysis__Def5} {\textbf{\textsf F}} = {\left[ {\begin{array}{*{20}{c}} {E_x^i}&{E_y^i}&{H_x^i}&{H_y^i} \end{array}} \right]^T} \end{equation} \noindent With the aid of these definitions, \eqref{Eq_GSTCs_Explicit_H} and \eqref{Eq_GSTCs_Explicit_E} can be re-written in a single matrix form as follows: \begin{equation} \label{Eq_Analysis__Matrix} {\textbf{\textsf {MZ}}} = {\textbf{\textsf {WF}}} \end{equation} \textbf{Explicit analytical formulation}. An explicit expression for the reflected and transmitted surface EM fields can be obtained by solving the system of equations in \eqref{Eq_Analysis__Matrix}. To this end, the matrix $\textbf{\textsf {M}}$ is formulated in its singular value decomposition (SVD) form. In particular, let us introduce the following notation: (i) $\textbf{\textsf {V}}$ is the matrix whose columns are the eigenvectors of ${{\textbf {\textsf{M}}}^H}{\textbf {\textsf{M}}}$; (ii) $\textbf {\textsf{U}}$ is the matrix whose columns are the eigenvectors of ${\textbf {\textsf{M}}}{{\textbf {\textsf{M}}}^H}$; (iii) ${ \textbf {\textsf{ S}}}$ is a diagonal matrix whose entries are zero or are the square root of the non-zero eigenvalues of ${{\textbf {\textsf{M}}}^H}{\textbf {\textsf{M}}}$ or ${\textbf {\textsf{M}}}{{\textbf {\textsf{M}}}^H}$; and (iv) ${ \textbf {\textsf{ S}}} ^\dag$ is a diagonal matrix whose entries are either zero or are the reciprocal of the non-zero entries of ${ \textbf {\textsf{ S}}}$, i.e., ${ \textbf {\textsf{ S}}} ^\dag$ is the pseudo-inverse of ${ \textbf {\textsf{ S}}}$. Therefore, ${\textbf {\textsf{M}}} = {\textbf {\textsf{U S}}} {{\textbf {\textsf{V}}}^H}$ and ${\textbf {\textsf{Z}}}$ in \eqref{Eq_Analysis__Matrix} can be explicitly written as follows: \begin{equation} \label{Eq_Analysis__Solution} {\textbf {\textsf{Z}}} = \left( \textbf {\textsf{V}}{{\textbf {\textsf{S}}} ^\dag }{{\textbf {\textsf{U}}}^H}{\textbf {\textsf{W}}} \right) {\textbf {\textsf{F}}} = {\textbf {\textsf{PF}}} \end{equation} \noindent where ${\textbf {\textsf{P}}} = {\textbf {\textsf{V}}}{{\textbf {\textsf{S}}} ^\dag }{{\textbf {\textsf{U}}}^H}{\textbf {\textsf{W}}}$ is a matrix that depends only on the metasurface structure, i.e., the surface susceptibility functions, while it is independent of the incident, reflected, and transmitted fields. It is worth mentioning that, for any given matrix, the pseudo-inverse always exists and is unique. This implies that, given a metasurface structure, i.e., the surface susceptibility functions and the incident EM fields, one can always find the corresponding reflected and transmitted EM fields. \textbf{Functional structure of the surface EM fields}. The matrix ${\textbf {\textsf{P}}}$ in \eqref{Eq_Analysis__Solution} offers an explicit analytical relation between the incident (surface) EM fields, i.e., the vector ${\textbf {\textsf{F}}}$, and the reflected and transmitted (surface) EM fields. By direct inspection of \eqref{Eq_Analysis__Solution}, in particular, it is apparent that the reflected and transmitted surface EM fields can be explicitly formulated as: \begin{equation} \label{Eq_Analysis__Final} \begin{split} E_{x,y}^{r,t}\left( {x,y} \right) &\propto \varsigma _{E,x}^{r,t}\left( {x,y} \right)E_x^i\left( {x,y} \right) \\ & + \varsigma _{E,y}^{r,t}\left( {x,y} \right)E_y^i\left( {x,y} \right)\\ & + \varsigma _{H,x}^{r,t}\left( {x,y} \right)H_x^i\left( {x,y} \right) \\ &+ \varsigma _{H,y}^{r,t}\left( {x,y} \right)H_y^i\left( {x,y} \right) \\ H_{x,y}^{r,t}\left( {x,y} \right) &\propto \xi _{E,x}^{r,t}\left( {x,y} \right)E_x^i\left( {x,y} \right) \\ & + \xi _{E,y}^{r,t}\left( {x,y} \right)E_y^i\left( {x,y} \right)\\ & + \xi _{H,x}^{r,t}\left( {x,y} \right)H_x^i\left( {x,y} \right) \\ &+ \xi _{H,y}^{r,t}\left( {x,y} \right)H_y^i\left( {x,y} \right) \end{split} \end{equation} \noindent where $\varsigma _{\left\{ {E,H} \right\},\left\{ {x,y} \right\}}^{r,t}\left( {x,y} \right)$ and $\xi _{\left\{ {E,H} \right\},\left\{ {x,y} \right\}}^{r,t}\left( {x,y} \right)$ are coefficients that are obtained from ${\textbf {\textsf{P}}}$ and that allow one to express each tangential component of the surface EM fields on the two sides of a metasurface structure as a linear combination of the tangential components of the incident surface EM fields. \textbf{Examples: Perfect anomalous reflection and perfect anomalous transmission}. In order to better understand the general formalism in \eqref{Eq_Analysis__Final}, it is instructive to explicitly analyze the case studies of metasurface structures that realize perfect anomalous reflection and perfect anomalous transmission. To this end, we can consider the constitutive relations in \eqref{Eq_SusceptibilityExample}. \begin{itemize} \item \textbf{\textit{Perfect anomalous reflection}}. Under the assumption of perfect anomalous reflection, we have $E_x^t\left( {x,y} \right) = E_y^t\left( {x,y} \right) = 0$ and $H_x^t\left( {x,y} \right) = H_y^t\left( {x,y} \right) = 0$. As an example, let us consider that calculation of $E_y^r\left( {x,y} \right)$ and $H_x^r\left( {x,y} \right)$ in \eqref{Eq_SusceptibilityExample}. Similar analytical expressions can be obtained for $E_x^r\left( {x,y} \right)$ and $H_y^r\left( {x,y} \right)$. Therefore, $\chi _{{\rm{ee}}}^{yy}\left( {x,y} \right)$ and $\chi _{{\rm{mm}}}^{xx}\left( {x,y} \right)$ are the surface-averaged susceptibility functions of interest. Since, $\chi _{{\rm{ee}}}^{yy}\left( {x,y} \right)\chi _{{\rm{mm}}}^{xx}\left( {x,y} \right) = - {4 \mathord{\left/ {\vphantom {4 {{k^2}}}} \right. \kern-\nulldelimiterspace} {{k^2}}}$, the two corresponding constitutive relations in \eqref{Eq_SusceptibilityExample} are not linearly independent. This implies that multiple EM field transformations fulfill the constitutive relations in \eqref{Eq_SusceptibilityExample}. As a case study, let us consider solutions of the kind $H_x^r\left( {x,y} \right) = e\left( {x,y} \right)E_y^r\left( {x,y} \right)$, where $e\left( {x,y} \right)$ is a given function that fulfills Maxwell's equations. For example, this solution is in agreement with \eqref{Eq_FullReflection_R} for plane waves. Under these assumptions, we obtain the following explicit expression of the reflected EM fields as a function of the incident EM fields: \begin{equation} \label{Eq_Example__1} \begin{split} & E_y^r\left( {x,y} \right) = \frac{{ - \frac{{j\omega \varepsilon }}{2}\chi _{{\rm{ee}}}^{yy}\left( {x,y} \right)}}{{e\left( {x,y} \right) + \frac{{j\omega \varepsilon }}{2}\chi _{{\rm{ee}}}^{yy}\left( {x,y} \right)}}E_y^i\left( {x,y} \right)\\ & \hspace{1.3cm} - \frac{1}{{e\left( {x,y} \right) + \frac{{j\omega \varepsilon }}{2}\chi _{{\rm{ee}}}^{yy}\left( {x,y} \right)}}H_x^i\left( {x,y} \right)\\ &H_x^r\left( {x,y} \right) = \frac{{ - \frac{{j\omega \varepsilon }}{2}e\left( {x,y} \right)\chi _{{\rm{ee}}}^{yy}\left( {x,y} \right)}}{{e\left( {x,y} \right) + \frac{{j\omega \varepsilon }}{2}\chi _{{\rm{ee}}}^{yy}\left( {x,y} \right)}}E_y^i\left( {x,y} \right)\\ & \hspace{1.3cm} - \frac{{e\left( {x,y} \right)}}{{e\left( {x,y} \right) + \frac{{j\omega \varepsilon }}{2}\chi _{{\rm{ee}}}^{yy}\left( {x,y} \right)}}H_x^i\left( {x,y} \right) \end{split} \end{equation} \item \textbf{\textit{Perfect anomalous transmission}}. Under the assumption of perfect anomalous transmission, we have $E_x^r\left( {x,y} \right) = E_y^r\left( {x,y} \right) = 0$ and $H_x^r\left( {x,y} \right) = H_y^r\left( {x,y} \right) = 0$. As an example, let us consider that calculation of $E_y^t\left( {x,y} \right)$ and $H_x^t\left( {x,y} \right)$. Similar analytical expressions can be obtained for $E_x^t\left( {x,y} \right)$ and $H_y^t\left( {x,y} \right)$. Therefore, $\chi _{{\rm{ee}}}^{yy}\left( {x,y} \right)$ and $\chi _{{\rm{mm}}}^{xx}\left( {x,y} \right)$ are the surface-averaged susceptibility functions of interest. Under these assumptions, we obtain the following explicit expression of the transmitted EM fields as a function of the incident EM fields: \begin{equation} \label{Eq_Example__2} \begin{split} & E_y^t\left( {x,y} \right) = \frac{{1 + \frac{{j\omega \varepsilon }}{2}\chi _{{\rm{ee}}}^{yy}\left( {x,y} \right)\frac{{j\omega \mu }}{2}\chi _{{\rm{mm}}}^{xx}\left( {x,y} \right)}}{{1 - \frac{{j\omega \varepsilon }}{2}\chi _{{\rm{ee}}}^{yy}\left( {x,y} \right)\frac{{j\omega \mu }}{2}\chi _{{\rm{mm}}}^{xx}\left( {x,y} \right)}}E_y^i\left( {x,y} \right)\\ & \hspace{1.3cm} + 2\frac{{\frac{{j\omega \mu }}{2}\chi _{{\rm{mm}}}^{xx}\left( {x,y} \right)}}{{1 - \frac{{j\omega \varepsilon }}{2}\chi _{{\rm{ee}}}^{yy}\left( {x,y} \right)\frac{{j\omega \mu }}{2}\chi _{{\rm{mm}}}^{xx}\left( {x,y} \right)}}H_x^i\left( {x,y} \right)\\ & H_x^t\left( {x,y} \right) = 2\frac{{\frac{{j\omega \varepsilon }}{2}\chi _{{\rm{ee}}}^{yy}\left( {x,y} \right)}}{{1 - \frac{{j\omega \varepsilon }}{2}\chi _{{\rm{ee}}}^{yy}\left( {x,y} \right)\frac{{j\omega \mu }}{2}\chi _{{\rm{mm}}}^{xx}\left( {x,y} \right)}}E_y^i\left( {x,y} \right)\\ & \hspace{1.3cm} + \frac{{1 + \frac{{j\omega \varepsilon }}{2}\chi _{{\rm{ee}}}^{yy}\left( {x,y} \right)\frac{{j\omega \mu }}{2}\chi _{{\rm{mm}}}^{xx}\left( {x,y} \right)}}{{1 - \frac{{j\omega \varepsilon }}{2}\chi _{{\rm{ee}}}^{yy}\left( {x,y} \right)\frac{{j\omega \mu }}{2}\chi _{{\rm{mm}}}^{xx}\left( {x,y} \right)}}H_x^i\left( {x,y} \right) \end{split} \end{equation} \end{itemize} In both case studies, we note that the transmitted electric and magnetic fields are expressed as a linear combination of both the incident electric and magnetic fields. In general, in other words, cross-coupling among the EM fields exist. \textbf{``Black box'' modeling of metasurfaces}. Based on these general considerations and specific examples, the main conclusion that can be drawn from \eqref{Eq_Analysis__Solution} is that a metasurface can be modeled as a ``black box'' that takes the electric and magnetic (surface-averaged) EM fields in ${\textbf {\textsf{F}}}$ at its input and yields as an output the (surface-averaged) EM fields in ${\textbf {\textsf{Z}}}$. The example of perfect anomalous reflector analyzed in the previous sub-section is a special case of the general analytical formulation in \eqref{Eq_Analysis__Solution}, in which many entries of the surface susceptibility matrices are equal to zero by design. From a conceptual point of view, $\varsigma _{\left\{ \cdot \right\},\left\{ \cdot \right\}}^{r, \cdot }\left( {x,y} \right)$ and $\xi _{\left\{ \cdot \right\},\left\{ \cdot \right\}}^{r, \cdot }\left( {x,y} \right)$ can be interpreted as surface-averaged reflection coefficients (i.e., ${R_{{\rm{EM}}}}\left( x \right)$) and $\varsigma _{\left\{ \cdot \right\},\left\{ \cdot \right\}}^{t, \cdot }\left( {x,y} \right)$ and $\xi _{\left\{ \cdot \right\},\left\{ \cdot \right\}}^{t, \cdot }\left( {x,y} \right)$ as surface-averaged transmission coefficients for specific pairs of tangential components of the surface-averaged electric and magnetic fields on the two sides of the metasurface. As remarked in the previous sub-section, these coefficients implicitly account for the mutual coupling among the unit cells of the metasurface, as well as for the inherent coupling between the phase response and the amplitude response of the surface susceptibility functions. It is important to point out, however, that the surface-averaged EM fields under consideration can, in principle, be measured at distances from the metasurface that are larger than of two-three times the size of a unit cell (see also Fig. \ref{Fig_18} discussed in further text). The EM fields in close vicinity of the metasurface may contain, on the other hand, significant evanescent-field content that is carefully optimized in the design of the super-cell structure. As far as the calculation of the EM fields scattered by a metasurface is concerned, however, it is sufficient to consider the surface-averaged EM fields that are obtained from the homogenized modeling of metasurfaces and that are formulated in terms of surface susceptibility functions or surface impedances. This modeling assumption is employed in the next sub-section to formulate the EM field scattered by a phase gradient metasurface. \textbf{Relation between synthesis and analysis}. It is worth mentioning and emphasizing that the synthesis and analysis of metasurfaces are strongly intertwined. As far as the synthesis is concerned, the metasurface structure is designed and optimized based on some given EM fields and desired radio wave transformations. This implies that, once the metasurface structure is manufactured and deployed, it will realize the desired response if the impinging radio waves have the same properties as those assumed during the design and synthesis. Otherwise, the efficiency of the metasurface structure will be reduced and the actual response of the metasurface structure will be different from the desired response. Similar comments apply to the analysis and performance evaluation of wireless networks for a given metasurface structure. The surface susceptibility functions, in fact, correspond to incident, reflected, and transmitted EM fields with specific properties, e.g., the radio waves are plane, spherical, have a specified polarization, or simply are supposed to impinge upon the metasurface at only some angles of incidence. These constraints need to be taken into account when analyzing and optimizing RIS-empowered SREs. \textbf{Beyond surface EM fields}. The general functional relations in \eqref{Eq_Analysis__Solution} constitute the departing point in order to compute the electric and magnetic fields at any point of a given volume, e.g., far away from a metasurface, where an RIS may be deployed. This issue is investigated in the next sub-section. \subsection{On Modeling Radio Wave Propagation in the Presence of Metasurfaces} \label{WavePropagation} \textbf{From surface EM fields to EM fields in volumes}. In the previous sub-section, we have shown that a metasurface can be described in terms of surface susceptibility functions and that the electric and magnetic (surface) fields scattered by the metasurface can be formulated in an algebraic form under sufficiently general modeling assumptions. In this sub-section, we show that the knowledge of the EM field at the two sides of a metasurface, i.e., only at $z=0^+$ and $z=0^-$, is sufficient for computing the EM field at any point of a given volume. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_17.pdf} \caption{System model for modeling the propagation of radio waves in the presence of metasurfaces.} \label{Fig_17} \end{centering} \end{figure} \textbf{Reference system model}. We summarize, in particular, the analytical approach recently reported in \cite{MDR_SPAWC2020}. We highlight only the most important aspects of \cite{MDR_SPAWC2020}, some of which are not extensively elaborated in the original paper. For simplicity, in addition, we restrict the analysis to a one-dimensional metasurface and to a two-dimensional space (i.e., the plane). The general case study that encompasses two-dimensional metasurfaces in a three-dimensional space can be found in \cite{MDR_PathLossFadil}. For ease of illustration, the system model under analysis is sketched in Fig. \ref{Fig_17}, which depicts an infinitesimal small source that radiates isotropically in the plane and a one-dimensional metasurface. Further details about the system model are given in further text. \textbf{Reference operating regimes}. Before introducing the main recipe for obtaining the EM field scattered by a metasurface, we feel important to introduce some relevant operating regimes and concepts. To help us clarify them, the illustrations in Figs. \ref{Fig_18} and \ref{Fig_19} are utilized. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_18.pdf} \caption{Near-field vs. far-field of a metasurface and far-field of the array microstructure. The far-field boundary of the metasurface is obtained from the Fraunhofer distance as illustrated in Figs. \ref{Fig_7} and \ref{Fig_8}.} \label{Fig_18} \end{centering} \end{figure} \begin{itemize} \item \textit{\textbf{Near-field vs. far-field}}. As depicted in Fig. \ref{Fig_4}, a metasurface is made of unit cells whose size is usually smaller than the wavelength of the impinging radio waves. At distances from the metasurface that are larger than two-three times the size of a unit cell, which is still small compared with the wavelength, the EM fields of the evanescent surface modes of the metasurface structure, which may be present, can be considered to be negligible already. From the macroscopic point of view, in particular, the radio waves impinging upon a metasurface can be assumed to be locally plane waves regardless of the actual characteristics of the source (e.g., the source may not necessarily emit plane waves). In simple terms, this implies that, e.g., a spherical wavefront impinging upon a unit cell can be approximated by its tangent provided that the size of the unit cell is sufficiently small that the phase of the impinging radio wave does not change along the unit cell. Since we are interested in EM fields that are evaluated at transmission distances from the metasurface that are larger than two-three times the size of a unit cell, we can ignore the evanescent fields that may be present along the metasurface structure, and we can utilize the surface-averaged reflection coefficient for locally plane waves. In the present paper, this region is referred to as ``the far-field of the array microstructure''. Physically, as mentioned, this region corresponds to distances from the metasurface structure at which the evanescent EM fields are negligible. If we consider the example of an anomalous perfect reflector, this implies that the EM field scattered by the metasurface is approximately equal to the sum of two plane waves (as modeled in the previous example). At these distances, one can define and use the surface-averaged reflection coefficient ${R_{{\rm{EM}}}}\left( x \right)$ as defined in the previous example. As far as the whole metasurface structure is concerned, on the other hand, the operating regime is not unique. The transverse size of a metasurface can, in fact, be tens or hundreds (or more) times larger than the wavelength of the impinging radio waves. This implies that it is not possible to ignore, in general, the phase change of the impinging radio waves along the entire metasurface. Depending on the actual network geometry, the size of the metasurface, the operating wavelength, therefore, a metasurface can operate either in the near-field regime or in the far-field regime. For clarity, these operating regimes are conceptually illustrated in Fig. \ref{Fig_18}. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_19.pdf} \caption{Electrically large vs. electrically small metasurfaces.} \label{Fig_19} \end{centering} \end{figure} \item \textit{\textbf{Electrically large and electrically small metasurfaces}}. As mentioned, we cannot assume, a priori, that a metasurface operates in the far-field regime. This implies that the signal models and the corresponding analytical frameworks need to be sufficiently general to take this into account. This can be considered to be a not so usual situation in mainstream wireless communications, where the far-field operating regime is usually \textit{de facto} implied, even though often not explicitly stated. In the present paper, we do not attempt to give a formal definition of near-field and far-field for a metasurface as a whole. As an illustrative example, and based on the conventional definition for active antennas, Figs. \ref{Fig_7} and \ref{Fig_8} report the boundary of the radiative near-field and far-field as computed from the Fraunhofer distance. We provide, on the other hand, arguments to distinguish these two operating regimes from a practical standpoint. Instead of using the terms near-field and far-field, we introduce the concepts of electrically large and electrically small metasurfaces. For clarity, these two concepts are illustrated in Fig. \ref{Fig_19}. A metasurface is referred to as electrically large if its geometric size is large enough as compared with the wavelength of the radio waves, and as compared with the transmission distance from the source to the metasurface and from the metasurface to the observation point. If this is not the case, then the metasurface is referred to as electrically small. The term ``large enough'' is deliberately left a bit vague, since a formal definition would depend on a large number of system parameters. In simple terms, based on Fig. \ref{Fig_19}, a metasurface can be considered to be electrically large if the size of a metasurface and the transmission distances are such that one sees the metasurface as being infinitely large, and, therefore, one cannot see the edges of the metasurface structure. If the opposite holds true, a metasurface can be considered to be electrically small. By considering a metasurface of a given and fixed size, with a similar line of thought, a metasurface can likely be considered to be electrically large if the transmission distances are sufficiently short. If the transmission distances are, on the other hand, sufficiently long, then a metasurface can likely be considered to be electrically small. In further text, we show that the scaling laws as a function of key system parameters, e.g., the size of the metasurface and the transmission distances, are usually different for electrically large and electrically small metasurfaces. \end{itemize} \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_20a.pdf} \caption{The Huygens-Fresnel principle.} \label{Fig_20} \end{centering} \end{figure} \textbf{Theory of diffraction and Huygens-Fresnel principle}. With these preliminary definitions at hand, we can now discuss how to appropriately model the propagation of radio waves in the presence of a metasurface. As recently proved in \cite{MDR_SPAWC2020} and \cite{MDR_PathLossFadil}, the EM field at any point of a volume and in the presence of a metasurface can be obtained by invoking the theory of diffraction and the Huygens-Fresnel principle. In general terms, the theory of diffraction provides one with the mathematical tools for modeling the bending of the radio waves when they encounter an object or a discontinuity, which in our case is a metasurface characterized by its specific effective parameters. In classical physics, more precisely, diffraction-based phenomena, including the reflection and transmission from objects, are described by the Huygens-Fresnel principle. According to this principle, every point of a propagating wavefront is viewed as a collection of individual spherical wavelets. In particular, every point on a wavefront is itself the source of spherical wavelets, and the secondary wavelets emanated from different points interfere with each other. The sum of the emanated spherical wavelets forms a new wavefront. This concept is sketched in Fig. \ref{Fig_20}. \textbf{Green's theorem}. When the radio waves emitted by a source impinge upon a metasurface, based on the Huygens-Fresnel principle, the wavefront of the impinging radio wave in correspondence of a metasurface, i.e., at each point of a metasurface, becomes the source of secondary wavelets that determine the EM field at any point of the volume of interest. Based on the divergence theorem (or, its more general formulation, the Green theorem \cite{Green_1828}), which states that the surface integral of a vector field over a closed surface is equal to the volume integral of the divergence of the vector field over the region inside the surface, the EM field of interest is uniquely determined by the EM fields on the two sides of a metasurface, i.e., the surface EM fields. The readers are referred to \cite{MDR_SPAWC2020}, \cite{MDR_PathLossFadil} for the analytical details. As far as the present paper is concerned, it is sufficient to understand that this implies that the EM field at any point of a volume can be obtained from the GSTCs computed in the previous sub-section, which, in fact, formulate the tangential components of the EM (surface) fields at the two sides of a metasurface. Formally, this is reported in \eqref{Eq_Analysis__Final} for a general metasurface. \textbf{The atomic case study}. In the rest of the present paper, we assume, for simplicity, that the metasurface under analysis is characterized by a single non-zero reflection coefficient $\varsigma _{\left\{ \cdot \right\},\left\{ \cdot \right\}}^{r, \cdot }\left( {x,y} \right) = \Delta \left( {x,y} \right)\exp \left( {jk\Upsilon \left( {x,y} \right)} \right)$, where $\Delta \left( {x,y} \right) = \left| {\varsigma _{\left\{ \cdot \right\},\left\{ \cdot \right\}}^{r, \cdot }\left( {x,y} \right)} \right|$ and $k\Upsilon \left( {x,y} \right) = \arg \left( {\varsigma _{\left\{ \cdot \right\},\left\{ \cdot \right\}}^{r, \cdot }\left( {x,y} \right)} \right)$ are the amplitude and the phase of $\varsigma _{\left\{ \cdot \right\},\left\{ \cdot \right\}}^{r, \cdot }\left( {x,y} \right)$. Also, we assume $\Delta \left( {x,y} \right) = \Delta \left( {x} \right)$ and $\Upsilon \left( {x,y} \right) = \Upsilon \left( {x} \right)$. If other coefficients in \eqref{Eq_Analysis__Final} are not equal to zero, the electric or magnetic tangential components of the field of interest can be formulated as a linear combination of integrals similar to those reported in further text. It is worth emphasizing that the term surface-averaged reflection coefficient is always referred to ${R_{{\rm{EM}}}}\left( x \right)$ (not to ${R_{{\rm{Z}}}}\left( x \right)$) if one is interested in analyzing the actual EM fields reflected from an RIS. \subsubsection{Analytical Formulation of the EM Field} \label{FieldFormulation} \textbf{An approach based on Green's functions}. By capitalizing on the Huygens-Fresnel principle and by assuming an infinitesimally small source whose complex amplitude is the Green function in a two-dimensional plane, the authors of \cite{MDR_SPAWC2020} have given the following expression for a generic component of the EM field reflected by a metasurface located at $y=0$ and $L_x \le x \le L_x$: \begin{equation} \label{Eq_Field_Integral} \begin{split} & Z\left( {{x_R},{y_R}} \right) \approx \frac{1}{{8\pi }}\int\nolimits_{ - {L_x}}^{ + {L_x}} {{\mathcal{I}}\left( x \right)\exp \left( { - jk{\mathcal{P}}\left( x \right)} \right)dx} \\ & {\mathcal{P}}\left( x \right) = {d_T}\left( x \right) + {d_R}\left( x \right) - \Upsilon \left( x \right)\\ & {\mathcal{I}}\left( x \right) = \frac{{\Delta \left( x \right)}}{{\sqrt {{d_T}\left( x \right){d_R}\left( x \right)} }}\left( {\frac{{{y_T}}}{{{d_T}\left( x \right)}} + \frac{{{y_R}}}{{{d_R}\left( x \right)}}} \right) \end{split} \end{equation} \noindent where $2 L_x$ is the size (length) of the metasurface, $\left( {{x_T},{y_T}} \right)$ is the location of the source, $\left( {{x_R},{y_R}} \right)$ is the location of the observation point (e.g., where an intended receiver is located), and ${{d_T}\left( x \right)}$ and ${{d_R}\left( x \right)}$ are the transmission distances from the source to the point $x$ of the metasurface and from the point $x$ of the metasurface to the observation point, respectively: \begin{equation} \label{Eq_Distances} \begin{split} & {d_T}\left( x \right) = \sqrt {{{\left( {{x_T} - x} \right)}^2} + y_T^2} \\ & {d_R}\left( x \right) = \sqrt {{{\left( {{x_R} - x} \right)}^2} + y_R^2} \end{split} \end{equation} It is worth mentioning that the integral (instead of a sum of EM fields scattered by individual scatterers) formulation in \eqref{Eq_Field_Integral} is a consequence of employing a homogenized approach for modeling metasurfaces, which is consistent with the sub-wavelength inter-distance between adjacent unit cells and the GSTCs introduced in the previous section. \textbf{Interpretation of the reflected field}. The analytical formulation in \eqref{Eq_Field_Integral}, based on the Huygens-Fresnel principle, can be interpreted by rewriting the integrand function as follows: \begin{equation} \label{Eq_Interpretation} \begin{split} {\mathcal{I}}\left( x \right)\exp \left( { - jk{\mathcal{P}}\left( x \right)} \right) & = \frac{{\exp \left( { - jk{d_T}\left( x \right)} \right)}}{{\sqrt {{d_T}\left( x \right)} }}\\ & \times \Delta \left( x \right)\exp \left( {jk\Upsilon \left( x \right)} \right)\\ & \times \frac{{\exp \left( { - jk{d_R}\left( x \right)} \right)}}{{\sqrt {{d_R}\left( x \right)} }}\\ & \times \left( {\frac{{{y_T}}}{{{d_T}\left( x \right)}} + \frac{{{y_R}}}{{{d_R}\left( x \right)}}} \right) \end{split} \end{equation} \noindent where: (i) the first term corresponds to the radio wave impinging upon the metasurface (i.e., the Green function); (ii) the second term corresponds to the surface response of the metasurface that is obtained from the homogenized model; (iii) the third term corresponds to the radio wave that is re-emitted by the metasurface upon reception of the impinging radio wave (i.e., the Green function); and (iv) the fourth term represents the sum of the cosines of the inclination angles under which the metasurface is viewed by the source and by the observation point. Finally, the integral originates from the fact that a metasurface can be homogeneized and by applying the divergence theorem, which, in simple terms, allows one to formulate a vector field in a given volume as a function of the corresponding surface integral. It is worth mentioning that ${\mathcal{I}}\left( x \right)$ depends on the square root of the transmission distances because a bi-dimensional system model is considered, and the amplitude of the corresponding Green function, in the absence of a metasurface, decays with the square root of the transmission distance. \subsubsection{Configuration of the Metasurface} \label{Configuration} \textbf{Beamsteering vs. focusing}. From \eqref{Eq_Field_Integral}, it is apparent that a metasurface can be appropriately configured and can perform different functions depending on the specific choice of $\Delta \left( x \right)$ and ${\Upsilon \left( x \right)}$. As illustrative examples, we consider three case studies that have important applications in wireless communications: (i) specular reflector (or specular beamsteering); (ii) anomalous reflector (or anomalous beamsteering); and (iii) focusing lens (or beamforming). We assume, for simplicity, $\Delta \left( x \right) =1$, which corresponds to a benchmark for the three configurations of the metasurface under analysis. \begin{itemize} \item \textit{\textbf{Specular reflector}}. The specified wave transformation that the metasurface needs to realize is reflection by modifying the phase of the impinging radio wave. This operation can be obtained by using a uniform metasurface whose phase response per unit length is as follows: \begin{equation} \label{Eq_Specular} \Upsilon \left( x \right) = {\phi _0}/k \end{equation} \noindent where $\phi _0 \in [0,2\pi)$ is a fixed phase shift. If $\phi _0 =\pi$, for example, a perfect electric conductor (PEC) is obtained, whose reflection coefficient is $-1$. \item \textit{\textbf{Anomalous reflector}}. The specified wave transformation that the metasurface needs to realize is reflection by modifying the angle of reflection and the phase of the impinging radio wave. This operation can be obtained by using a phase gradient metasurface whose phase response per unit length is as follows: \begin{equation} \label{Eq_Anomalous} \Upsilon \left( x \right) = \left( {{{\bar \phi }_T} - {{\bar \phi }_R}} \right)x + {\phi _0}/k \end{equation} \noindent where $\phi _0 \in [0,2\pi)$ is a fixed phase shift, and ${{\bar \phi }_T}$ and ${{\bar \phi }_R}$ are two parameters to be optimized in order to steer the impinging radio wave towards a specified angle of reflection. In \cite{MDR_SPAWC2020}, for example, ${{\bar \phi }_T}$ and ${{\bar \phi }_R}$ are optimized as a function of the angles under which the source and the receiver view the center of the metasurface. It is worth mentioning that the design of the phase gradient in \eqref{Eq_Anomalous} can be considered to be an approximation of the optimal reflector in \eqref{Eq_FullReflection_ExplicitFormulaReflection} that originates from ray optics arguments. The numerical results in \cite{MDR_SPAWC2020} show, however, that the desired function is appropriately realized, even though the efficiency of the metasurface, i.e., the ratio between the reflected and incident powers, may not necessarily be optimized. \item \textit{\textbf{Focusing lens}}. The specified wave transformation that the metasurface needs to realize is focusing the impinging radio wave towards a specified location. This operation can be obtained by using a phase gradient metasurface whose phase response per unit length is as follows: \begin{equation} \label{Eq_Focusing} \Upsilon \left( x \right) = \sqrt {{{\left( {x - {x_T}} \right)}^2} + y_T^2} + \sqrt {{{\left( {x - {{\bar x}_R}} \right)}^2} + \bar y_R^2} \end{equation} \noindent where $\left( {{{\bar x}_R},{{\bar y}_R}} \right)$ is the location where the radio wave needs to be focused. \end{itemize} \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_21.pdf} \caption{Comparison among specular reflector, anomalous reflector, and focusing lens (reproduced from \cite{MDR_SPAWC2020}). The source is not reported for clarity.} \label{Fig_21} \end{centering} \end{figure} \textbf{Optimization criteria for beamsteering and focusing}. We observe, therefore, that the phase response of the metasurface structure under analysis is quite different depending on the specified function to be realized. As an example, we can analyze the differences between the two phase responses in \eqref{Eq_Anomalous} and \eqref{Eq_Focusing}. In simple terms, the criterion employed for obtaining \eqref{Eq_Anomalous} consists of ensuring that, as a first-order approximation, the first-order derivative of $\mathcal{P}(x)$ in \eqref{Eq_Field_Integral} is equal to zero in correspondence of those points, $x$, of the metasurface for which the angle of reflection is the desired one (assuming that the angle of incidence is given and fixed). The criterion employed for obtaining \eqref{Eq_Focusing} consists, on the other hand, of ensuring that $\mathcal{P}(x)$ in \eqref{Eq_Field_Integral} is equal to zero in correspondence of the location where the radio wave needs to be focused to. By using this criterion, in fact, the complex terms as a function of $x$ in \eqref{Eq_Field_Integral} are all co-phased at the location of interest, thus yielding the desired focusing effect. In conclusion, we can state that \eqref{Eq_Anomalous} is chosen by considering the stationary points of $\mathcal{P}(x)$, while \eqref{Eq_Focusing} is chosen by considering the zeros of $\mathcal{P}(x)$. An example of the different behavior of the considered metasurface structure based on the configurations specified by the phase responses in \eqref{Eq_Specular}, \eqref{Eq_Anomalous}, and \eqref{Eq_Focusing} is illustrated in Fig. \ref{Fig_21}. \textbf{Comparing metasurfaces obtained from different optimization criteria}. Based on these considerations, we conclude that, in general, the performance of a metasurface is different depending on the criterion employed for optimizing $\mathcal{P}(x)$. This implies that it may not be relevant or interesting to first optimize a metasurface for operating as, e.g., a focusing lens, and then to study when and if the same metasurface can operate as an anomalous reflector. This is because the two metasurfaces are designed based on different criteria and in order to perform different functions. Furthermore, the comparison may not necessarily be fair since different designs usually rely on a different amount of channel state information and on different implementation complexities. As an example, let us consider the realization and practical operation of a metasurface with the phase response in \eqref{Eq_Anomalous} and a metasurface with the phase response in \eqref{Eq_Focusing}. In the first case, one needs to know only the angle of incidence and the angle of reflection for optimizing the phase response. This implies that the design needs not to be changed if, e.g., a receiver moves along the same direction. This could be true if, e.g., a user moves along a street or a hallway. In the second case, on the other hand, the optimization of \eqref{Eq_Focusing} necessitates the exact location of the receiver. This implies that the metasurface needs to be reconfigured every time that the user moves, even though the direction of motion is kept the same. This imposes some practical constraints on the rate at which a metasurface needs to be reconfigured, and the rate at which the environmental information needs to be estimated in order to achieve good performance. \subsubsection{Electrically Large vs. Electrically Small Regimes} \label{largeVSsmall} \textbf{Scaling laws and performance trends}. In this sub-section, we analyze in further detail the conditions under which a metasurface can be assumed to be electrically large and electrically small. In particular, we discuss the different scaling laws, as a function of many system parameters, that emerge in these two operating regimes. For simplicity, we consider only the configuration of a metasurface that operates as a specular reflector. This is the simplest case study, which allows us to draw several interesting and general conclusions on the performance trends that can be expected, and, at the same time, allows us to validate the consistency of the analytical formulation in \eqref{Eq_Field_Integral} in a canonical case study. The interested readers can find a similar analysis for metasurfaces that operate as an anomalous reflector and as a focusing lens in \cite{MDR_SPAWC2020} and \cite{MDR_PathLossFadil}. \textbf{Electrically large regime}. If the metasurface structure can be assumed to be electrically large, e.g., given its size and operating frequency, the transmission distances are sufficiently short that the metasurface is viewed as infinitely large, the intensity of the field in \eqref{Eq_Field_Integral} can be approximated as follows: \begin{equation} \label{Eq_Large} \left| {{Z}\left( {{x_R},{y_R}} \right)} \right| \approx \frac{1}{{\sqrt {8\pi k} }}\frac{1}{{\sqrt {{d_T}\left( {{x_s}} \right) + {d_R}\left( {{x_s}} \right)} }} \end{equation} \noindent where ${x_s} \in \left[ {-L_x,L_x} \right]$ is the unique solution, if it exists, of the equation: \begin{equation} \label{Eq_Xs} \frac{{{x_s} - {x_T}}}{{{d_T}\left( {{x_s}} \right)}} - \frac{{{x_R} - {x_s}}}{{{d_R}\left( {{x_s}} \right)}} = 0 \end{equation} \noindent which corresponds to the stationary point of $\mathcal{P}(x)$. \textbf{Electrically small regime}. If, on the other hand, the metasurface structure can be assumed to be electrically small, e.g., given its size and operating frequency, the transmission distances are sufficiently long that the metasurface is viewed as a small scatterer, the intensity of the field in \eqref{Eq_Field_Integral} can be approximated as follows: \begin{equation} \label{Eq_Small} \begin{split} \left| {{Z}\left( {{x_R},{y_R}} \right)} \right| &\approx \frac{L_x}{{4\pi }}\left| \frac{{\cos \left( {{\theta _{T0}}} \right) + \cos \left( {{\theta _{R0}}} \right)}}{{\sqrt {{d_{T0}}{d_{R0}}} }}\right|\\ & \times \left|\frac{{\sin \left( {k L_x\left( {\sin \left( {{\theta _{T0}}} \right) - \sin \left( {{\theta _{R0}}} \right)} \right)} \right)}}{{k L_x\left( {\sin \left( {{\theta _{T0}}} \right) - \sin \left( {{\theta _{R0}}} \right)} \right)}}\right| \end{split} \end{equation} \noindent where, for $Q=\{T, R \}$, ${d_{Q0}} = \sqrt {x_Q^2 + y_Q^2}$ is the transmission distance between the source and the center of the metasurface (i.e., the origin) if $Q=T$ and is the transmission distance between the center of the metasurface and the observation point if $Q=R$, and $\cos \left( {{\theta _{Q0}}} \right) = {{{y_Q}} \mathord{\left/ {\vphantom {{{y_Q}} {{d_{Q0}}}}} \right. \kern-\nulldelimiterspace} {{d_{Q0}}}}$ is the cosine of the angle that the direction of propagation of the incident (if $Q=T$) and reflected (if $Q=R$) radio wave forms with the normal to the metasurface, i.e., the $z$-axis. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_22.pdf} \caption{Intensity of the field as a function of the transmission distance (reproduced from \cite{MDR_SPAWC2020}). The distance is the sum of the distances between the source-to-RIS and RIS-to-destination, which are assumed to be equal.} \label{Fig_22} \end{centering} \end{figure} \textbf{Comparing the two regimes}. In simple terms, the main difference between \eqref{Eq_Large} and \eqref{Eq_Small} is that the latter equation is obtained by exploiting the parallel rays approximation of the radio wave emitted by the source thanks to the long transmission/observation distances. In the electrically small regime, in other words, it is possible to capitalize on the plane wave approximation of the impinging radio waves for the whole metasurface. The accuracy of the approximations in \eqref{Eq_Large} and \eqref{Eq_Small} is analyzed in Fig. \ref{Fig_22} for a metasurface that operates in the millimeter-wave frequency band (28 GHz) and whose size is 1.5 meters. In the considered case study, the metasurface structure is viewed as electrically large for distances of the order of tens of meters. The range of distances for which the approximation in \eqref{Eq_Large} is accurate depends, however, among other parameters, on the size of the metasurface structure and the operating frequency. In general, the larger the size of the metasurface structure is and the higher the operating frequency is, the more accurate the approximation in \eqref{Eq_Large} becomes, i.e., it can be used for longer transmission distances. \textbf{Design insights and performance trends}. From the obtained closed-form analytical expressions of the intensity of the EM field in \eqref{Eq_Large} and \eqref{Eq_Small}, several important conclusions can be drawn. The most important are summarized as follows. \begin{itemize} \item \textit{\textbf{Specular mirror}}. In the electrically large operating regime, (e.g., for short transmission distances), the metasurface structure behaves as a specular mirror. From \eqref{Eq_Large}, in particular, we observe that the (end-to-end, i.e., from the source to the observation point) intensity of the field reflected from the metasurface decays as a function of the reciprocal of the square root of the sum of the transmission distances from the source to the stationary point in \eqref{Eq_Xs} and from the stationary point in \eqref{Eq_Xs} to the observation point. The presence of the square root originates from the assumption of two-dimensional space as elaborated in previous text. \item \textit{\textbf{Method of images}}. The scaling law as a function of the transmission distances in \eqref{Eq_Large} is in agreement with the method of (mirror) images, which justifies the denomination ``specular mirror''. In particular, \eqref{Eq_Large} can be regarded as an approximation of \eqref{Eq_Field_Integral} under the assumption of geometric optics propagation. More precisely, \eqref{Eq_Large} unveils that the intensity of the field is approximately the same as the one obtained from a single ray (i.e., the direction of propagation of the wavefront of the EM wave) that corresponds to the piece-wise linear function made of the line segment the connects the source with with stationary point in \eqref{Eq_Xs} and the line segment the connects the stationary point in \eqref{Eq_Xs} with the observation point. Therefore, the stationary point in \eqref{Eq_Xs} is often referred to as the reflection point for a given source and observation point. \item \textit{\textbf{Law of reflection}}. Given a point $x$ of the metasurface structure, the angle of incidence, ${\theta _T}\left( x \right)$, and the angle of reflection, ${\theta _R}\left( x \right)$, fulfill the identities ${{\left( {{x} - {x_T}} \right)} \mathord{\left/ {\vphantom {{\left( {{x} - {x_T}} \right)} {{d_T}\left( {{x}} \right)}}} \right. \kern-\nulldelimiterspace} {{d_T}\left( {{x}} \right)}} = \sin \left( {{\theta _T}\left( {{x}} \right)} \right)$ and ${{\left( {{x_R} - {x}} \right)} \mathord{\left/ {\vphantom {{\left( {{x_R} - {x}} \right)} {{d_R}\left( {{}} \right)}}} \right. \kern-\nulldelimiterspace} {{d_R}\left( {{x}} \right)}} = \sin \left( {{\theta _R}\left( {{x}} \right)} \right)$, respectively. From \eqref{Eq_Xs}, this implies that the angle of incidence and the angle of reflection coincide at the reflection (stationary) point ${x_s} \in \left[ {-L_x,L_x} \right]$, i.e., ${\theta _T}\left( x_s \right) = {\theta _R}\left( x_s \right)$. In other words, \eqref{Eq_Large} and \eqref{Eq_Xs} allow us to retrieve the law of reflection. \item \textit{\textbf{Scatterer or diffuser}}. In the electrically small operating regime, (e.g., for long transmission distances), the metasurface structure does not behave as a specular mirror. Thanks to the parallel ray approximation that is employed to obtain \eqref{Eq_Large}, we observe that the intensity of the field depends, predominantly, on the distance, ${d_{T0}}$, from the source to the center (i.e., the origin) of the metasurface and on the distance, ${d_{R0}}$, from the center of the metasurface to the observation point. In particular, the scaling law that governs the intensity of the field as a function of the transmission distances is not straightforward to unveil. To shed light on the impact of the transmission distances, i.e., ${d_{T0}}$ and ${d_{R0}}$ in \eqref{Eq_Large}, we can consider the case study in which the source and the observation point move along two straight lines such that the angles $\theta_{T0}$ and $\theta_{R0}$ are kept constant (the two angles do not have to be necessarily the same), but ${d_{T0}}$ and ${d_{R0}}$ are different. In this case, we evince from \eqref{Eq_Large} that the intensity of the field decays as a function of the square root of the product of the transmission distances ${d_{T0}}$ and ${d_{R0}}$. In the electrically small operating regime, therefore, a metasurface is better modeled as a scatterer rather than a mirror, since its size is relatively small in comparison with the transmission distances ${d_{T0}}$ and ${d_{R0}}$. \item \textit{\textbf{Directivity}}. The intensity of the field in the electrically large and electrically small operating regimes is quite different not only as a function of the transmission distances, but as a function of the angular response as well. By direct inspection of \eqref{Eq_Small}, we retrieve the ``sinc-like'' behavior that is typical of the far-field regime, since ${\rm{sinc}}\left( {ax} \right) = {{\sin \left( {ax} \right)} \mathord{\left/ {\vphantom {{\sin \left( {ax} \right)} {\left( {ax} \right)}}} \right. \kern-\nulldelimiterspace} {\left( {ax} \right)}}$. Assuming that the angle of incidence, $\theta_{T0}$, of the impinging radio wave is fixed, this implies that the intensity of the field (i) achieves its maximum in the direction of observation that fulfills the condition $\theta_{R0} =\theta_{T0}$ and (ii) has an oscillating behavior whose envelope decays as the difference between $\theta_{R0}$ and $\theta_{T0}$ increases. This implies that, even in the electrically small operating regime, the metasurface structure has a behavior that resembles a specular reflector, but it is different from a specular mirror. In general, in addition, the main lobe of the ${\rm{sinc}}\left( {ax} \right)$ function becomes narrower as $a$ increases. With a slight abuse of terminology, we could say that the metasurface structure becomes more directive. In \eqref{Eq_Small}, $a = {{{L_x}} \mathord{\left/ {\vphantom {{{L_x}} k}} \right. \kern-\nulldelimiterspace} k} = {{\lambda {L_x}} \mathord{\left/ {\vphantom {{\lambda {L_x}} {\left( {2\pi } \right)}}} \right. \kern-\nulldelimiterspace} {\left( {2\pi } \right)}}$. This implies that the end-to-end response of the metasurface structure becomes more directive as the product ${\lambda {L_x}}$ increases, i.e., if either the operating frequency decreases or the size of the metasurface increases. The comparison between \eqref{Eq_Large} and \eqref{Eq_Small} informs us that the scaling laws that originate from \eqref{Eq_Small} hold true only if the metasurface structure operates in the electrically small regime, which implies that, given the transmission distances, the size of the metasurface cannot be increased without any limits. If the size of the metasurface exceeds a given threshold, then the parallel rays approximation cannot be used anymore, and \eqref{Eq_Large} and \eqref{Eq_Small} become a more accurate and a less accurate approximation for \eqref{Eq_Field_Integral}, respectively. By direct inspection of \eqref{Eq_Large}, we observe that the electrically large operating regime is not characterized by the ``sinc-like'' angular response that, on the other hand, characterizes \eqref{Eq_Small}. The intensity of the field in \eqref{Eq_Large} still depends, however, on the observation angle, since \eqref{Eq_Large} holds true only if there exists a point on the metasurface structure that fulfills \eqref{Eq_Xs}. In contrast with \eqref{Eq_Small}, the probability that there exists a point on the metasurface structure that fulfills \eqref{Eq_Xs} increases as the size of the metasurface increases. We conclude, therefore, that the scaling laws that emerge in the electrically large and electrically small operating regimes are quite different. Depending on the system setup, the correct approximation needs to be used. \item \textit{\textbf{Size vs. power conservation principle}}. The scaling law as a function of the size, $2 L_x$, of the metasurface structure is different in the electrically large and electrically small operating regimes. For ease of comparison, let us consider \eqref{Eq_Small} in correspondence of its maximum value that is obtained for $\theta_{R0} =\theta_{T0}$. We observe that \eqref{Eq_Large} is independent of $L_x$ while \eqref{Eq_Small} increases linearly with $L_x$. This scaling law as a function of $L_x$ can be intuitively justified by direct inspection of Fig. \ref{Fig_19}. In the electrically large operating regime, we cannot ``see'' the edges of the metasurface structure. Therefore, the intensity of the field cannot depend on the size of the metasurface. In the electrically small operating regime, the opposite holds true, and we expect that the intensity of the field depends on the size of the metasurface. This different scaling law is important, since it allows us to prove that the proposed approach based on the Huygens-Fresnel principle is consistent with the power conservation principle. For ease of exposition and for ease of comparison with other research works available in recent papers \cite{Wankai_PathLoss}, let us consider a discretized version for the metasurface structure. A metasurface can be discretized in $N$ unit cells whose inter-distance is ${\lambda \mathord{\left/ {\vphantom {\lambda \mathcal{D}}} \right. \kern-\nulldelimiterspace} \mathcal{D}}$ with $\mathcal{D} > 1$, such that $L_x = N \lambda/\mathcal{D}$. From \eqref{Eq_Small}, this implies, in agreement with some recent research papers \cite{Wankai_PathLoss}, that the power of the received field increases quadratically with the number $N$ of unit cells (by assuming that $\mathcal{D}$ is fixed). From \eqref{Eq_Large}, on the other hand, the power of the received field is independent of $N$. Based on \eqref{Eq_Small}, the received power would grow infinitely large as $N$ tends to infinity. This observation usually leads many researchers to conclude that the considered system model is physically incorrect, since it is not in agreement with the power conservation principle. The truth is, on the other hand, that the scaling law and the considered model are physically correct, since \eqref{Eq_Small} can be applied only in the electrically small operating regime. If $N$ increases tending to infinity, then \eqref{Eq_Small} cannot be utilized anymore. As $N$ increases towards infinity, \eqref{Eq_Small} becomes the less and less accurate, and it needs to be replaced by \eqref{Eq_Large} that well captures the regime of $N$ tending to infinity. Based on \eqref{Eq_Large}, we observe that the power does not grow infinitely large as the size of the metasurface structure tends to infinity, but it reaches an asymptotic limit that is independent of the size of the metasurface. Once again, we conclude that the correct approximation needs to be utilized in order to draw meaningful conclusions, and caution needs to be taken on arguing the inconsistency of models that are, on the other hand, correct in the operating regimes in which they are computed. \end{itemize} \textbf{Beyond uniform metasurfaces}. The remarks made in this section hold true for a metasurface that is uniform and operates as a specular reflector. A similar study can be performed for metasurfaces that are not uniform and are configured to operate as anomalous reflectors or as focusing lenses. As recently proved in \cite{MDR_SPAWC2020} and \cite{MDR_PathLossFadil}, the performance trends as a function of the system parameters can be different as compared with a specular reflector. In addition, the performance of each configuration can be different and needs to be judged based on the complexity and the amount of environmental information that is needed for an appropriate operation. A metasurface that operates as a focusing lens, for example, is expected to maximize the received power at a given location. Therefore, it is expected to outperform a metasurface that operates as a specular or as an anomalous reflector. As mentioned in previous text, however, the side information that is needed for operating a metasurface as a reflector and as a lens may be different, which has an impact on the overhead necessary for their configuration and, eventually, on their ultimate performance, \cite{MDR_OverheadAware}, \cite{MDR_SPAWC2020}, \cite{MDR_PathLossFadil}. \subsection{Modeling and Analyzing Reconfigurable Intelligent Surfaces: Recipe for Wireless Researchers} \label{RecipeWireless} \textbf{Two case studies}. Based on the approaches described for the synthesis and analysis of RISs in wireless networks, we summarize in this sub-section the recipe that wireless researchers could employ in order to incorporate analytically tractable but sufficiently accurate models for the metasurfaces in their signal and system models. In particular, we distinguish two case studies: (i) to analyze and optimize the performance of wireless networks by assuming to employ a metasurface structure that operates in a predetermined manner; and (ii) to identify the structure of the optimal metasurface structure that maximizes some desired performance metrics. These two case studies are analyzed in the following two sub-sections. \subsubsection{The Metasurface Structure is Given} In this case study, the structure of the metasurface is decided a priori, i.e., we assume to have a metasurface that transforms the impinging radio waves in specified ways. The following procedure for application in wireless networks can be used. \begin{itemize} \item \textit{\textbf{Input}}: The incident, reflected, and transmitted electric and magnetic fields in \eqref{Eq_Analysis__Def2} and \eqref{Eq_Analysis__Def5} are given and known. \item \textit{\textbf{Step 1}}: From \eqref{Eq_Analysis__Def2} and \eqref{Eq_Analysis__Def5}, the surface susceptibility functions of the metasurface structure that realizes the specified wave transformations are obtained from the constitutive relations in \eqref{Eq_GSTCs_Explicit_H} and \eqref{Eq_GSTCs_Explicit_E}. \item \textit{\textbf{Step 2}}: From the constitutive relations in \eqref{Eq_GSTCs_Explicit_H} and \eqref{Eq_GSTCs_Explicit_E}, the representation of the EM fields in terms of surface reflection and transmission coefficients is obtained from \eqref{Eq_Analysis__Solution}. \item \textit{\textbf{Step 3}}: From \eqref{Eq_Analysis__Solution}, the EM fields in a generic observation point of a given volume are obtained from the analytical formulation of the Huygens-Fresnel principle in \eqref{Eq_Field_Integral}. \item \textit{\textbf{Output}}: The performance metric of interest is formulated as a function of the EM fields, and it is used for system optimization. \end{itemize} It is worth mentioning that the surface susceptibility functions (in Step 1) may be available without any explicit formulation of the incident, reflected, and transmitted electric and magnetic fields. In this case, the procedure starts at Step 2. Also, it is worth mentioning that the analytical formulation in Step 3 needs to be consistent with the input fields. \subsubsection{The Metasurface Structure is Optimized} In this case study, the structure of the metasurface is not decided a priori but needs to be chosen in order to maximize some performance metrics, e.g., the spectral efficiency and the energy efficiency. The following procedure for application in wireless networks can be used. \begin{itemize} \item \textit{\textbf{Input}}: The surface susceptibility functions are the unknown of the problem. \item \textit{\textbf{Step 1}}: The EM fields are formulated in terms of generic surface susceptibility functions by using \eqref{Eq_Analysis__Solution}. \item \textit{\textbf{Step 2}}: From the generic analytical formulation in \eqref{Eq_Analysis__Solution}, the EM fields at a generic observation point of a given volume are obtained from the analytical formulation of the Huygens-Fresnel principle in \eqref{Eq_Field_Integral}. \item \textit{\textbf{Step 3}}: The performance metric of interest is formulated in terms of EM fields, and, therefore, as a function of generic surface susceptibility functions. \item \textit{\textbf{Output}}: The optimal surface susceptibility functions that maximize the performance metric of interest are calculated, and the corresponding metasurface structure is identified. \end{itemize} \textbf{Appropriate models need to be used}. We conclude this section by reminding the readers that, regardless of the specific problem as hand, it is important that realistic models for the metasurfaces and for the propagation of radio waves are employed. This is necessary in order to obtain results that are in agreement with the fundamental laws of physics. The methods described in this section, even though are based on some assumptions, may allow one to solve a broad class of research problems in wireless networks, and, more importantly, may help one understand the potential benefits and the limitations of employing RISs for wireless applications. \section{The State of Research} \label{SOTA} In this section, we report a comprehensive summary of the research activities on RIS-empowered SREs that are available to date. The research papers are split into main categories and a brief description for each paper is given. \subsection{Tutorials and Surveys} During the last two years, several survey and tutorial papers on the application of RISs to the design of wireless networks have been published \cite{MDR_AI_VTM}, \cite{MDR_AM_TCOM}, \cite{MDR_AI_RIS}, \cite{Liaskos_COMMAG}, \cite{Liaskos_ACM}, \cite{MDR_Survey_EURASIP}, \cite{MDR_Survey_Access}, \cite{MDR_RISs_Relays}, \cite{Liang2019}, \cite{MDR_Survey_Holos}, \cite{RuiZhang_Survey}, \cite{JunZhao_Survey_1}, \cite{Angela_Survey}, \cite{Niyato_Survey}. In \cite{MDR_Survey_EURASIP}, the concept of SREs is comprehensively discussed along with a historical perspective of initial contributions in this field of research. In \cite{MDR_Survey_Access}, the applications of RISs as anomalous reflectors and singe-RF transmitters are elaborated, and the bit error probability offered by both implementations is analyzed and compared. In \cite{MDR_RISs_Relays}, RISs and relays are compared against each other. It is shown that RISs are capable of providing a similar average rate as relays, but without necessitating a power amplifier and provided that they are sufficiently large. In \cite{MDR_AI_VTM}, \cite{MDR_AM_TCOM}, \cite{MDR_AI_RIS}, the potential need and applications of machine learning and AI to SREs are investigated. \subsection{Collaborative Research Projects} Besides the upsurge of research activities in academia and industry, several collaborative research projects have been funded during the last two years. In particular, the European Commission has recently funded three major research projects on the application of RISs to future wireless networks. The \textbf{\textit{VisorSurf}} project \cite{VisorSurf} began in January 2017. VisorSurf is aimed to develop a full stack of hardware and software components for smart and interconnected planar objects with a programmable electromagnetic behavior. The \textbf{\textit{ARIADNE}} project \cite{Ariadne} began in November 2019. ARIADNE is aimed to develop innovative technologies and protocols for providing enhanced connectivity to wireless networks that operate in the D-band (110-170 GHz), by coating environmental objects with RISs and turning them into controllable reflectors. The \textbf{\textit{PathFinder}} project \cite{PathFinder} will begin in May 2021. PathFinder is aimed to build the theoretical and algorithmic foundation of RIS-empowered wireless networks by introducing cross-disciplinary methodologies that capitalize on tools from communication theory, physics, and electromagnetism. \subsection{Physics and Electromagnetism} Research on metamaterials and metasurfaces has a very long history and countless research contributions can be found in the open technical literature. The readers interested in having background information on this wide research topic are invited to consult the many survey papers, tutorial papers, and books that are available in the literature. For example, background information on \textbf{\textit{metamaterials}} can be found in the books \cite{Book_Caloz}, \cite{Book_Engheta}, \cite{Book_Capolino}, \cite{Book_TieJunCui}, \cite{Book_Maier}. Notably, a historical perspective on metamaterials can be found in \cite{Book_Capolino}. The theory and applications of \textbf{\textit{metasurfaces and surface electromagnetics}} can be found in the book \cite{Book_SurfaceElectromagnetics}, and in the recent survey papers \cite{Survey_Tretyakov} and \cite{Survey_Others}. Readers interested in the \textbf{\textit{analytical modeling of applied electromagnetics and scattering theory}} are referred to the books \cite{Book_Tretyakov} and \cite{Book_Osipov}. The concept of \textbf{\textit{coding metamaterials}}, which can be viewed as the foundation of RISs, can be found in \cite{Coding_Cui}. Examples of realizations of metasurfaces with perfect control of the reflection and transmission of radio waves can be found in \cite{Asadchy_2017}, \cite{Asadchy_2016}, \cite{Epstein_2016}, \cite{Diaz-Rubio_2017}. A recent approach to design metasurfaces with multiple reconfigurable functions can be found in \cite{Tretyakov_Multifunction}. A recent short survey paper on the state-of-the-art of reconfigurable metasurfaces can be found in \cite{VisorSurf_Survey}. A comprehensive survey paper on reconfigurable reflectarrays and array lenses for dynamic antenna beam control is available in \cite{Perruisseau-Carrier}. \textbf{Main references of this paper}. In the present paper, the focus of Sections II and IV is on the development of computational methods for modeling and analyzing metasurfaces for application to the optimization of wireless communications and networks. The approach reported in Sections II and IV is, in particular, focused on a macroscopic homogenized abstraction modeling based on surface susceptibility functions and the corresponding surface reflection and transmission coefficients. Readers interested in further information on the fundamental theory behind this approach are invited to consult \cite{Caloz_GSTCs2015}, \cite{Caloz_Synthesis2018}, \cite{Caloz_Computational2018} and the first four chapters of the book \cite{Book_SurfaceElectromagnetics}. Readers interested in the implementation of metasurfaces with perfect anomalous reflection and transmission capabilities are invited to consult \cite{Asadchy_2017}, \cite{Asadchy_2016}, \cite{Epstein_2016}, \cite{Diaz-Rubio_2017}. In these latter papers, in particular, the implementation challenges of realizing locally and globally passive metasurfaces with high power efficiency are extensively discussed and early references on the topic are given. \subsection{Smart Radio Environments Empowered by Reconfigurable Intelligent Surfaces: Initial Works} Tracing back the history of an emerging research field is not a simple task. Going back to the years 2003-2014, we were able to find a few early papers in which the concepts of ``smart surfaces'' and ``smart environments" were advocated. In \cite{Holloway_Oct2003} and \cite{Holloway_Nov2005} published in 2003 and 2005, respectively, one can read ``\textit{The GSTCs are expected to have wide application to the design and analysis of antennas, reflectors, and other devices where controllable scatterers are used to form a ``smart'' surface}''; ``\textit{This could in principle enable us to realize controllable surfaces, able for instance to switch electronically between reflecting and transmitting states}''; and ``\textit{We see that if a scatterer can be chosen such that the electric and/or magnetic polarizability is changeable on demand, then a smart or controllable surface would be realized}''. In the tree papers \cite{Subrt2010}, \cite{Subrt2012a}, \cite{Subrt2012} published in 2010 and 2012, respectively, one can read ``\textit{This paper deals with a new approach to the control of the propagation environment in indoor scenarios using intelligent walls. The intelligent wall is a conventional wall situated inside a building, but equipped with an active frequency selective surface and sensors. The intelligent wall can be designed as a self-configuring and self-optimizing autonomous part of a collaborative infrastructure working within a high-capacity mobile radio system. The paper shows how such surfaces can be used to adjust the electromagnetic characteristics of the wall in response to changes in traffic demand, monitored using a network of sensors, thereby controlling the propagation environment inside the building}'' and ``\textit{We have proposed a new method of controlling signal coverage which can be used inside buildings both for coverage controlling and avoiding of interference between transmitters. The method is based on changing of electromagnetic properties of intelligent walls which are conventional walls equipped with an active frequency selective surface and sensors. The walls are part of a collaborative autonomous infrastructure and they are able to adjust their properties, e.g., on the basis of data obtained by sensing of users or cognitive network sensing. The results show that intelligent walls can be strong instrument to control signal coverage and subsequently to control available level of service. The controlling of coverage is very useful when mobile users change their position in an indoor scenario, because then intelligent walls provide the efficient way to change propagation environment rapidly}''. In \cite{Kaina2014} published in 2014, the authors demonstrate that spatial microwave modulators are capable of shaping, in a passive way, complex microwave fields in complex wireless environments, by using only binary phase state tunable metasurfaces. These findings are obtained through the design of a 0.4 $m^2$ spatial microwave modulator that consists of 102 controllable EM reflectors and that operates at a working frequency of 2.47 GHz. The 102 reflectors are controlled by using two Arduino 54-channel digital controllers. In the abstract of the paper, more specifically, one can read ``\textit{In this article, we propose to use electronically tunable metasurfaces as spatial microwave modulators. We demonstrate that like spatial light modulators, which have been recently proved to be ideal tools for controlling light propagation through multiple scattering media, spatial microwave modulators can efficiently shape in a passive way complex existing microwave fields in reverberating environments with a non-coherent energy feedback. We expect that spatial microwave modulators will be interesting tools for fundamental physics and will have applications in the field of wireless communications}''. During the last five years (2015-2020), and, in particular, during the last two years, the research contributions on RIS-empowered SREs have increased exponentially. The research papers available to date are discussed in the following thematic sub-sections. \subsection{Path-Loss and Channel Modeling} A major research issue for analyzing the ultimate performance limits, optimizing the operation, and assessing the advantages and limitations of RIS-empowered SREs is the development of simple but sufficiently accurate models for the power received at a given location in space when a transmitter emits radio waves that illuminate an RIS. This is an open and challenging research issue to tackle. Recently, however, a few initial research works have attempted to shed light on modeling the path-loss of RISs. In \cite{Wankai_PathLoss}, the authors perform a measurement campaign in an anechoic chamber and show that the power reflected from an RIS follows a scaling law that depends on many parameters, including the size of the RIS, the mutual distances between the transmitter/receiver and the RIS (i.e., near-field vs. far-field conditions), and whether the RIS is used for beamforming or broadcasting applications. In \cite{garcia2019reconfigurable}, the authors employ antenna theory to compute the electric field in the near-field and far-field of a finite-size RIS, and prove that an RIS is capable of acting as an anomalous mirror in the near-field of the array. The results are obtained numerically and no explicit analytical formulation of the received power as a function of the distance is given. Similar findings are reported in \cite{ellingson2019path}. In \cite{Khawaja-Coverage}, the authors study, through experimental measurements, the power scattered from passive reflectors that operate in the millimeter-wave frequency band. Also, the authors compare the obtained results against ray tracing simulations. By optimizing the area of the surface that is illuminated, it is shown that a finite-size passive reflector can act as an anomalous mirror. In \cite{ozdogan2019intelligent}, the authors study the path-loss of RISs in the far-field regime by leveraging antenna theory. The obtained results are in agreement with those reported in \cite{garcia2019reconfigurable} and \cite{ellingson2019path} under the assumption of far-field propagation. In \cite{MDR_SPAWC2020}, the authors use the scalar theory of diffraction and the Huygens-Fresnel principle in order to model the path-loss in both the near-field and far-field of RISs, which are modeled as homogenized sheets of electromagnetic material with negligible thickness. By using the stationary phase method, the authors unveil the regimes under which the path-loss depends on the sum and the product of the distances between the RIS and the transmitter, and the RIS and the receiver. The proposed analytical approach is shown to be sufficiently general for application to uniform reflecting surfaces, anomalous reflectors, and focusing reflecting lenses. \subsection{Surface-Based Modulation and Encoding} One of the emerging and promising applications of RISs is to employ them for modulating and encoding data into their individual reconfigurable elements. This application of RISs can be viewed as an instance of spatial modulation and index modulation \cite{MDR_SM_COMMAG}, \cite{MDR_SM_PIEEE}, \cite{MDR_SM_CST2015}, \cite{MDR_SM_CST2016}, \cite{MDR_SM_MILCOM}, \cite{MDR_IM_Access}, \cite{MDR_SM_JSAC}. In particular, recent research activities on this topic constitute a generalization of the concept of spatial modulation based on reconfigurable antennas, which was introduced in \cite{MDR_SM_MILCOM} and was recently engineered and realize in \cite{PhanHuy2019}. The bit error probability of spatial modulation based on the reconfigurable antennas is studied in \cite{MDR2019_Dung}, by using radiation patterns obtained from a manufactured reconfigurable antenna. The bit error probability of RIS-based spatial modulation is studied in \cite{MDR_Survey_Access}. In \cite{Basar2019}, the author studies the error probability offered by space shift keying and spatial modulation schemes that employ RISs. The author proposes maximum energy-based suboptimal and exhaustive search-based optimal detectors, and analyzes their performance with the aid of analytical frameworks and numerical simulations. The obtained results show that RIS-based spatial modulation is capable of providing high data rates at low error rates. A similar study can be found in \cite{canbilen2020reconfigurable}. In \cite{yan2019WCL}, the authors apply the principle of spatial modulation by modulating information onto the ON/OFF states of the reflecting elements of RISs. In addition, passive beamforming is obtained by adjusting the phase shifts of the activated reflecting elements. To optimize passive beamforming, the authors formulate an optimization problem and solve it by using semidefinite relaxation. To retrieve the information data from the transmitter and the RIS, the authors introduce a two-step detection algorithm based on compressed sensing and matrix factorization. The tradeoff between the passive beamforming gain and the information rate provided by RISs is investigated. In \cite{Guo19RefMod}, the authors propose a reflecting modulation scheme for RIS-based communications, where both the reflecting patterns and transmit signals carry information. To enhance the reliability of transmission, the authors devise a discrete optimization-based joint signal mapping, shaping, and reflecting design that minimizes the bit error probability for a given transmit signal candidate set and a given reflecting pattern candidate set. Numerical results show that the proposed optimized schemes outperform existing solutions in terms of bit error probability. In \cite{Hanzo__2020}, the authors propose three different architectures based on RISs for beam-index modulation in millimeter wave communication, which circumvent the line-of-sight blockage of millimeter wave frequencies. The authors derive the optimal maximum likelihood detector and a low-complexity compressed sensing detector for the proposed schemes. The proposed solutions are evaluated through extensive simulations and analytical bounds. In \cite{MDR_ISIT2020}, the authors conduct an information-theoretic analysis of RIS-empowered wireless networks. An RIS-aided communication link is considered, in which the transmitter can control the state of an RIS via a finite-rate control link. The authors derive information-theoretic limits and demonstrate that the capacity is achieved by a scheme that jointly encodes information onto the transmitted signal and onto the RIS configuration. In addition, a novel signaling strategy based on layered encoding is proposed, which enables practical successive cancellation-type decoding at the receiver. Numerical experiments demonstrate that conventional schemes that fix the configuration of RISs in order to maximize the signal-to-noise ratio are strictly suboptimal, since they are outperformed by the proposed strategies. \subsection{Channel Estimation} Channel estimation is a fundamental issue to tackle in SREs wherein nearly-passive RISs are employed. In contrast to other communication systems, e.g., relays, which are equipped with sufficiently powerful signal processing capabilities, nearly-passive RISs are equipped with minimal on-board signal processing units that are not intended to be used during their normal operation phase. Therefore, new algorithms and protocols are necessary in order to perform channel estimation, while keeping the complexity of RISs as low as possible and avoiding on-board signal processing operations as much as possible. In \cite{Nadeem2019b}, the authors investigate channel estimation in RIS-based multiple-input-single-output (MISO) links. The implementation and performance advantages of RIS-based communications over traditional relay-based and MIMO systems are discussed. A minimum mean square error channel estimation protocol is developed, and, based on the estimated channels, the phase shifts of the RIS are optimized by employing a gradient ascent algorithm. In \cite{Jensen2019}, the authors introduce optimal methods for estimating the cascaded channel from the transmitter to the receiver, i.e., the combined channel that includes the link from the transmitter to the RIS and the link from the RIS to the receiver. The proposed method is based on activating the RIS elements based on a sequence of patterns, which are selected based on the minimum variance unbiased estimation principle. It is found that the channel estimation phase mimics a series of discrete Fourier transforms. The authors show that the estimation variance of the proposed algorithms is one order of magnitude smaller compared with traditional approaches. In \cite{Lin2019}, the authors formulate the channel estimation problem in RIS-based systems as a constrained estimation error minimization problem, which is tackled by using the methods of Lagrange multipliers and a dual ascent-based algorithm. The Cramer-Rao lower bounds are determined for benchmarking purposes. It is shown that the derived method yields better accuracy, in the low signal-to-noise ratio regime, compared with least square methods. In \cite{Chen2019b}, the authors develop an algorithm for estimating the cascaded channel. The proposed approach leverages compressive sensing methods, by leveraging the sparsity available in the cascaded channel. In addition, the authors extend the approach to the joint estimation of multiple channels in a multi-user network setup. In order to improve the estimation performance, the optimization of the training reflection sequences is considered. In \cite{Ning2019}, the authors tackle the channel estimation problem by means of beam training. The associated quantization error is characterized and evaluated. As a low-complexity alternative for channel estimation, a hierarchical search codebook design is proposed. Based on the proposed channel estimation methods, the performance of RIS-based wireless networks is studied. In \cite{Wang2019d}, the authors propose a three-phase protocol for estimating large numbers of channel coefficients, for application to RIS-assisted uplink systems, by using a small number of pilot symbols. Building upon the observation that each RIS element reflects the signals from all the users to the transmitter via the same channel, the authors quantify the time that is necessary to estimate all required channels. The authors show that massive MIMO may play an important role in reducing the channel estimation overhead in RIS-based communication systems. In \cite{Xia2019}, the authors consider the uplink of a network with massive connectivity and investigate the joint problem of channel estimation and activity detection. The problem is formulated as a sparse matrix factorization, matrix completion, and multiple measurement vector problem, and a three-stage algorithm is proposed for solving it, by leveraging message passing methods. In \cite{cui2019efficient}, the authors propose a low-complexity channel information acquisition method for RIS-assisted communication systems that exploit the sparsity of millimeter-wave channels and the topology of RISs. Compared with state-of-the-art methods, the proposed approach requires less time-frequency resources for acquiring the channel information. In \cite{You2019}, the authors tackle the problem of joint channel estimation and sum-rate maximization in the uplink of a single-user RIS-based system. In particular, the phase shifts of RISs are assumed to be discretized. A practical but sub-optimal channel estimation method based on the discrete Fourier transform and on a truncation of Hadamard matrices is developed. Based on the estimated channel, rate optimization is tackled by designing the discrete phase shifts at the RIS. To this end, a low-complexity successive refinement algorithm is developed. By using numerical simulations, the authors show that the performance of the proposed method depends on the quality of the initialization point. In \cite{liu2019matrix}, the authors formulate the channel estimation problem of an RIS-assisted multiuser MIMO system as a matrix-calibration based matrix factorization task. This is exploited in order to reduce the length of the training sequences for estimating the cascaded channel, which includes the transmitter-to-RIS and the RIS-to-receiver links. By assuming slow-varying channel components and channel sparsity, the authors propose a message-passing based algorithm that factorizes the cascaded channel. The authors present an analytical framework to characterize the theoretical performance of the proposed estimator in the large-system limit. In \cite{wei2020parallel}, the authors propose a method for channel estimation that is based on the parallel factor decomposition algorithm in order to unfold the cascaded channel from the transmitter to the receiver. The proposed method is based on an alternating least squares algorithm that iteratively estimates the channel between the transmitter and the RIS as well as the channel between the RIS and the users. Simulation results show that the proposed iterative channel estimation method outperforms benchmark schemes based on genie-aided information. In \cite{wan2020broadband}, the authors propose a compressed-sensing-based channel estimation algorithm in which the angular channel sparsity of large-scale arrays that operate at millimeter wave frequencies is exploited to perform channel estimation at a reduced pilot overhead. The authors design pilot signals based on prior knowledge of the line-of-sight-dominated transmitter-to-RIS channel as well as prior information on the high-dimensional transmitter-to-receiver and RIS-to-receiver channels, by using compressed sensing methods. A distributed orthogonal matching pursuit algorithm is exploited in order to capitalize on the channel sparsity. In \cite{wang2019compressed}, the authors develop a joint channel estimation and beamforming design for RIS-assisted MISO systems in the millimeter-wave frequency band. In order to reduce the training overhead, the inherent sparsity of millimeter-wave channels is exploited. The authors first find a sparse representation of the cascaded channel, and then develop a compressed-sensing-based channel estimation method. Also, joint beamforming design is performed based on the estimated channel. In \cite{he2020channel}, the authors propose a two-stage channel estimation scheme by using iterative re-weighted methods for estimating the channel parameters in a sequential optimization loop. Simulation results show that the proposed method provides better performance than the two-stage orthogonal matching pursuit approach, in terms of channel estimation error and spectral efficiency gain. In \cite{mishra2019channel}, the authors introduce a channel estimation protocol for RIS-assisted energy transfer over MISO Rician fading channels. In order to account for the practical limitations of RISs and energy harvesting users, all computations are carried out at the transmitter. The authors derive near-optimal and closed-form expressions for active beamforming at the transmitter and for passive beamforming at the RIS. In \cite{de2020parafac}, the authors propose two novel channel estimation methods by assuming a structured time-domain pattern of pilots and RIS phase shifts. The authors show that the received signal follows a parallel factor tensor model that can be exploited to estimate the involved communication channels in closed-form or iteratively. Numerical results corroborate the effectiveness of the proposed channel estimation methods and highlight the existing tradeoffs. In \cite{ning2019channel}, the authors introduce a channel estimation and transmission design for low scattering channels that is based on hybrid beamforming architectures. The authors design two different codebooks for efficiently realizing the proposed estimation procedure via a three-tree hierarchical search algorithm. The two codebooks are referred to as tree dictionary codebook and phase shifter deactivation codebook. By using the estimation information, the authors compute two closed-form transmission designs that maximize the overall spectral efficiency. In \cite{you2019progressive}, the authors propose a hierarchical training reflection design for progressively estimating the channels based on an RIS-elements grouping and partition method. Specifically, a new discrete Fourier transform Hadamard-based basis training reflection matrix design is proposed in order to minimize the mean square channel estimation error. Moreover, the authors propose two subgroup partition schemes and design efficient subgroup training reflection matrices to progressively resolve the subgroup aggregated channels of each group over the blocks. Based on the resolved subgroup aggregated channels, passive beamforming is used for improving the achievable rate, by taking into account the derived channel estimation error covariance matrix. Also, a low-complexity successive refinement algorithm with properly designed initializations is proposed in order to obtain high-quality suboptimal solutions. In \cite{mirza2019channel}, the authors introduce a two stage channel estimation method. Based on the proposed algorithm, the direct channel between the access point and the users is estimated during the first stage. The RIS channels are estimated during the second stage by using a bilinear adaptive vector approximate message passing algorithm. A phase shift design for the RIS elements, which approximately maximizes the channel gain at the user, is proposed. In \cite{hu2019two}, the authors propose a two-timescale channel estimation framework. The key idea of the framework is to exploit the property that the transmitter-RIS channel is high-dimensional but quasi-static, while the RIS-receiver channel is mobile but low dimensional. To estimate the quasi-static transmitter-RIS channel, the authors propose a dual-link pilot transmission scheme, in which the transmitter emits downlink pilots and receives uplink pilots reflected by the RIS. The authors propose a coordinate descent-based algorithm to recover the transmitter-RIS channel. With the aid of numerical results, the authors show that the proposed two-timescale channel estimation framework can achieve accurate channel estimation with low pilot overhead. In \cite{zheng2019channel}, the authors study the problem of channel estimation for ambient backscattering. The authors design an estimator consisting of an initial estimation step and a subsequent iteration phase in order to acquire the channel parameters. To further evaluate the performance of the designed estimator, the authors derive Cramer-Rao lower bounds for the channel estimates. In \cite{XiaojunYuan}, the authors introduce a general framework for the estimation of the transmitter-RIS and RIS-receiver cascaded channel, by leveraging a combined bilinear spare matrix factorization and matrix completion. In particular, the authors present a two-stage algorithm that includes a generalized bilinear message passing algorithm for matrix factorization and a Riemannian manifold gradient-based algorithm for matrix completion. Simulation results illustrate that the proposed method achieves accurate channel estimation performance for application to RIS-assisted systems. In \cite{alexandropoulos2020hardware}, the authors present an architecture for RISs that comprises an arbitrary number of passive reflecting elements, a simple controller for their adjustable configuration, and a single RF chain for baseband measurements. By capitalizing on the proposed architecture and by assuming sparse wireless channels in the beamspace domain, the authors introduce an alternating optimization approach for the explicit estimation of the channel gains by relaying on a single RF chain. Simulation results demonstrate the channel estimation accuracy and achievable performance of the proposed solution as a function of the number of training symbols and the number of RIS reflecting elements. \subsection{Performance Evaluation} Since their inception, RISs have been under study for unveiling their fundamental performance limits and the impact of the imperfect knowledge of various systems parameters on their achievable performance. In this context, several exact, approximate, and asymptotic analytical frameworks have been developed in order to quantify the advantages and limitations of RISs in different network scenarios. In \cite{Zhang2019e}, the authors study the impact of the finite resolution of the RIS phase shifts on the achievable performance. In particular, the authors introduce an approximated expression of the achievable data rate of an RIS-aided communication system, and derive the minimum number of phase shifts that is necessary in order to guarantee a data rate degradation constraint. In \cite{Hu2018b}, the authors study the capacity degradation that stems from potential hardware impairments in RIS-aided systems. In the absence of hardware impairments, the first-order derivative of the capacity with respect to the surface-area is shown to be proportional to the inverse of it. In the presence of hardware impairments, the latter performance metric is degraded. The authors introduce a model for the hardware impairments, and derive the effective noise density and the capacity loss in closed-form. The authors investigate distributed implementations for RIS-aided wireless systems as well, and show that the impact of hardware impairments can be reduced due to the smaller size of each RIS. In \cite{Jung2018}, the authors study the asymptotic rate of an RIS-based uplink channel in which an RIS is equipped with a large number of reflecting elements. Also, the authors take channel estimation errors and spatially correlated multi-user interference in account. It is shown that channel hardening effects occur, similar to massive MIMO systems. Moreover, it is shown that the impairments due to thermal noise, interference, and channel estimation errors become negligible as the number of RIS reflectors increases. This leads to results comparable with those of massive MIMO systems, but at a reduced deployment area and costs. In \cite{Jung2019}, the authors study the asymptotic optimality of the achievable rate of a downlink RIS-aided system. In order to increase the achievable system sum-rate, the authors propose a modulation scheme that can be used in an RIS-aided system without interfering with existing users. The authors study the average symbol error probability and introduce a resource allocation algorithm that jointly optimizes the scheduling of users and the power control at the transmitter. The proposed asymptotic analysis is validated with the aid of numerical simulations. In \cite{Nadeem2019}, the authors study the downlink channel of a single-cell multi-user system in which a base station equipped with multiple antennas communicates with several single-antenna users through an RIS. The minimum signal-to-interference+noise-ratio (SINR) among the mobile users is asymptotically analyzed, by considering the case studies in which the line-of-sight channel matrix between the base station and the RIS has unit rank and full rank. In the unit rank case, the minimum SINR is shown to be bounded by a quantity that goes to zero as the number of users increases. In the full rank case, on the other hand, deterministic approximations are derived and are used to optimize the RIS phase shifts by using the gradient ascent method. In \cite{Zhang2019c}, the authors consider a single-user multi-RISs link communication system The RIS phase shifts are adapted to the line-of-sight components of the propagation channels. The outage probability of this system model is derived and it is shown that it decreases as the number of RISs and as the number of reflecting elements at each RIS increase. Moreover, the outage probability is characterized in the high signal-to-noise-ratio regime, and it is proved that it decreases with the power of the line-of-sight links. In \cite{basar2019transmission}, the author introduces a general mathematical framework for the calculation of the symbol error probability of network scenarios in which an RIS is used as a reflector and as a transmitter. With the aid of numerical simulations, the author compares RIS-based systems with and without the knowledge of channel phases. In \cite{jung2019reliability}, the authors study the distribution of the uplink sum-rate of an RIS-based system. Leveraging the derived asymptotic expression of the rate, the authors introduce an analytical framework for computing the outage probability. The authors show that the proposed asymptotic analysis is in close agreement with numerical simulations, under the assumption of a large number of antennas and devices. In \cite{kudathanthirige2020performance}, the authors compute the outage probability, the average symbol error probability, and the achievable rate of an RIS-aided system. It is proved that the accuracy of the obtained analytical expressions becomes tighter as the number of RIS elements grows large. The achievable diversity order is quantified by deriving single-polynomial approximations in the high signal-to-noise-ratio regime. The diversity order is shown to be equal to the number of RIS elements. In \cite{badiu2019communication}, the authors study the transmission through an RIS in the presence of phase errors. The authors show that the RIS-based composite channel is equivalent to a point-to-point Nakagami fading channel. This equivalent representation allows the authors to perform theoretical analysis of the performance and to study the interplay between the performance, the distribution of phase errors, and the number of reflectors. Numerical evaluation of the error probability for a limited number of reflectors confirms the theoretical prediction and shows that the performance of RISs is remarkably robust against the phase errors. In \cite{psomas2019low}, the authors present an analytical framework for the performance evaluation of random rotation-based RIS-aided communications. Under this framework, the authors propose four low-complexity and energy efficient techniques based on two approaches: A coding-based and a selection-based approach. Both approaches depend on random phase rotations and require no channel state information. In particular, the coding-based schemes use time-varying random phase rotations in order to produce a time-varying channel. The selection-based schemes select a partition of the RIS elements at each time slot based on the received signal power at the destination. Analytical expressions for the outage probability and energy efficiency of each scheme are derived. The authors demonstrate that all schemes can provide significant performance gains and full diversity order. In \cite{Guo20CL}, the authors study an RIS-assisted MISO system in which a base station equipped with multiple antennas arranged in a uniform rectangular array serves a single-antenna user with the help of an RIS equipped with multiple elements arranged in a uniform rectangular array. The authors consider a Rician fading model, where the non-line-of-sight components vary slowly and the line-of-sight components do not change. To reduce the overhead for channel estimation and phase adjustment, the authors adopt a fixed maximum-ratio transmission scheme at the base station, fixed phase shifts at the RIS, and a constant rate transmission. The authors obtain analytical expressions of the outage probability and optimize the RIS phase shifts based on them. Based on the obtained analytical framework, the authors analyze the impact of several key system parameters on the optimal outage probability. In \cite{basar2019reconfigurable}, the authors revisit the multipath fading phenomenon in the context of RISs. In particular, the authors investigate the feasibility of eliminating or mitigating the multipath fading effect, which originates from the movement of mobile receivers, with the aid of RISs. The authors show that the rapid fluctuations in the received signal strength due to the Doppler effect can be effectively reduced by using real-time tunable RISs. Also, the authors prove that the multipath fading effect can be eliminated if all available reflectors are coated with RISs, as well as that the presence of a few RIS-coated reflectors can significantly reduce the Doppler spread and the deep fades in the received signal. In \cite{ozdogan2020using}, the authors study RISs in order to improve the rank of wireless channels. One of the classical bottlenecks of point-to-point MIMO communications is that the capacity gains provided by spatial multiplexing are large in the high signal-to-noise-ratio regime. However, the latter regime usually occurs in line-of-sight scenarios in which the channel matrix has a low rank, and, therefore, it does not support spatial multiplexing. The authors demonstrate that an RIS can be used and optimized in line-of-sight scenarios in order to increase the rank of the channel matrix, which leads to substantial capacity gains. In \cite{xu2019discrete}, the authors study an RIS-aided downlink communication system. The RIS is equipped with $B$-bit discrete phase shifters and the base station exploits low-resolution digital-to-analog converters. Without knowledge of the channel state information, the authors propose a practical phase shift design method whose computational complexity depends on $B$, but it is independent of the number of RIS reflecting elements. The authors compute a tight lower bound for the asymptotic rate of the users. As the number of reflecting elements increases, the authors prove that the asymptotic rate saturates because the received signal power and the quantization noise of the digital-to-analog converters increase. Compared with the optimal continuous phase shift design with perfect channel state information, the authors prove that the proposed design asymptotically approaches the ideal benchmark performance for moderate to high values of $B$. In \cite{cao2019capacity}, the authors analyze the performance of a distributed RIS-aided large-scale antenna system by formulating an upper bound expression of the ergodic capacity. The authors provide an asymptotic optimal phase shift design in order to maximize the ergodic capacity, and they propose a novel greedy scheduling scheme that takes the scheduling fairness into account. With the aid of simulations, the authors show that the analytical upper bounds are sufficiently accurate, and they validate that the proposed scheduling scheme achieves almost the same ergodic capacity as classical greedy scheduling algorithms. In \cite{hu2019spherical}, the authors consider three-dimensional RISs that are deployed as spherical surfaces. Compared with two-dimensional RISs, the authors prove that spherical RISs are capable of offering wider coverage, simpler positioning techniques, and a more flexible deployment. In \cite{zhang2020intelligent}, the authors investigate the capacity region of a multiple access channel in which two users send independent messages to an access point that is aided by $M$ reflecting elements. The authors study two practical deployment strategies: A distributed deployment in which the $M$ reflecting elements form two RISs that are deployed in the vicinity of two users; and a centralized deployment in which the $M$ reflecting elements are deployed in the vicinity of the access point. As for the distributed deployment, the authors derive the capacity region in closed-form. As for the centralized deployment, the authors derive a capacity region outer bound and propose an efficient rate-profile based method to characterize an achievable rate region. Based on the obtained analytical frameworks, the authors show that the centralized deployment outperforms the distributed deployment under practical channel setups, and that the capacity gain is higher when the user rates are asymmetric. In \cite{lyu2020spatial}, the authors characterize the spatial throughput of a single-cell multiuser system aided by multiple RISs that are randomly deployed in the cell. By using analysis and simulations, the authors prove that an RIS-aided system outperforms full-duplex relaying in terms of spatial throughput, provided that the number of RIS elements exceeds a certain value. Moreover, the authors show that different deploying strategies for RISs and relays should be adopted for their respective throughput maximization. Finally, it is shown that, for a given total number of reflecting elements, the system spatial throughput increases if fewer RISs, each having a larger number of reflecting elements, are deployed. However, this comes at the cost of higher spatially varying user rates. In \cite{williams2019communication}, the authors consider an RIS that is made of active elements and that is used as a transmitter. The RIS is modeled as a collection of tiny closely spaced antenna elements. Due to the proximity of the elements, mutual coupling arises. The authors introduce analytical expressions for the mutual coupling of two types of planar arrays. The singular values of the mutual coupling matrix is shown to approach zero as the antenna element density increases. When the spacing between elements becomes small (smaller than half a wavelength), the authors show that the directivity surpasses the conventional directivity equal to the number of antennas, as well as the gain that is obtained when modeling the surface as a continuous one. The authors show that the gain is theoretically unbounded as the element density increases for a constant aperture. In \cite{wang2020intelligent}, the authors study the feasibility of adopting RISs for improving the beamforming gain and throughput of uplink massive MIMO communications. The authors show that the favorable propagation property of conventional massive MIMO systems no longer holds in the presence of RISs. This is because each RIS element reflects the signals from all the users to the base station via the same channel, thus making the channels correlated. As a result, a maximal ratio combining receive beamforming leads to strong inter-user interference and low user rates. To tackle this challenge, the authors propose a novel zero-forcing beamforming strategy that efficiently nulls the interference. By using this approach, the authors show that RIS-assisted massive MIMO systems can achieve a higher throughput compared with their counterpart that does not use RISs. \subsection{Stochastic Geometry Based Analysis} Random spatial processes are considered to be the most suitable analytical tool to shed light on the ultimate performance limits of innovative technologies when applied in wireless networks and to guide the design of optimal algorithms and protocols for attaining such ultimate limits. In particular, random spatial processes have been successfully applied to the analysis of cellular networks, multi-tier cellular networks, millimeter-wave cellular networks, multi-antenna cellular networks, wireless information and power transfer, energy efficiency optimization, etc. \cite{SG_Jeff}, \cite{SG_MDR_1}, \cite{SG_MDR_2}, \cite{SG_MDR_3}, \cite{SG_MDR_4a}, \cite{SG_MDR_4}, \cite{SG_MDR_7}, \cite{SG_MDR_5}, \cite{SG_MDR_6}. Despite the many results available, fundamental issues remain open. In the current literature, in particular, the environmental objects are modeled as entities that can only attenuate the signals, by making the links either line-of-sight or non-line-of-sight. Modeling anything else is acknowledged to be difficult. Modeling reflections, for example, either according to the conventional law of reflection or to the generalized law of reflection, can be considered to be an open and challenging research issue to tackle. Due to the importance of quantifying the performance gains offered by RISs in large-scale wireless networks, some researchers have recently attempted to fill this fundamental research gap. In \cite{MDR2019_Eurasip}, the authors model the environmental objects with a modified random line process of fixed length and with random orientations and locations. Based on the proposed modeling approach, the authors introduce the first analytical framework that provides one with the probability that a randomly distributed object that is coated with an RIS acts as a reflector for a given pair of transmitter and receiver. In contrast to the conventional network setup where the environmental objects are not coated with RISs, the authors prove that the probability that the typical random object acts as a reflector is independent of the length of the object itself. In \cite{Hou2019}, the authors consider a MIMO system that is intended to provide wireless services to randomly roaming users, and they analyze the achievable performance by utilizing stochastic geometry. Each user is assumed to receive the superposed signals reflected by multiple RISs. The objective is to serve multiple users by jointly designing the beamforming weights at the RISs and the receiver weights vectors at the users, respectively. The authors derive closed-form expressions of the outage probability and the ergodic rate of the users, and their corresponding diversity orders. The analytical results demonstrate that the specific fading environments between the RISs and users have almost no impact on the diversity order attained. In \cite{kishk2020exploiting}, the authors use tools from stochastic geometry in order to study the effect of large-scale deployment of RISs on the performance of cellular networks. In particular, the authors model the blockages using a line Boolean model. The authors focus their attention on how equipping a subset of the blockages with RISs can enhance the performance of a cellular network. The authors derive the ratio of the blind-spots to the total area, and the probability that a typical mobile user associates with a base station in the presence of an RIS. Also, they derive the probability distribution of the path-loss between the typical user and its associated base station. Based on the proposed analytical framework, the main conclusion drawn by the authors unveils that the deployment of RISs is capable of highly improving the coverage regions of cellular base stations. \subsection{Optimization and Resource Allocation} Optimization of the system radio resources is one of the most researched topics in the context of RIS-based systems. A significant share of research articles has considered the problem of passive and active beamforming in MISO systems, i.e., the optimization of the transmit (active) beamforming and the (passive) RIS phase shifts, by resorting to the popular tool of alternating maximization in order to handle the non-convexity of the optimization problem. These papers are reviewed in the first sub-section. In the second sub-section, we review the use of other optimization techniques for solving the problem of active and passive beamforming in MISO systems. Research contributions on other resource allocation problems are discussed in the third sub-section. In the fourth sub-section, we summarize the notable scenario in which RISs can only apply discrete/quantized phase shifts. In the fifth sub-section, we report some recent research directions in the context of resource optimization for RIS-based networks. \textit{1) Passive / Active Beamforming in MISO Systems by Using Alternating Optimization}\label{Sec:RA1}\hfill\\ \textbf{Rate and Energy Efficiency}. In \cite{Huang_ICASSP,ZapTWC2019}, the authors consider the maximization of the spectral and energy efficiency in a multi-user MISO downlink network, by alternatively optimizing the base station beamforming and the RIS phase shifts. The power allocation problem is optimally solved by a water-filling-like solution, while two methods are developed for optimizing the RIS phase shifts. The first method employs a gradient search approach, while the second method exploits the framework of sequential optimization. Both methods provide phase shifts allocations that are stationary points of the spectral and energy efficiency. Moreover, numerical results show that the use of RISs significantly improves the energy efficiency compared to the use of amplify-and-forward relays, while a gap is observed with respect to the spectral efficiency. This is due to the fact that RISs are passive devices, while amplify-and-forward relays are able to apply signal amplification. In \cite{Abeywickrama2019}, the authors develop a phase shift model that relates the RIS phase shifts to the amplitude of the reflection coefficient. A single-user MISO link is considered, and, based on the new phase shift model, the problem of maximizing the system achievable rate with respect to the transmit beamforming and to the RIS phase shifts is formulated. In order to cope with the non-convexity of the problem, alternating optimization is employed to obtain a low-complexity algorithm, in which the transmit beamforming and the RIS phase shifts are iteratively optimized. In \cite{Yxu2020resource}, the authors consider the downlink of an RIS-enabled heterogeneous network, in which a multiple-antenna base station serves single-antenna users. In this context, the authors develop an algorithm that jointly allocates the base station transmit power and the RIS phase shifts, in order to maximize the SINR and the sum-rate at the small cell users, subject to a minimum SINR constraint on the rate of the macro-cell users. An algorithm based on alternating maximization coupled with semi-definite relaxation is developed to tackle the sum-rate maximization problem, by trading off complexity and optimality. In \cite{xie2019max}, the authors investigate an RIS-aided multi-cell MISO system, with the objective of maximizing the minimum weighted SINR at all users by jointly optimizing the base station beamforming and the RIS phase shifts, subject to individual power constraints at the base station. The authors propose an algorithm to tackle this problem based on the alternating optimization framework, wherein the base station beamforming and the RIS phase shifts are alternatively optimized. The beamforming sub-problem is formulated as a second-order-cone program, while the optimization of the RIS phase shifts is tackled by leveraging semi-definite relaxation and successive convex approximation. In \cite{gao2020reconfigurable}, the authors consider the problem of maximizing the spectral efficiency in RIS-aided MISO systems under nonlinear proportional rate constraints. The problem is tackled by alternatively optimizing the transmit power at the base station and the reflecting phase shifts at the RIS, which enables the authors to develop a practical algorithm even though no optimality properties can be guaranteed. Numerical simulations based on the proposed alternating optimization algorithm show that RISs are beneficial for improving the network data rate. In \cite{Pan2019b}, the authors study the downlink of a MIMO multi-cell system, wherein an RIS is deployed at the boundary between multiple cells. In this context, the authors tackle the problem of weighted sum-rate maximization, by alternating optimization of the base station beamformer and the RIS phase shifts. The beamformer optimization subproblem is obtained in closed form, for fixed RIS phase shifts. Instead, two efficient, but sub-optimal, algorithms are proposed for optimizing the RIS phase shifts, for fixed beamformers, by leveraging the sequential optimization and the complex circle manifold methods. Both algorithms yield first-order optimality. In \cite{Guo2019}, the authors address the problem of weighted sum-rate maximization in a multi-user RIS-based network. The problem is tackled by resorting to alternating optimization, in which the beamforming a the base station is optimized for fixed RIS phase shifts, and then the RIS phase shifts are optimized by keeping fixed the base station beamforming. Lagrangian duality is coupled with fractional programming methods for beamforming optimization at the base station, while three closed-form allocations of the RIS phase shifts are proposed. In \cite{Zhou2019b}, the authors consider a MISO multi-group multicast system in which an RIS is used to assist the communication. The authors study the problem of optimizing the base station precoding matrix and the RIS reflection coefficients for sum-rate maximization. The resulting optimization problem is first approximated by means of a concave lower bound of the objective function, which is then optimized by alternating optimization between the BS precoding and the RIS phase shifts. Both subproblems are second-order cone programming problems, which can be solved by convex optimization theory. Moreover, the use of sequential optimization is utilized in order to formulate approximate problems that can be solved in closed-form. In \cite{Yang2019}, the authors study an RIS-aided system model and propose a practical transmission protocol and channel estimation algorithm, by assuming an orthogonal frequency division multiplexing (OFDM) transmission scheme and a frequency-selective channel. The problem of maximizing the achievable rate by jointly optimizing the transmit power allocation and the RIS reflection coefficients is analyzed. The resulting optimization problem is non-convex, and the authors propose an efficient algorithm by solving the power allocation problem and the optimization of the phase shifts in an iterative manner. Simulation results show that RISs significantly improve the performance of OFDM systems. In \cite{Li2019c}, the authors study an RIS-enhanced wide-band multiuser OFDM-based MISO system. The transmit beamformer and the RIS phase shifts are optimized, in order to maximize the average sum-rate over all subcarriers. The problem is tackled by exploiting the connection between the sum-rate maximization and the mean square error minimization, which is used to equivalently reformulate the problem and to tackle it by using alternating optimization. In \cite{Yang2019c}, the authors consider an RIS-aided OFDM-based system and tackle the problem of maximizing the system rate by optimizing the reflection coefficients over different time slots within each channel coherence block. The resulting optimization problem is shown to be non-convex, and it is tackled by using alternating optimization with respect to the resource block assignment, the transmit power over each resource block, and the RIS phase shifts. Numerical results show that RISs are capable of increasing the system rate. \textbf{Other performance metrics}. In \cite{Han2019}, the authors address the problem of power control for physical layer broadcasting in the downlink of a multi-user network. In particular, the authors design the base station transmit beamforming and the RIS phase shifts by using alternating optimization, in order to minimize the base station power consumption subject to a minimum signal-to-noise ratio constraint for the mobile users. Given the sub-optimality of alternating optimization, a lower-bound of the optimal solution is derived for benchmarking purposes. Simulation results show that the proposed method approaches the lower bound as the number of RIS reflecting elements increases. In \cite{Wu2019b}, the authors address the problem of minimizing the base station power consumption with respect to the base station beamformer and the RIS phase shifts, subject to minimum SINR constraints at the receivers. The resulting problem is tackled by using alternating optimization in order to obtain a practical optimization method, at the price of sacrificing optimality. A power scaling law for RIS-based links is derived, and it is shown that the received power scales with the square of the number of RIS reflecting elements. In \cite{zhou2020framework}, the authors consider an RIS-aided multi-user MISO system and investigate the problem of robust beamforming under the assumption of imperfect knowledge of the cascaded channel from the base station to the users. Alternating optimization is adopted to minimize the transmit power subject to worst-case rate constraints under the assumption of a bounded channel error model, and subject to rate outage probability constraints under a statistical channel state information error model. The results reveal that the number of RIS elements may have a negative impact on the system performance if the cascaded channel is not properly estimated. In \cite{shao2020minimum}, the authors study the symbol error probability of an RIS-aided multiuser MISO downlink network. An expression of the symbol error probability is derived and alternating optimization is used to optimize the symbol-level base station precoder and the RIS phase shifts. The resulting algorithm is guaranteed to yield a stationary solution for the non-convex symbol error probability minimization problem. Simulation results demonstrate that the use of RISs reduces the bit error probability, especially if a large number of RIS elements is deployed. In \cite{liu2019joint}, the authors consider the problem of joint symbol-level precoding and reflection coefficients design in RIS-enhanced multi-user MISO systems. The authors propose iterative algorithms to solve the power consumption minimization and quality of service balancing problems. Symbol-level precoding and RIS phase shifts are designed by using alternating optimization and the gradient projection and Riemannian conjugate gradient algorithms, in order solve the resulting sub-problems. The results confirm that the employment of RISs in systems in which symbol-level precoding is used can provide more efficient multi-user interference exploitation by intelligently manipulating the multi-user channels. In \cite{jiang2019over}, the authors propose to employ RISs with the aim of improving the performance of over-the-air computation in wireless multi-user networks, thereby achieving ultra-fast data aggregation. The authors propose an alternating minimization approach to optimize the transceiver and the RIS phase shifts. The resulting non-convex quadratically constrained quadratic sub-problem is formulated as a rank-one constrained matrix optimization problem, which is tackled via the matrix lifting method. In \cite{Zhou2019}, the authors perform the robust design of an RIS-aided multiuser MISO system wherein only imperfect channel state information is available for optimization purposes. The considered problem consists of minimizing the transmit power with respect to the base station beamformer and the RIS phase shifts, under the constraint of achievable rate guarantees for each user and for all possible channel error realizations. By leveraging some approximations, the considered resource allocation problem is transformed into a more tractable form, which is then tackled by solving a sequence of semidefinite programming subproblems that can be efficiently solved. \textit{2) Design of Passive / Active Beamforming in MISO Systems by Using Other Optimization Techniques}\label{Sec:RA2}\\ \hfill In \cite{guo2019model}, the authors consider a single-user MISO downlink wireless communication system, wherein multiple RISs are deployed to aid the communication. The authors tackle the problem of optimizing the phase shift matrices of all the RISs by assuming that only statistical channel state information is available. The resulting optimization problem is solved by means of the stochastic successive convex approximation method. Numerical results show that the proposed algorithms significantly outperform the random phase shift scheme, especially when the channel randomness is limited. In \cite{li2020weighted}, the authors consider a wireless network wherein multiple RISs are deployed to cooperatively assist the communication between a multi-antenna base station and multiple single-antenna cell-edge users. The goal is to maximize the weighted sum rate of all cell-edge users by jointly optimizing the base station transmit beamforming and the RISs phase shifts. Optimal beamforming at the base station is found by using the Lagrangian method, while the RIS phase shifts are obtained based on the Rienmann manifold conjugate gradient method. In \cite{Yu2019}, the authors maximize the spectral efficiency of an RIS-aided point-to-point MISO system. Transmit beamforming and RIS phase shifts are optimized by resorting to iterative methods and manifold optimization techniques. Two suboptimal but low-complexity algorithms are developed. Numerical results reveal that deploying large-scale RISs in wireless systems provides higher spectral and energy efficiency than increasing the size of the transmit antenna-array at the base station. This shows how RIS can be effectively used to reduce the number of antennas deployed at the transmitter and receiver, which is an expensive part of a communication system. In \cite{Li2019b}, the authors consider a massive MIMO system, in which multiple RISs equipped with a large number of reflectors are deployed to assist a base station that serves a small number of single-antenna users. The problem of maximizing the minimum SINR at the users is tackled by jointly optimizing the transmit precoding vector and the RISs phase shifts. The problem is converted into an RIS-user association problem, for which an exhaustive search scheme and a greedy-based search scheme are proposed. In \cite{jia2020analysis}, the authors consider the design of an RIS-assisted system in which a multi-antenna base station serves a single-antenna user with the help of an RIS in the presence of interference generated by another multi-antenna base station serving its own single-antenna user. A tractable expression of the ergodic rate is obtained and it is used as the objective function for optimizing the RIS phase shifts. The optimization is performed by exploiting the parallel coordinate descent algorithm, which, in general, converges to a stationary point of the considered resource allocation problem. In \cite{razavizadeh20203d}, the authors discuss the problem of using three-dimensional beamforming in RIS-empowered wireless networks. The authors, in particular, propose a new scheme that provides more degrees of freedom in designing and deploying RIS-based networks. The authors consider a base station equipped with a full dimensional array of antennas, which optimizes its radiation pattern in the three dimensional space in order to maximize the received signal-to-noise-ratio at a target user. The tilt and azimuth angles of the base station and the phase shifts at the RIS are jointly optimized. The authors study the impact of the number of reflecting elements at the RIS, by taking into account the effect of the angle of incidence of signal received by the RIS. In \cite{yan2019passive}, the authors investigate the problem of passive beamforming and information transfer in the context of an RIS-aided MIMO system. An RIS is used for enhancing the primary communication while at the same time transmitting a second data stream by adjusting the state of the reflecting elements. The RIS phase shifts are optimized for sum-capacity maximization, by formulating the problem as a two-step stochastic program that is solved by leveraging the stochastic average approximation algorithm. In \cite{yu2020optimal}, the authors investigate the design of an RIS-assisted single-user MISO wireless communication system, by jointly optimizing the beamformer at the base station and the phase shifts at the RIS. The resulting non-convex optimization problem is tackled by resorting to the branch-and-bound algorithm, which enables the authors to handle the non-convex unit modulus constraints that need to be enforced on the RIS phase shifts, at the expense of an exponential complexity of the overall optimization algorithm. \textit{3) Design of Other RIS-Based Wireless Scenarios}\label{Sec:RA3}\\ \hfill In \cite{gao2020reflection}, the authors consider the problem of joint transmit power allocation and RIS phase shifts optimization in RIS-aided peer-to-peer communication networks. The objective is to jointly select a sparse passive beamforming matrix and allocate the transmit power such that the minimum SINR is maximized, subject to a maximum transmit power constraint and to RIS reflection coefficients constraints. The parallel alternating direction method of multipliers is employed to tackle the resulting non-convex resource optimization problem. In \cite{zhang2020joint}, the authors introduce the concept of RIS-aided cell-free network, which is aimed at improving the network capacity at a low cost and power consumption. In a wideband scenario, the authors formulate the problem of optimizing the base station beamforming and the RIS phase shifts, with the aim of maximizing the weighted sum-rate under a transmit power constraint at the base station and under unit-modulus phase shifts constraints at the RIS. A general joint precoding framework is proposed to solve the resulting problem. In \cite{zhou2019ris}, the authors propose to use RISs for off-shore wireless communications. In particular, the authors assume that an RIS is placed off-shore to facilitate the communication between single-antenna ships and a multi-antenna coastal base station. In this context, the article considers the problem of optimizing the system sum-rate with respect to the base station beamforming, the RIS phase shifts, and the service time allocated to each ship. The resulting non-convex problem is tackled by means of alternating optimization, whose performance is numerically analyzed to reveal that it yields comparable performance to the case in which fully digital antenna-arrays are used. In \cite{he2020coordinated}, the authors consider a distributed RIS-empowered communication network architecture, in which multiple source-destination pairs communicate through multiple distributed RISs. In this scenario, the authors study the problem of maximizing the network achievable sum-rate as a function of the transmit power vector at the sources and the phase shift matrix at the distributed RISs. The resulting non-convex problem is tackled by employing alternating optimization, in which each sub-problem is cast as a fractional programming problem. In \cite{xu2020resource}, the authors consider an RIS-based cognitive radio communication system, and focus their attention on the problem of optimizing the sum-rate of the secondary system as a function of the downlink transmit beamformers at the base station and the phase shifts at the RIS, and under quality of serice constraints for the primary system. The resulting optimization problem is non-convex due to the unit-modulus constraints imposed to the RIS reflection coefficients. A practical iterative optimization method is developed by using the alternating optimization algorithm with respect to the base station beamformer and the RIS phase shifts. In \cite{atapattu2020reconfigurable}, the authors consider a wireless system in which two-way communications take place between a pair of users, with the help of an RIS. Reciprocal and non-reciprocal channels are considered, and the RIS phase shifts are optimized in order to maximize the SINR at the two receivers. In the reciprocal case, the optimal RIS phase shifts are determined. In the non-reciprocal case, the problem turns out to be more difficult and is tackled by means of semidefinite relaxation. In both cases, the special case of an RIS with a single element is investigated, and optimal solutions and expressions of the system outage probability are calculated. In \cite{cao2020sum}, the authors consider a device-to-device communication system in which an RIS is employed to enhance the communication between the device-to-device users who underlay the cellular users. The authors formulate the problem of sum-rate maximization of the device-to-device users as a function of the transmit powers, the receive linear filters, and the RIS phase shifts. These three blocks of variables are optimized iteratively by using the alternating maximization method. Closed-form solutions for the transmit powers and receive filters are provided, while the semi-definite relaxation method is exploited for optimizing the RIS phase shifts. Numerical results demonstrate that the use of RISs significantly improves the system sum-rate. In \cite{du2019multiple}, the authors consider a wireless system in which a multiple-antenna base station sends a multicast transmission to single-antenna mobile users, with the help of an RIS. The authors address the problem of maximizing the system capacity as a function of the transmit covariance matrix and the RIS phase shifts. Sub-gradient and gradient descent methods are adopted to tackle the resulting optimization problem. In addition, asymptotic analysis is performed in order to derive the order of growth of the maximum capacity in the regime of an infinite number of RIS reflecting elements, base station antennas, and mobile users. In \cite{yuan2019intelligent}, the authors consider an RIS-aided cognitive radio network, wherein multiple RISs are used to improve the achievable rate of secondary users without disturbing the existing primary users in the network. The transmit beamforming vector at the secondary user transmitter and the reflecting coefficients at each RIS are jointly optimized under a total transmit power constraint at the secondary user and under an interference temperature constraints at the primary user. The impact of perfect and imperfect channel state information is analyzed. In \cite{ye2019joint}, the authors consider the joint design of the RIS phase shifts and the full rank precoder at the transmitter in a point-to-point RIS-assisted MIMO system. The problem of minimizing the error probability is tackled by employing the alternating maximization method, wherein the two sub-problems are globally solved. In order to develop resource allocation algorithms with lower complexity, approximate solutions for the two sub-problems are derived. Numerical results indicate that the lower-complexity methods can still provide satisfactory performance. In \cite{Ning2019b}, the authors study the maximization of the spectral efficiency in an RIS-assisted MIMO link. The transmit beamforming and the RIS phase shifts are optimized by converting the spectral efficiency maximization problem into the simpler problem of maximizing the sum of the gains of the different communication paths. This simplified problem is then tackled by resorting to the alternating direction method of multipliers. In \cite{sanchez2019iterative}, the authors address the uplink detection problem in the communication from multiple single-antenna users to an RIS that is connected to a central processing unit that performs data detection. The central processing unit acts as a receiver and applies a linear filter to the received signal. The authors determine the system sum-rate and derive an algorithm that yields the equalizer that maximizes the system sum-rate. Numerical results indicate that the considered RIS-based architecture outperforms traditional approaches based on matched filtering. In \cite{Hu2018}, the authors consider an RIS-aided wireless communication system, in which each RIS element has a separate signal processing unit and is connected to a central processing unit that coordinates the behavior of all RIS elements. The user assignments are optimized to maximize the sum-rate and the minimal user-rate. By constructing a cost matrix based on the received signal strength at each RIS element for each user, a weighted bipartite graph between the users and the RIS elements is obtained. Thanks to the constructed bipartite graph, the problem of optimal user assignments for sum-rate maximization is transformed into a linear sum assignment problem, and the problem of minimum user-rate maximization is transformed into a linear bottleneck assignment problem. \textit{4) Discrete Phase Shifts and Phase Quantization}\label{Sec:RA4} \\ \hfill In \cite{wu2019beamforming}, the authors address the problem of beamforming optimization under practical discrete phase shift constraints at the RIS. The transmit precoder at the access point and the discrete phase shifts at the RIS are jointly optimized to minimize the transmit power at the access point while meeting the individual SINR targets at the users. Optimal solutions and suboptimal solutions based on successive convex approximations are proposed. The authors show that RISs with one bit phase shifters are able to achieve the same asymptotic squared power gain as continuous phase shifts, but they are subject to a constant power loss. In \cite{omid2020irs}, the authors consider a large-scale MIMO system in which an that employ discrete phase shifts aids the downlink transmission. Passive precoding methods are used at the base station and at the RIS. The objective is to minimize the sum power of multi-user interference by jointly optimizing the RIS beamforming and the base stations precoding vectors. A trellis-based joint RIS and base station precoding design is introduced, according to which the base station precoding in each cell is performed individually. By applying stochastic optimization, a low-overhead trellis-based optimization technique is introduced, and performance improvements are obtained by minimizing the inter-cell and intra-cell interference. In addition, semi-definite relaxation is applied to develop benchmark methods for comparison. In \cite{han2019large}, the authors evaluate the ergodic spectral efficiency of an RIS-assisted large-scale antenna system. An upper-bound for the ergodic spectral efficiency is computed and it is utilized for optimizing the RIS phase shifts. In particular, the authors analyze the case study in which the RIS is capable of applying only discrete phase shifts and they evaluate the minimum number of quantization bits that are required in order to ensure an acceptable spectral efficiency. Numerical results show that a two bit quantizer is sufficient to ensure an ergodic capacity degradation of at most one bit/s/Hz. In \cite{li2019sum}, the authors consider an RIS-aided multi-user MISO downlink system. The objective is to maximize the system sum rate by jointly optimizing the transmit beamformer at the base station and the phase shifts at the RIS. The case studies with continuous and discrete RIS phase shifts are addressed. In order to tackle the resulting optimization problem, a smooth approximation of the objective function is derived and a block coordinate accelerated projected gradient algorithm is developed. Numerical simulations demonstrate that the proposed design achieves satisfactory performance, especially if the RIS is equipped with a large number of reflecting elements. In \cite{zhao2019intelligent}, the authors consider an RIS-aided multi-user system and design a two-timescale joint active and passive beamforming optimization approach. The RIS phase shifts are optimized leveraging the statistical channel state information of all links, while beamforming at the access point is performed based on the instantaneous channel state information of the effective channels of the users, which account for the optimized RIS phase shifts. This approach is used to maximize the system weighted sum-rate, under the assumption of discrete phase shift at the RIS. A penalty dual decomposition based algorithm is developed for the single-user and multi-user case studies. In \cite{BoyaDi20}, the authors study an RIS-based downlink multi-user multi-antenna system, in which the base station transmits signals to users via an RIS with limited-resolution phase shifters. The authors consider the practical case study in which only the large-scale fading gain is known at the transceivers. A hybrid beamforming scheme is proposed for sum-rate maximization, in which digital beamforming is performed at the base station and analog beamforming is employed at the RIS. The resulting sum-rate maximization problem is tackled by using alternating optimization. In \cite{Liu2019}, the authors address the problem of precoder design in an RIS-based multi-user MISO wireless system, in which the RIS phase shifts have a low resolution. The information to be transmitted is encoded into the configuration of the RIS phase shifts and the problem of designing a symbol-level RIS precoder that minimizes the maximum symbol error rate of single-antenna receivers is considered. Under the assumption that the symbol-level precoding vector has a one bit resolution, the resulting optimization problem is tackled by using relaxation methods coupled with the Riemannian conjugate gradient algorithm and the branch-and-bound method. In \cite{Wu2019c}, the authors consider a single-user system, in which an RIS with finite-resolution phase shifters aids the communication from a multi-antenna transmitter to a single-antenna receiver. The problem of transmit power minimization at the transmitter is analyzed, under a minimum signal-to-noise ratio constraint. The problem is tackled by using alternating maximization, by taking turn in optimizing the transmit beamforming and the RIS phase shifts. The authors show that the power gain at the receiver scales quadratically with the number of phase shifts of the RIS, but only in the limit of a large number of RIS reflecting elements. In \cite{Di2019}, the authors consider a downlink multi-user MISO system, in which an RIS is used to help a base station communicate with the downlink users. Under the assumption that the RIS can apply only discrete phase shifts, the sum-rate maximization problem is addressed by optimizing the digital beamforming at the base station and the discrete phase shifts at the RIS. The resulting resource allocation problem is tackled by an iterative algorithm based on alternating optimization. In \cite{mu2020capacity}, the authors investigate an RIS-assisted multi-user communication system, in which a single-antenna access point sends independent information to multiple single-antenna users with the aid of an RIS that is capable of applying discrete phase shifts. The authors consider the bi-objective maximization of the system ergodic capacity and the delay-limited capacity, and characterize the corresponding Pareto boundary. The authors show that the ergodic capacity can be achieved by using an alternating transmission strategy in which the RIS phase shifts are dynamically changed. In order to achieve the delay-limited capacity, the authors show that the RIS phase shift matrix needs to be fixed at a specific value. \textit{5) Overhead for Estimation and Control}\label{Sec:Perspectives} \\ \hfill All available works on resource optimization for RIS-based networks are focused only on the communication phase and assume that channel state information (perfect or imperfect) has been acquired already. This is the conventional approach in the context of resource allocation in wireless networks. In RIS-based systems, however, channel estimation and feedback affect the performance of resource allocation schemes in a more fundamental way than in other instances of wireless networks. For this reason, the design of RIS-based wireless networks requires, more than in any other wireless systems, the development of algorithms for joint channel estimation/feedback and system optimization. A first contribution in this direction has recently appeared in \cite{MDR_OverheadAware}. Therein, the authors derive an expression of the rate and energy efficiency of a single-user RIS-based MIMO system that explicitly accounts for the overhead due to channel estimation and feedback. Also, the authors introduce an optimization framework for the design of the transmit beamforming, the receive filter, the RIS phase shifts, and the power and bandwidth that are allocated for both channel feedback and data transmission phases. \subsection{Physical Layer Security} The premise of physical-layer security is to exploit the physical properties of wireless channels in order to enhance the communication security through appropriate coding and signal processing schemes. The analysis of the potential gains and advantages of RISs for enhancing the physical-layer security of communication links has recently attracted research interests and attention. In \cite{Chu2019}, the authors consider an RIS-aided wiretap channel model, and study the problem of minimizing the power consumption under a minimum secrecy rate constraint and by optimizing the transmit power and the RIS phase shifts. The resulting optimization problem is shown to be non-convex, and is tackled by means of semi-definite relaxation and alternating optimization between the transmit powers and the RIS phase shifts. A closed-form allocation strategy for the transmit beamformer is derived. In \cite{Cui2019}, the authors analyze the problem of secrecy rate optimization in an RIS-aided wiretap channel, in which a multi-antenna access point communicates with a single-antenna receiver in the presence of a single-antenna eavesdropper. The authors assume that exists a strong spatial correlation among the channels of the legitimate link and the eavesdroppers. The transmit beamforming and the RIS phase shifts are optimized by resorting to alternating optimization and semidefinite relaxation methods. In \cite{Feng2019b}, the authors consider a network scenario in which an RIS is used to help a base station equipped with a uniform linear antenna-array that transmits confidential signals to a single-antenna legitimate user in the presence of a single-antenna eavesdropper. The problem of secrecy rate maximization is addressed by optimizing the transmit beamforming and the RIS phase shifts. The authors introduce a sub-optimal but low-complexity optimization algorithm by leveraging quadratic transformations and manifold optimization techniques, whose convergence is theoretically proved. In \cite{Shen2019}, the authors study the problem of secrecy rate maximization in an RIS-assisted wiretap channel. The authors, assume a maximum transmit power constraint at the transmitter and unit modulus constraints for the RIS phase shifts. The problem is tackled by using alternating optimization, and, in particular, the transmit power control sub-problem is solved in closed-form, and the RIS phase shifts allocation sub-problem is solved in semi-closed form. The convergence of the proposed algorithm is guaranteed theoretically. In \cite{Feng2019}, the authors study the problem of secure transmissions in an RIS-aided wiretap channel while minimizing the system energy consumption. The authors analyze the case studies in which the channel between the transmitter and the RIS has unitary and full rank. The optimal transmit beamforming is obtained by using eigenvalue-based allocation, while the semi-definite relaxation algorithm and the projected gradient algorithm are used to compute the optimal RIS phase shifts. In \cite{Yu2019c}, the authors study an RIS-assisted wiretap channel, in which a multi-antenna transmitter communicates with a single-antenna receiver in the presence of an eavesdropper. The problem of secrecy rate maximization is considered with respect to the transmit beamformer and the RIS phase shifts. The resulting optimization problem is tackled by using alternating optimization and sequential optimization, which leads to an efficient but, in general, sub-optimal algorithm. In \cite{Guan2019}, the authors analyze a wiretap channel in which an RIS is used to aid a multi-antenna transmitter to communicate with a single-antenna receiver in the presence of multiple single-antenna eavesdroppers. The authors employ artificial noise for improving the system achievable secrecy rate. Alternating optimization is used for optimizing the transmit beamforming, the artificial noise jammer, and the RIS phase shifts. In \cite{Yu2019b}, the authors use artificial noise for ensuring secure communication in an RIS-assisted network. In particular, a multi-antenna access point exploits an RIS in order to serve multiple single-antenna legitimate users in the presence of multiple multi-antenna potential eavesdroppers, whose channel state information is not perfectly known at the access point. The access point makes use of artificial noise to jam the eavesdroppers and maximize the system secrecy rate. To solve this optimization problem, the authors develop an algorithm based on alternating optimization, successive convex approximation, and semidefinite relaxation. In \cite{Lu2019}, the authors study an RIS-based system in which the secrecy of the communication link is enhanced by making the signal transmission covert to potential eavesdroppers. This is achieved by using an RIS that focuses the transmit signal only towards the direction of the intended receiver. The authors substantiate the proposed approach in a system scenario in which a single-antenna transmitter communicates with a single-antenna receiver. In particular, the signal leakage towards a single-antenna eavesdropper is minimized by optimizing the transmit power and the RIS phase shifts. In \cite{Chen2019}, the authors study a downlink MISO system, in which the base station transmits independent data streams to multiple legitimate receivers in the presence of multiple eavesdroppers. By jointly optimizing the beamformers at the base station and the RIS phase shifts, the authors maximize the minimum secrecy rate under the assumption of continuous and discrete RIS phase shifts. The optimization problem is solved by using alternating optimization and the path-following algorithm. In \cite{hong2020artificial}, the authors consider a MIMO wireless communication system that employs physical layer security. The transmitter sends artificial noise in order to maximize the system secrecy rate. This is achieved by optimizing the precoding matrix at the transmitter, the covariance matrix of the artificial noise, and the phase shifts at the RIS under the assumption of a maximum transmit power limit and unit modulus constrains for the phase shifts. The optimization problem is tackled by using the block coordinate descent algorithm. In \cite{dong2020secure}, the authors consider an RIS-assisted Guassian MIMO wiretap channel, in which a multi-antenna transmitter communicates with a multi-antenna receiver in the presence of a multi-antenna eavesdropper. The secrecy rate is maximized by using an alternating optimization algorithm, which jointly optimizes the transmit covariance and the phase shifts at the RIS. The successive convex approximation algorithm is adopted to solve the optimization sub-problems. In \cite{jiang2020intelligent}, the authors study an RIS-based MIMO network, in which a multi-antenna access point communicates with a multi-antenna legitimate user in the presence of a multi-antenna eavesdropper. The authors investigate the joint optimization of the transmit covariance matrix at the access point and the phase shifts at the RIS, in order to maximize the system secrecy rate under the assumption of continuous and discrete RIS phase shifts. The optimization problem is tackled by applying alternating optimization to the transmit covariance matrix at the access point and to the phase shifts at the RIS. In \cite{wang2020angle}, the authors study the physical-layer security in a massive MIMO multicasting system. The authors propose an angle-aware user cooperation scheme that avoids direct transmission to the attacked user and relies on other users for cooperative relaying. The proposed scheme requires only the angle information about the eavesdropper. By considering an angular secrecy model to formulate the average secrecy rate of the attacked system, the authors use successive convex optimization to design the beamformer. In \cite{xu2019resource}, the authors consider the secure communication in RIS-aided MISO communication systems. To enhance physical layer security, artificial noise is transmitted from the base station in order to impair the eavesdroppers. The problem of jointly optimizing the phase shifts at the RIS and the beamforming vectors and artificial noise covariance matrix at the base station is investigated. The secrecy rate maximization problem is tackled by using non-convex optimization. In addition, a suboptimal algorithm based on alternating optimization, successive convex approximation, semidefinite relaxation, and manifold optimization is proposed. In \cite{lyu2020irs}, the authors consider a jammer that attacks a legitimate communication without using any internal energy to generate jamming signals. The jammer uses an RIS that controls the reflected signals in order to decrease the SINR at the legitimate receiver. Simulation results show that, although no energy is used, the proposed RIS-based jammer outperforms conventional active jamming attacks. In \cite{makarfi2019physical}, the authors study the physical layer security in a vehicular network that employs an RIS. Two network models are investigated: A vehicle-to-vehicle communication in which the transmitter employs an RIS-equipped access point, and a vehicular ad-hoc network in which an RIS-equipped relay in deployed in a building. Both system setups assume the presence of an eavesdropper and the average secrecy capacity is investigated. Numerical results show that the secrecy capacity is affected by the location of the RIS and the size of the RIS. \subsection{Non-Orthogonal Multiple Access} Non-orthogonal multiple access (NOMA) has received major attention for the design of radio access techniques in future wireless networks. The basic concept behind NOMA is to serve more than one user in the same resource block, e.g., time slot, subcarrier, spreading code, space. Based on this approach, NOMA promotes massive connectivity, lowers latency, improves user fairness and spectral efficiency, and increases reliability compared to orthogonal multiple access (OMA) techniques. The potential advantages and limitations of RISs in the context of NOMA-based networks have been investigated in a few recent papers. In \cite{Fu2019}, the authors analyze the use of RISs in the context of NOMA systems. Specifically, an RIS is used to enhance the downlink communication from a base station to mobile users. The base station beamforming and the RIS phase shifts are optimized in order to minimize the system total power consumption under the constraint of given rate requirements at the receivers. The problem is tackled by using alternating optimization and the difference of convex functions programming. The resulting algorithm is shown to be provably convergent but, in general, suboptimal. In \cite{Li2019}, the authors consider an RIS-aided NOMA-based downlink MISO channel. The authors minimize the total transmit power by optimizing the transmit beamforming vectors at the base station and the reflection coefficient vector at the RIS. This optimization problem is tackled by using semidefinite programming, second-order cone programming, and the alternating direction method of multipliers. A low-complexity algorithm based on zero-forcing transmission is proposed. In \cite{Mu2019}, the authors analyze the sum-rate optimization of an RIS-aided NOMA-based downlink MISO channel. In particular, the system sum-rate is maximized with respect to the base station beamformer and the RIS phase shifts. The problem is solved by using alternating optimization and by applying successive convex approximation methods. The case study of discrete phase shifts at the RIS is studied and a quantization-based scheme is proposed. In \cite{Yang2019b}, the authors maximize the minimum rate among the users of an RIS-assisted downlink NOMA system. The optimization problem is formulated in terms of the transmit beamforming vector and the RIS phase shifts. A user ordering scheme based on the signal strength of the combined channel is introduced, in order to decouple the user-ordering design and the beamforming design. The resulting non-convex problem is tackled by using alternating optimization and semi-definite relaxation methods. Single-antenna and multi-antenna system setups at the base station are analyzed. In \cite{zheng2020intelligent}, the authors compare the performance between NOMA and OMA. The authors optimize the RIS reflection coefficients, by assuming a discrete resolution for the phase shifts, by minimizing the transmit power of the access point under the assumption of some specified constraints for the user rates. It is shown that NOMA may underperform OMA in some network configurations. In \cite{ding2019simple}, the authors propose an RIS-based NOMA transmission scheme in which the number of users that can be served in each orthogonal spatial direction is larger compared with spatial division multiple access schemes. It is shown that, by employing an RIS, the directions of the channel vectors of the users can be effectively aligned and that this facilitates the implementation of NOMA. In \cite{ding2020impact}, the authors study the performance of two phase shifting designs, i.e., random phase shifting and coherent phase shifting, for application to RIS-assisted NOMA systems. Simulation results prove the accuracy of the obtained analytical results and are used to compare RIS-NOMA with respect to conventional relaying and RIS-OMA. In \cite{fu2019intelligent}, the authors study the downlink transmit power minimization problem in RIS-empowered NOMA networks, by jointly optimizing the transmit beamformer and the RIS phase shifts. The optimization problem is tackled by using alternating minimization. In particular, the underlaying subproblems are shown to be non-convex quadratic programs, and they are tackled by using difference of convex programming methods. In \cite{yue2020performance}, the authors consider a NOMA-based system in which a base station transmits a multiplex of signals to multiple users by means of an RIS. The performance of the system model is studied by assuming perfect and imperfect successive interference cancellation and a one bit coding scheme. Exact and asymptotic expressions of the system outage probability and ergodic rate are derived. From the obtained analytical frameworks, the authors show that RIS-NOMA outperforms RIS-OMA and conventional relaying schemes, and that the performance of RIS-NOMA improves if the number of reflecting elements increases. In \cite{zuo2020resource}, the authors study the downlink of an RIS-assisted NOMA system. In order to maximize the system throughput, the authors formulate an optimization problem as a function of the channel assignment, the decoding order of NOMA users, the transmit power, and the RIS reflection coefficients. The resulting optimization problem is non-convex, and a three-step alternating optimization algorithm is proposed to tackle it. In particular, the channel assignment problem is solved by using a many-to-one matching algorithm, the decoding order problem is solved by introducing a low complexity algorithm, and, finally, given the channel assignment and decoding order, the joint power allocation and reflection coefficient design is solved. The three sub-problems are solved iteratively until convergence. In \cite{zhu2019power}, the authors optimize the beamforming vectors and the RIS phase shifts in an RIS-assisted NOMA system. The authors propose an improved quasi-degradation condition under which RIS-NOMA achieves the same performance as dirty paper coding. The authors characterize the optimal beamforming of RIS-assisted NOMA and RIS-assisted zero-forcing schemes, by assuming a given RIS phase shift matrix. It is shown that NOMA always outperforms zero-forcing if the improved quasi-degradation condition is considered and the same RIS phase shift matrix is used. In \cite{hou2019reconfigurable}, the authors propose a priority-oriented design for enhancing the spectral efficiency of an RIS-aided NOMA network. Accurate and approximated closed-form expressions for the outage probability and the ergodic rate are derived. Numerical results show that the diversity order of the system can be enhanced by increasing the number of phase shifts of the RIS. \subsection{Internet of Things and Backscattering} In the broadest sense, the Internet of Things (IoT) encompasses everything connected to the Internet, but it is often used to define objects that talk to each other. The IoT is made up of massive deployments of devices, encompassing sensors, smart phones, wearables, etc., which are all connected together. One of the major open challenges for the IoT is the limited network lifetime, which is due to the massive deployment of devices that are powered by batteries of finite capacities. In this context, backscatter communication (or simply backscattering), which enables the transmission of information through the passive reflection and modulation of an incident radio wave, has emerged as a promising technology for enabling the connectivity of massive deployments of devices at a low power consumption and at a low complexity. In \cite{MDR_Survey_EURASIP}, the authors have elaborated on the potential applications and benefits of employing RISs for IoT applications. Since then, several authors have started researching on the applications of RISs in this context. In \cite{park2020intelligent}, the authors propose an RIS-aided phase shift backscatter communication system. The authors study the scenario in which the RIS is employed for transmitting secondary information data while relaying primary information data. This is obtained by employing the RIS to relay the primary information data through beamforming and by encoding the secondary information data onto the phase shifts. The spectral efficiency of the secondary system subject to a minimum spectral efficiency requirement for the primary system is analyzed, and it is shown that RIS-aided backscattering is capable of outperforming the system performance. In \cite{zhang2020large}, the authors propose an RIS-assisted symbiotic radio system. The joint design and optimization of the transmit beamformer and the reflecting phases at the RIS is studied, by minimizing the total transmit power under a rate constraint for the primary transmission and a signal-to-noise-ratio constraint for the IoT communication. Alternating optimization is adopted to tackle the resulting optimization problem. In \cite{ZhaoPerformanceAnalysis20}, the authors study an RIS-aided backscatter system in order to support ultra-reliable communications for IoT applications. By considering random and optimized phase shifts at the RIS, the authors compute the error probability, by using the moment generating function approach. Tight upper bounds are obtained for both independent and correlated channels. Numerical results unveil the impact on the achievable error performance of the number of reflecting elements of the RIS. In \cite{makarfi2019reconfigurable}, the authors analyze and RIS-aided IoT system over composite fading and shadowing channels. Exact and approximate expressions for the average capacity, average error probability, and outage probability are given. The impact of the transmit power, the fading and shadowing severity, and the size of the RIS is analyzed. \subsection{Aerial Communications} Over the last years, the use of Unmanned Aerial Vehicles (UAVs), commonly referred to as drones, has received significant attention from various industry sectors and research communities. This is mostly attributed to the broad range of UAV-enabled use cases in, e.g., agriculture, public protection, disaster relief, logistics, media production, mapping, etc. The transformation of UAVs into distributed aerial communication and computing platforms is gathering pace by leveraging research advancements in 5G and 6G technologies, edge computing, and machine learning. This transformation promises exciting and high impact use cases and innovations far beyond legacy UAV solutions. A few recent papers have started investigating the possible applications of RISs in the context of UAV-based communications. In \cite{Li2019d}, the authors study the joint design of the trajectory of an UAV and the beamforming design of an RIS in order to maximize the average achievable rate. To tackle the resulting non-convex optimization problem, the authors divide the optimization into two sub-problems that consist of optimizing the beamforming at the RIS and the trajectory of the UAV. The authors derive a closed-form solution for the beamforming vector for a given trajectory. A sub-optimal solution for the trajectory is obtained by using successive convex approximation methods. Numerical results demonstrate that the use of RISs enhances the average achievable rate. In \cite{Ma2019}, the authors consider the deployment of RISs on the walls of buildings and assume that they can be remotely configured by cellular base stations in order to coherently direct the reflected radio waves towards specific UAVs for increasing the received signal strength. By using standardized ground-to-air channel models, the authors analyze the signal gain at the UAVs, as a function of the height of the UAVs, and the size, altitude, and distance from base station of the RIS. The authors identify the optimal location (height and distance from the base stations) of the RIS that maximizes the performance. In \cite{lu2020enabling}, the authors introduce a three dimensional networking architecture, enabled by UAVs and RISs, in order to achieve panoramic signal reflections from the sky. The authors study the problem of maximizing the worst-case signal-to-noise ratio in a given coverage area, by jointly optimizing the transmit beamforming, and the placement and phase shifts of RIS-mounted UAVs. The resulting problem is non-convex and the optimization variables are coupled. To tackle this problem, the authors develop an efficient sub-optimal solution that exploits the similarity between optimization of the RIS phase shifts and the optimization of the analog beamforming of phased arrays. In \cite{Zhang2019d}, the authors consider a UAV-carried RIS in order to enhance the performance of millimeter-wave networks. In particular, the UAV-carried RIS is used to intelligently reflect signals from a base station towards a mobile outdoor user, while harvesting energy from the signals so as to power the RIS. To maintain a line-of-sight channel, a reinforcement learning approach is used to model the propagation environment, so that the location and reflection coefficient of the UAV-carried RIS are optimized to maximize the downlink transmission capacity. Simulation results show the advantages of using a UAV-carried RIS as compared with a conventional RIS, in terms of average data rate and achievable downlink line-of-sight connectivity. \subsection{Wireless Power Transfer} Wireless power transfer is the transmission of electrical energy without using wires as a physical link. In a wireless power transmission system, a transmitter (driven by electric power from a power source) generates a time-varying EM field towards a receiver that extracts power from the field and supplies it to an electrical load. The technology of wireless power transmission can eliminate the use of wires and batteries, thus increasing the mobility, convenience, and safety of an electronic device. Wireless power transfer has received major attention from the research community, and several authors are currently investigating the potential uses and applications of RISs in this context. In \cite{ZhengIRS20}, the authors consider an RIS that assists the transmission of a two-user cooperative wireless-powered communication network. The authors study the problem of maximizing the throughput, by jointly optimizing the phase shifts of the RIS, the transmission time, and the power allocation strategy. Numerical results show that the use of RISs can effectively improve the throughput of cooperative transmissions. In \cite{Pan2019}, the authors study a downlink MISO wireless network with simultaneous wireless and information power transfer, in which an RIS is employed for enhancing the wireless transfer capabilities of the system. The authors analyze the problem of maximizing the system weighted sum-rate with respect to the transmit precoding matrices of the base station and the phase shifts of the RIS. Alternating optimization is employed to tackle the resulting optimization problem, and, in particular, the authors propose two low-complexity iterative algorithms that converge to a first-order optimal point of the respective optimization sub-problem. In \cite{Tang2019}, the authors consider the downlink of a MISO system in which a base station sends information and energy signals to a set of receivers and an RIS is used to aid the information and energy transfer. In this setup, the base station beamformer and the RIS phase shifts are alternatively optimized with the aim of maximizing the minimum power received at all the energy-harvesting receivers, by fulfilling individual SINR constraints for the information receivers and a maximum transmit power constraint for the base station. The resulting optimization problem is tackled by using alternating optimization and semi-definite relaxation, thus obtaining a sub-optimal but efficient algorithm. In \cite{Wu2019d}, the authors analyze the downlink of a MISO system in which the simultaneous transmission of information and power is considered. In the considered system model, multiple RISs are deployed in order to aid the information and power transfer. The authors consider the problem of minimizing the transmit power of the base station through the optimization of the transmit precoders and the phase shifts of the RISs. The use of alternating optimization methods to tackle the problem is shown to be unsuitable and a penalty-based algorithm is proposed instead. In \cite{shi2019enhanced}, the authors analyze the downlink of an RIS-aided MISO system where simultaneous wireless information and power transfer is employed. The authors study the design of secure transmit beamforming and RIS phase shifts in order to maximize the harvested power. In order to solve the resulting non-convex optimization problem, two alternating iterative algorithms based on semi-definite relaxation and successive convex approximation are proposed. \subsection{Multiple-Access Edge Computing} Multi-access edge computing (MEC) is a network architecture concept that enables cloud computing capabilities and an information technology service environment at the edge of any network, e.g., a cellular network. The basic idea behind MEC is that, by running applications and performing related processing tasks closer to the customers, network congestion is reduced and applications perform better. MEC technology is designed to be implemented at the cellular base stations or at other edge nodes. It enables flexible and rapid deployment of new applications and services for customers. Recently, the application of RISs in this context has been investigated by some researchers. In \cite{Bai2019}, the authors consider a scenario in which single-antenna devices may decide to offload part of their computational tasks to the edge computing node via an RIS-aided multi-antenna access point. In this context, the authors formulate a latency minimization problem, by considering single-device and multi-device scenarios, in which constraints on the edge computing capabilities are imposed. Alternating optimization is used to tackle the optimization problem, by alternatively optimizing computing and communication operations. The computing sub-problem is solved optimally while only a first-order optimal solution is determined for the communication sub-problem. In \cite{Hua2019}, the authors consider an RIS-aided system model in which inference tasks generated from mobile devices are uploaded to and cooperatively performed by multiple base stations. The objective is to minimize the network power consumption as a function of the set of tasks performed by each base station, the base stations transmit and receive beamforming vectors, the transmit power of the mobile devices, and the RIS phase shifts. The resulting combinatorial problem is addressed by exploiting the group sparsity structure of the beamforming vectors and by employing alternating maximization to decouple the optimization variables. In \cite{cao2019intelligent}, the authors study an RIS-assisted MEC system model for application to the millimeter-wave frequency band. In particular, the RIS is employed to alleviate link blockage problems in an economical manner and to guarantee the real-time offloading of computing tasks. The objective is to minimize the uplink mobile power for all users while satisfying the offloading latency constraints, where the power of the individual devices, the multi-user detection matrix, and the beamforming coefficients of the RIS are jointly optimized. An alternating optimization framework is developed, in order to decompose the joint optimization of all coupled variables into tractable sub-problems. Simulation results highlight the benefits of using RISs in the context of MEC. In \cite{liu2020intelligent}, the authors consider the problem of computation offloading for MEC in a wireless network equipped with RISs. In particular, mobile devices are assumed to offload computation tasks to an edge server located at the access point in order to reduce a cost function that is a weighted sum of time and energy. The edge server adjusts the phase shifts of the RIS in order to maximize its earning while maintaining the incentives of the mobile devices for offloading and guaranteeing each of them a customized information rate. This resulting optimization problem is tackled by using an iterative evaluation procedure that identifies the feasibility of the problem when confronting an arbitrary set of information rate requirements. Numerical results show that the use of RISs enables the access point to guarantee higher information rate to all mobile devices, while at the same time improving the earning of the edge server. \subsection{Millimeter-Wave, Terahertz, and Optical Wireless Communications} Wireless data traffic has been increasing at a high rate and this trend is expected to accelerate over the next decade. To address this demand, the wireless industry is designing future wireless transmission technologies and standards in order to unlock the potential opportunities offered by large and unused frequency bands, which include the millimeter-wave, the terahertz, and the visible light spectrum. Since the wavelengths shrink by order of magnitudes, compared to currently used microwave frequencies, at these high frequency bands, diffraction and material penetration will incur greater attenuation, thus elevating the importance of line-of-sight propagation, reflection, and scattering. RISs are considered to be an enabling technology for controlling the radio waves and for enhancing the connectivity of wireless networks that operate at these emerging high frequency bands. In \cite{Cao2019}, the authors study the application of RISs in order to overcome signal path-loss and blind spots in millimeter-wave systems. The problem of maximizing the sum-rate in a multi-user network is addressed by jointly optimizing the transmit beamforming and the RIS phase shifts. With the aid of alternating maximization, the resulting two optimization sub-problems are solved in closed-form, and the initial optimization problem is tackled by iterating between them until convergence. The impact of discrete phase shifts is investigated as well, and a projection method is developed to tackle the associated optimization problem. In \cite{chaccour2020risk}, the authors consider a virtual reality network and study the problem of associating RISs to virtual reality users for application in the terahertz frequency band. In particular, the authors formulate a risk-based framework based on the entropic value-at-risk and optimize rate and reliability. The formulated problem accounts for the higher order statistics of the queue length, thus guaranteeing continuous reliability. Tools such as Lyapunov optimization, deep reinforcement learning, and recurrent neural network are adopted to tackle the optimization problem. In \cite{ying2020gmd}, the authors propose geometric mean decomposition-based beamforming for application to RIS-assisted millimeter-wave hybrid MIMO systems. By exploiting the common angular-domain sparsity of millimeter-wave channels over different sub-carriers, an orthogonal matching pursuit algorithm is proposed to obtain the optimal beamforming vector. By leveraging the angle of arrival and angle of departure associated with line-of-sight channels, the authors design the RIS phase shifts by maximizing the array gain for line-of-sight channels. Simulation results show that the proposed scheme achieves better error performance. In \cite{cao2019delay}, the authors consider an RIS-assisted millimeter-wave communication system in which an RIS is used to overcome the impact of spatial blockages. The objective is to jointly optimize the power of individual devices, the multi-user detection matrix, and the beamforming at the RIS. To this end, new methods for minimizing the power under delay requirements are proposed, and the optimization problem is solved by using alternating optimization. In particular, the configuration of the RIS is formulated as a sum-of-inverse minimization fractional programming problem, and it is solved by using the alternating direction method of multipliers. The proposed approach is shown to outperform semidefinite relaxation techniques. In \cite{xiu2020irs}, the authors consider an RIS-aided downlink wireless system in the millimeter-wave frequency band and formulate a joint power allocation and beamforming design problem in order to maximize the weighted sum-rate. To solve the problem, the authors propose a novel alternating manifold optimization based beamforming algorithm. Simulation results show that the proposed optimization algorithm outperforms existing algorithms. In \cite{chen2019sum}, the authors consider an indoor communication system for application to terahertz communications and study the application of RISs for improving the reliability of signal transmission. The authors study the problem of optimizing the sum-rate performance by selecting the optimal RIS phase shifts. Two algorithms based on a local search method and cross-entropy method are proposed and their performance analyzed with the aid of numerical simulations. In \cite{jamali2019intelligent}, the authors analyze an RIS-aided millimeter-wave massive MIMO system and show that a proper positioning of the active antennas with respect to the RIS leads to a considerable improvement of the system spectral efficiency. It is revealed that conventional MIMO architectures are either energy inefficient or expensive and bulky if the number of transmit antennas is large. On the other hand, RIS-aided MIMO architectures are shown to be highly energy efficient and fully scalable in terms of number of transmit antennas. In \cite{najafi2019intelligent}, the authors consider the application of RISs in order to alleviate the line-of-sight requirement in free space optical systems. The authors develop conditional and statistical channel models that characterize the impact of the physical parameters of an RIS, which include the size, position, and orientation, on the quality of the end-to-end channel. Furthermore, the authors propose a statistical channel model that accounts for the random movements of the RIS, the transmitter, and the receiver. With the aid of the proposed channel models, the authors analyze the advantages and limitations of RISs in different scenarios. In \cite{Perovi2019}, the authors consider the application of RISs for improving the channel capacity of millimeter-wave indoor networks. More precisely, the authors propose two optimization schemes that exploit the customizing capabilities of the RIS reflection elements in order to maximize the channel capacity. The first optimization scheme exploits only the adjustability of the RIS reflection elements. For this scheme, approximate expressions of the channel capacity are derived and used to infer the connection between the channel capacity gains and the system parameters. The second optimization scheme jointly optimizes the RIS reflection elements and the transmit phase precoder. For this scheme, the authors propose a low-complexity technique called global co-phasing to determine the phase shift values for use at the RIS. Simulation results show that the optimization of the RIS reflection elements produces significant channel capacity gains, and that this gain increases with the number of RIS elements. In \cite{Pradhan2019}, the authors study a millimeter-wave system in which a base station that employs hybrid precoding communicates with multiple single-antenna users through an RIS. The mean square error between the received symbols and the transmitted symbols is minimized by optimizing the hybrid precoder at the base-station and the RIS phase shifts. The optimization problem is tackled by resorting to the gradient projection method. The resulting algorithm is shown to be provably convergent to a point that fulfills the first-order optimality conditions of the considered optimization problem. In \cite{Wang2019b}, the authors analyze a single-user downlink millimeter-wave system model in the presence of multiple RISs. The transmit beamforming and the RIS phase shifts are optimized by analyzing single-RIS and multi-RIS system setups. In the single-RIS case, the optimal solution that maximizes the signal-to-noise ratio is derived, under the assumption of rank-one channel. In the multi-RIS case, a sub-optimal solution based on the semidefinite relaxation method is proposed. The authors show that RISs provide an effective way for signal focusing that is potentially useful for applications in the millimeter-wave frequency band. In \cite{Wang2019}, the authors generalize the study by analyzing the impact of the finite resolution of the RIS phase shifts. In \cite{wang2020performance}, the authors investigate the use of RISs for optical communications. In particular, the authors consider a system model in which multiple optical RISs are deployed in the environment and are used to build multiple artificial channels in oder to improve the system performance and to reduce the outage probability. The authors analyze the impact of three factors that affect the channel coefficients: beam jitter, jitter of the RISs, and the probability of obstruction. Based on the proposed model, the authors derive the probability density function of the channel coefficients, the asymptotic average bit error rate, and the outage probability for systems with single and multiple RISs. It is revealed that the probability density function contains an impulse function, which causes irreducible error rate and outage probability floors. \subsection{Relays and Massive Multiple-Input-Multiple-Output Systems} When new technologies come into the limelight, it is dutiful to critically investigate the potential benefits and limitations that they may provide as compared with similar and well established technologies. Therefore, it is sensible to compare RISs with transmission technologies that may be considered to be closely related to them. In the research literature, two technologies are often considered to be the most similar to RISs: Relays and massive MIMO. In general terms, RISs are different with respect to relays and massive MIMO because the former emerging technology is intended to be realized in a passive way with minimal power amplification and signal processing capabilities, while the latter two technologies rely upon the utilization of individual RF chains and powerful signal processing algorithms. The long-term vision of RIS-based SREs consists of realizing a multi-function platform in which the transmission, processing, and computation are, as much as possible, moved to the EM level. Relays and massive MIMO, have been envisioned, on the other hand, as platforms in which the EM signal are first converted into the digital domain and, after processing, are converted back to the EM domain. The large-scale experimental platforms reported in \cite{RFocus}, \cite{Jamieson_2017}, \cite{Jamieson_2019}, \cite{Bharadia_2020}, which are described in Section \ref{Testbeds}, clearly point this out. Despite these general considerations, it is important to identify a fair basis for the comparison of RISs against relays and massive MIMO. A few research papers have recently attempted to shed light on this issue. In \cite{Hu2017}, notably, the authors coin the term LIS and describe it as ``\textit{a new concept that conceptually goes beyond contemporary massive MIMO technology}''. In \cite{MDR_RISs_Relays} and \cite{Bjornson2019}, the authors report a comparative study of RISs against decode and forward relaying. In \cite{MDR_RISs_Relays}, in particular, the authors discuss all the advantages and disadvantages of RISs and relays in a comprehensive manner. From a performance comparison point of view, both papers lead to similar conclusions: RISs may outperform relaying provided that the size of RISs is sufficiently large. If one considers the implementation of RISs by using a large number of inexpensive antennas, this implies that several antenna elements are needed in order to achieve good performance without the need of using power amplification and signal regeneration. This finding was somehow expected. The interesting finding in \cite{MDR_RISs_Relays} is, however, that a sufficiently large RIS that is configured to operate as a simple anomalous reflector may outperform an ideal full-duplex single-antenna decode and forward relay in terms of achievable data rate. If one considers other performance metrics, such as the energy efficiency and the power consumption, the gains may be larger if RISs are realized without using active elements and power amplifiers. It is important to mention, however, that the signal manipulations that can be realized at the EM level are simpler than those that can be realized in the digital domain. In addition, the implementation of metasurface-based RISs with a high power efficiency requires the design of sophisticated metasurface structures, which are the state-of-the-art of research in the field. In \cite{Dardari_DegreesFreedom} and \cite{bjornson2020power}, the authors report a comparative study of RISs against MIMO and massive MIMO. The author of \cite{Dardari_DegreesFreedom} analyzes the fundamental aspects of the communication between RISs from the EM standpoint, with a focus on the degrees of freedom that are offered by the system. The departing point of the author is that the spatial multiplexing gains of MIMO systems, i.e., the channel degrees of freedom, are achieved in rich scattering environments and they are usually lost in favor of beamforming gains in rank-deficient channels. The main finding of the author is that the degrees of freedom offered by RISs are greater than one in propagation environments that are not characterized by rich scattering, e.g., in line-of-sight channels or for transmission at high frequencies (the millimeter-wave frequency range and beyond). Based on the findings of the author, this is, on the other hand, not possible in conventional MIMO systems. For this reason, the author concludes that RISs may outperform MIMO systems in those scenarios and may ultimately offer a large increase of the spatial capacity density. The authors of \cite{bjornson2020power} move from the findings in \cite{dardari2019communicating}, and analyze the scaling laws of RISs and massive MIMO as a function of the number of reflecting elements. The authors show that the scaling law is quadratic and linear in the number of antenna elements for RISs and massive MIMO, respectively. RISs are, however, expected to need a larger number of reflecting elements for achieving similar signal-to-noise ratios as massive MIMO, owing to the inherent assumption that RISs can apply only phase shifts and cannot amplify the incident EM fields if they are assumed to be made of locally or globally passive smart surfaces. \subsection{Software Defined Networking Based Design and Nano-Communication Networks} An important component for realizing the vision of SREs is the capability of controlling and programming the RISs in a software-based fashion \cite{Liaskos_COMMAG}, \cite{Liaskos_ACM}. More specifically, the long-term vision consists of realizing fully adaptive metasurfaces that are flexible enough to synthesize multiple concurrent functionalities at the EM level. Researchers of the European-funded project VisorSurf \cite{VisorSurf} have been researching towards the design and implementation of software-defined metamaterials for the last four years. Software-defined metamaterials are built upon descriptions of EM functionalities in reusable software modules that are specifically designed for changing the behavior of RISs by sending preset commands. In simple terms, the EM properties of RISs can be reconfigured at runtime by using a set of software primitives. In order to disseminate, interpret, and apply the commands, RISs need, however, the integration of a network of miniaturized controllers within their structure, which are capable of interacting locally and communicating globally to realize the desired EM behavior. The realization of truly software-defined metamaterials is, therefore, coupled with the realization of the network of miniaturized controllers, which are equipped with communication capabilities that can, e.g., be realized by exploiting nano-communication technologies. Several research papers on the design of software-defined metamaterials and nano-communication networks for application to metasurfaces have recently appeared in the literature. The research issues tacked in these papers encompass the definition of software-defined primitives, the analysis of communication and security issues, the design of medium access control protocols, routing protocols, and the network layer configuration and operation \cite{VisorSurf__6}, \cite{VisorSurf__7}, \cite{VisorSurf__4}, \cite{VisorSurf__5}, \cite{VisorSurf__3}, \cite{VisorSurf__1}, \cite{VisorSurf__2}. Interested readers are referred to \cite{VisorSurf} for further information. \subsection{Machine Learning Based Design} The field of machine learning has a long and extremely successful history. Machine learning has shown its overwhelming advantages in many areas, including computer vision, robotics, and natural language processing, where it is normally difficult to find a concrete mathematical model for feature representation. In those areas, machine learning has proved to be a powerful tool as it does not require a comprehensive specification of the model. Different from the aforementioned machine learning applications, the development of communications has vastly relied on theories and models, from information theory to channel modeling. These traditional approaches are currently showing some limitations, especially in view of the increased complexity of communication networks. Therefore, research on machine learning applied to communications, especially to wireless communications, is currently experiencing an incredible surge of interest. Recently, in addition, wireless researchers have started researching on the possibility of combining together model-based and data-driven approaches, in an attempt of capitalizing on their advantages while overcoming their inherent limitations. Machine learning is considered to be a potential enabler for realizing the vision of RIS-empowered SREs. In \cite{MDR_AM_TCOM}, the authors put forth the connection between RISs and machine learning, arguing that both are needed to realize the vision of SREs. The authors discuss how the use of machine learning is essential to reduce the complexity related to the design of RIS-based wireless networks, which is anticipated to be higher than in conventional wireless networks. To this end, the authors propose a model-aided deep learning framework, which is further elaborated in \cite{MDR_AI_VTM}, that exploits transfer learning to simplify wireless network design by combining together model-based and data-driven methods. The same authors discuss the connection between RIS-empowered SREs and reinforcement learning in \cite{MDR_AI_RIS}. In \cite{liaskos2019interpretable}, the authors introduce a neural-network-based approach for configuring the behavior of tiles in RIS-based environments. The wireless propagation is modeled as a custom, interpretable, back-propagating neural network, in which the RIS elements act as nodes and their cross-interactions as links. After a training phase, the neural network learns how to configure the RISs for improving the communication performance. By using a ray tracing simulation environment, the authors show performance gain in agreement with state-of-the-art solutions, but with a distinct gain in reducing the total number of active tiles. In \cite{Huang2019}, the authors employ an artificial neural network to maximize the received power in a RIS-based network. The downlink of a multi-user MISO system is considered, and the deep learning framework developed in \cite{MDR_AM_TCOM} is applied. An indoor scenario is considered, and a deep neural network is used as a function approximator to learn the map between the locations of the users and the corresponding configuration of the RIS reflecting elements that maximizes the signal-to-noise ratio at the intended receiver. In \cite{gao2020unsupervised}, the authors employ deep learning techniques to reduce the design complexity of RIS-based wireless networks. In particular, the authors propose an unsupervised approach to optimize the RIS phase shifts. In the proposed approach, a customized deep neural network is trained offline by using the objective function to be optimized for training the parameters of the deep neural network. Simulation results show a gain over conventional approaches based on the use of semi-definite relaxation and alternating optimization, even though the considered approach remains heuristic in the sense that no optimality property can be claimed. In \cite{huang2020reconfigurable}, the authors propose a joint design of transmit beamforming and phase shifts in a RIS-assisted MIMO system, by using a deep reinforcement learning framework. The proposed deep reinforcement learning algorithm is shown to be scalable for accommodating various system settings. Instead of utilizing conventional alternating optimization techniques to obtain the transmit beamforming and the RIS phase shifts, the proposed algorithm obtains the joint design simultaneously at the output of a deep neural network whose training is refined in real-time. In \cite{taha2020deep}, the authors propose a deep reinforcement learning framework with reduced training overhead that is able to tune the phase shifts of the RIS elements with reduced training overhead. The proposed approach paves the way to the deployment of distributed RISs, which are able of self-configuration and operation without the assistance of base stations or infrastructure nodes. The authors illustrate numerical results that show that the proposed online learning framework is able to approach the same rate as a benchmark system with perfect channel state information. In \cite{feng2020deep}, the authors optimize the design of the phase shifts of an RIS-aided downlink MISO wireless communication system, with the goal of maximizing the received signal-to-noise ratio. Because of the non-convexity of the considered resource allocation problem, the authors employ deep reinforcement learning in order to develop a practical phase shift design algorithm. Numerical results reveal that the developed algorithm can achieve near-optimal signal-to-noise ratio performance with relatively low complexity. In \cite{liu2020ris}, the authors consider the problem of joint system deployment, RIS phase shift control, power allocation, and dynamic decoding order determination in a RIS-enhanced wireless system, while enforcing individual data rate requirements to the multiple users. To tackle this optimization problem, the authors use machine learning. In particular, the authors propose a novel long short-term memory based echo state network algorithm for predicting the future traffic demands of multiple users based on an empirical dataset. In addition, the authors propose a decaying double deep Q-network based position-acquisition and phase-control algorithm to determine the position and control policy of the RIS. In \cite{Khan2019}, the authors use an artificial neural network for estimating and detecting symbols in an RIS-aided wireless system. A fully connected artificial neural network is employed to estimate the channels and phase angles from a reflected signal received through an RIS. This enables the authors to perform symbol detection without any dedicated pilot signaling, which significantly reduces the overhead required for the operation of RIS-aided networks. The proposed method is shown to achieve a lower bit error rate than traditional detectors. In \cite{elbir2020deep}, the authors investigate the use of deep learning for channel estimation in a RIS-assisted massive MIMO system. In the proposed scheme, each user has an identical convolutional neural network which takes as input the received pilot signals and yields as output an estimate of the direct channel between the transmitter and receiver, and the cascaded channel from the transmitter to the receiver through the RIS. The approach is extended to a multi-user scenario, wherein each user has its own convolutional neural network and estimates its own channel. With the aid of numerical simulations, the approach is compared against state-of-the-art deep learning based techniques and performance gains are shown. In \cite{taha2019enabling}, the authors propose an RIS-based architecture based on sparse channel sensors. All RIS elements are passive except for a few elements that are active and connected to the baseband of the RIS controller. The authors propose two solutions for the design of the RIS reflection matrices based on compressive sensing and deep learning. The deep learning based solution has the advantage of requiring a negligible training overhead, which makes it practical especially in the RIS context, since it reduces the overhead related to RIS control. In \cite{yang2020deep}, the authors study an RIS-aided wireless communication system for physical layer security, in which an RIS is deployed to adjust its surface reflecting elements in order to guarantee the secure communication of multiple legitimate users in the presence of multiple eavesdroppers. Aiming to improve the system secrecy rate, a design problem for jointly optimizing the base station beamforming and the RIS reflecting beamforming is formulated, under the assumption of different quality of service requirements and time-varying channel condition. As the system is highly dynamic and complex, and it is challenging to address the resulting non-convex optimization problem, the authors propose a deep reinforcement learning secure beamforming approach that achieves the optimal beamforming policy. Furthermore, post-decision state and prioritized experience replay schemes are utilized to enhance the learning efficiency and secrecy performance. Simulation results demonstrate that the proposed secure beamforming approach can significantly improve the system secrecy rate and satisfaction probability. \subsection{Localization, Positioning, and Sensing} Future wireless networks are expected to offer more than allowing people, mobile devices, and objects to communicate with each other. Future wireless networks need to be turned into a distributed intelligent communication, sensing, and computing platform. Besides connectivity, more specifically, this envisioned 6G platform is expected to be capable of sensing the environment, as well as locally storing and processing information, in order to provide network applications and services with context-awareness capabilities. Such processing could accommodate the time critical, ultra-reliable, and energy-efficient delivery of data, and the accurate localization of people and devices. Besides enabling enhanced connectivity, therefore, RISs are envisioned to play an important role to accomplish several other tasks that complement and support communications. Thanks to the possibility of equipping smart surfaces with energy-harvesting sensors, RISs may be able to offer a dense and capillary network for sensing the environment, and for creating environmental maps supporting a variety of emerging applications. Thanks to the possibility of realizing large-size smart surfaces, RISs may offer a platform that provides localization and positioning services with high accuracy in outdoor and outdoor scenarios, as well as they may enable near-field highly focusing capabilities for supporting the communication of massive deployments of devices. Thanks to the possibility of performing algebraic operations and functions directly on the impinging radio waves, RISs may offer the opportunity to realize a fully EM-based computing platform unlocking the potential of reconfigurable backscatter communications. For all these reasons, several researchers have started investigating the potential opportunities offered by RISs for applications beyond enhanced connectivity. In \cite{Hu2018c}, the authors envision the use of RISs for positioning purposes. In particular, the authors analyze the Cram\'er-Rao lower bound for the localization accuracy offered by RISs. Closed-form expressions and accurate approximations for the Cram\'er-Rao lower bound are derived and are used to prove that the localization error offered by RISs decreases quadratically with their surface area. This holds true in general except for the case in which a terminal is located exactly on the central perpendicular line of the RIS. In this latter case, the localization error decreases linearly. The results show that a considerable performance improvement is possible over conventional approaches, even when an unknown phase shift is present in the RIS analog circuit. Moreover, the authors discuss different deployment architectures for RISs that can be used for positioning, and compare the case studies in which the deployment area is covered by a single large RIS or by multiple smaller RIS. Results show that none of the two approaches always outperforms the other. In \cite{AlegriaASILOMAR}, the authors derive the Cram\'er-Rao lower bound for the localization accuracy offered by RISs under the assumption of having discrete phase shifts and measuring amplitudes with a finite resolution. In addition, the authors compute analytical bounds for the Cram\'er-Rao lower bound related to the positioning error when the phase information is disregarded and the amplitude is measured with full resolution. Numerical results are used to analyze and quantify the Cram\'er-Rao lower bound loss with respect to the resolution of quantization. In \cite{he2019large}, the authors investigate the use of RISs for positioning and object tracking in millimeter-wave MIMO wireless networks. The authors show that RISs provide promising performance thanks to the very sharp beams that they can realize. In particular, the Cram\'er-Rao lower bound of the positioning error is derived, and the impact of the number of RIS reflecting elements on the localization performance is analyzed. Numerical results corroborate the theoretical analysis, and show that RIS-based positioning systems can achieve better performance than traditional schemes. In \cite{He2019}, the authors investigate the design of millimeter-wave MIMO wireless networks with joint communication and localization capabilities. This authors show that the use of RISs is beneficial for both tasks, granting both accurate positioning and high data-rate transmission. The authors introduce an adaptive phase shifter design based on hierarchical codebooks and feedback from the mobile station. The proposed scheme does not require the deployment of active sensors and baseband processing units. In \cite{wymeersch2019radio}, the authors analyze and discuss the fundamental technical and scientific challenges for the successful use of RISs for the localization of users and for creating maps of the coverage area in millimeter-wave wireless networks. In this context, the authors describe their vision on the use of RIS-based localization and illustrate initial results and solutions along this line of research. It is argued that the use of RISs for localization purposes has a great potential for improving the localization accuracy, thanks to the sharpness of the beams that RISs equipped with a large number of reflecting elements can realize. \subsection{Experimental Assessment and Testbeds} \label{Testbeds} From a technological point of view, RISs are a new and emerging paradigm in the context of wireless communications. Even though reflectarrays have been used for long time in several communication-related applications, the realization of metasurface-based RISs bring new implementation challenges, and necessitate the realization of proof-of-concept platforms and hardware testbeds in order to substantiate theoretical findings and to develop realistic channel and signal models for system design. Even though several research works on the design of metasurfaces with advanced functionalities can be found, research on the realization of hardware platforms for application to wireless communications is still at its infancy. However, a few relevant research works can be found already. As mentioned in Section II, the MIT's RFocus \cite{RFocus} and the NTT-DOCOMO \cite{Docomo_Glass} platforms are two notable examples of promising research activities towards the realization of RISs that are specifically designed for wireless applications. The world's first field trials performed by NTT DOCOMO and MetaWave in December 2018 on the application of RISs to the millimeter-wave frequency can be found in \cite{DocomoMetaWave}. Other examples available in the literature are briefly reported as follows. In \cite{Tan_ICC2016} and \cite{Tan2018} the authors report the design of a smart reflectarray that is designed for enhancing indoor connectivity in the millimeter-wave frequency band. The reflector panel is fabricated to operate in the 60 GHz frequency band, and its dimensions are 337 mm, 345 mm, and 0.254 mm for its length, height, and thickness, respectively. The reflector panel is made of 224 reflector units, whose inter-distance is larger than one wavelength. Therefore, this design does not fall into the definition of metasurfaces. The authors show that the proposed solution enables the communication of multiple users in the same indoor area, over the same spectrum band, at the same time, and without suffering any significant interference, as well as it enables the reduction of the link outage probability. Recent research results of the same authors are available in \cite{Buffalo2019}. Along the same lines as \cite{RFocus}, a few other research groups around the world have built prototypes for realizing smart surfaces that are made of large arrays of inexpensive antennas. Notable fully-functional experimental testbeds and experimental activities along this line of research include the PRESS (programmable radio environment for smart spaces) prototype \cite{Jamieson_2017}, the LAIA (large array of inexpensive antenna) prototype \cite{Jamieson_2019}, and the ScatterMIMO prototype \cite{Bharadia_2020}. As far as the realization of smart surfaces based on metasurfaces is concerned, a relevant example is the HyperSurface hardware platform: A software-defined, controllable, and programmable metasurface structure that is capable of shaping the EM waves in reconfigurable ways. The HyperSurface is under development by researchers of the European-funded project VisorSurf \cite{VisorSurf}. In \cite{dai2019reconfigurable}, the authors report a new type of high-gain yet low-cost RIS made of 256 elements. The proposed RIS combines the functions of phase shift and EM radiation on an electromagnetic surface where PIN diodes are used to realize two-bit phase shifts for beamforming. This proposed design forms the basis for the world's first wireless communication prototype that realize an RIS having 256 two-bit elements. The prototype consists of modular hardware and flexible software that encompass the hosts for parameter setting and data exchange, universal software radio peripherals for baseband and RF signal processing, as well as modules for signal transmission and reception. Experimental results confirm the feasibility and efficiency of RISs for wireless communications. In particular, at 2.3 GHz the proposed RIS can achieve a 21.7 dBi antenna gain. At the millimeter wave frequency of 28.5 GHz, it attains a 19.1 dBi antenna gain. Furthermore, it is shown that the developed prototype is capable of significantly reducing the power consumption. In \cite{hu2019reconfigurable}, the authors design an RF sensing system for posture recognition based on RISs. The proposed system can actively customize the environment in order to provide the desirable propagation properties and diverse transmission channels. The prototype has a size of 69 cm $\times$ 69 cm $\times$ 0.52 cm, and it is composed of a two-dimensional array of electrically controllable unit elements. Each row/column of the array contains 48 unit elements, which corresponds to a surface made of 2,304 unit elements. Each unit element has a size of 1.5 cm $\times$ 1.5 cm $\times$ 0.52 cm, and it is composed of four rectangle copper patches printed on a dielectric substrate. Any two adjacent copper patches are connected by a PIN diode that is controlled by applying appropriate voltages. By combing simulation and experimental results, the authors show that the posture recognition accuracy increases with the size of the RIS and with the number of independently controllable elements. In \cite{Wankai_ElectronLetterEditor}, \cite{Wankai_ElectronLetter}, \cite{Wankai_ChinaCommun}, \cite{Wankai_WCM}, \cite{Wankai_JSAC}, the authors report the design and some experimental results on multiple prototypes of reconfigurable metasurfaces that implement single-RF transmitters. In particular, the prototype reported in \cite{Wankai_ElectronLetter} is designed to have a full 360 degrees phase response and a reflectivity of about 85\% at a working frequency of 4.25 GHz. The fabricated metasurface sample is made of $8 \times 32$ unit cells. The size of a unit cell is 12 mm $\times$ 12 mm $\times$ 5 mm, which approximately corresponds to 0.17$\lambda$ $\times$ 0.17$\lambda$ $\times$ 0.07$\lambda$ at 4.25 GHz. The capacitance of the unit cell is dominated by a varactor diode, which indicates that the phase response of the metasurface can be tuned through the bias voltage of the varactor diode. This bias voltage has an approximate linear relationship with the phase of the reflected wave and can achieve 360 degrees phase modulation. For example, the authors prove that the designed metasurface prototype is capable of mimicking the phase response of an eight phase shift keying modulation scheme. In \cite{Wankai_PathLoss}, the authors report the world's first experimental measurements to characterize the path-loss experienced by EM waves in the presence of metasurfaces. The authors report experiments, which are conducted in an anechoic chamber, for three samples of manufactured metasurfaces with 10,200, 1,700, and 256 unit cells, and whose size is 1.02 m $\times$ 1 m at 10.5 GHz, 0.34 m $\times$ 0.5 m at 10.5 GHz, and 0.384 m $\times$ 0.096 m at 4.25 GHz, respectively. The authors prove that the path-loss as a function of the transmission distance depends on several parameters, which include the size of the metasurface, the function applied by the metasurface, and whether the system operates in the radiative near-field or in the far-field. \section{The Road Ahead} \label{Beyond} \textbf{Major research problems to tackle}. In this section, we elaborate on some major open research problems that we consider to be of great importance for unveiling the potential benefits and for assessing the advantages and limitations of RISs against other mature wireless technologies. The list of open research problems is, however, not intended to be exhaustive in light of the steady growth of fundamental and applied research on RIS-empowered SREs. \textbf{EM-based circuital models}. The homogenized and macroscopic model-based approach (either based on surface susceptibility functions or surface impedances) briefly summarized in the present paper is a powerful method for analyzing and optimizing RISs. It constitutes, in particular, a suitable interface between the physics phenomena underlying the operation of RISs and the level of abstraction that is needed for obtaining adequately accurate but sufficiently tractable models for application to wireless communications. This approach hides, however, some aspects related to the practical realization of RISs, which may be convenient to preserve in the analytical formulation. For analyzing and optimizing wireless networks, in particular, it may be appropriate to start from simple models for the unit cell of metasurfaces, e.g., simple dipoles, and to obtain equivalent EM-based circuital models for metasurface structures, which explicitly account for the mutual coupling among the unit cells as a function of their size, inter-distance, and spatial arrangements. This will allow us to better understand the potential benefits and limitations of sub-wavelength metasurface structures, and to better quantify the potential gains for wireless applications. \textbf{Path-loss and channel modeling}. In order to evaluate the performance limits of RISs in wireless networks, we need realistic models for the propagation of the signals scattered by metasurfaces. In addition, it is necessary to abandon the comfortable assumption of far-field propagation, since several promising applications and potential advantages of RISs may emerge in the radiative near-field regime. To this end, it is necessary to relay upon physics-based models for the propagation of EM fields in proximity of metasurfaces and to account for their circuital models in the problem formulation. Besides the development of accurate path-loss models for link budget analysis, it is necessary to develop fading models for sub-wavelength structures, both at the microscopic level, which account for individual unit cells, and at the macroscopic level, which may be more easily integrated into communication-theoretic frameworks. \textbf{Fundamental performance limits}. RISs can be employed for different purposes, which include beamsteering, beamforming, focusing, modulation, and joint modulation and encoding with the transmitter. Depending on the specific application and wave transformation applied, the ultimate performance limits are not known yet. Recent results have pointed out, in a simple point-to-point communication setup, that the channel capacity is achieved by performing joint encoding at the transmitter and RIS, whereas typical criteria that rely on maximizing the power of the received signal are sub-optimal. These findings are obtained, however, by considering simple models for the metasurface structure, which are in agreement with conventional assumptions in communication and information theory. The ultimate performance limits of RISs, how to best configure RISs to achieve them, and the actual gains with respect to other well established technologies are not known yet. \textbf{Robust optimization and resource allocation}. The simple examples reported in the present paper confirm that physics-based models for simple metasurfaces, e.g., perfect anomalous reflectors, are more complex that the typical models that communication theorists employ in formulating resource allocation problems. As an example, the amplitude and phase responses of a metasurface operating as a perfect anomalous reflector are not independent of each other, and the resulting metasurface structure is locally non-passive. It is necessary to integrate physics-based models for metasurface structures into resource allocation problems, and, in particular, to explicitly account for the impact of the sub-wavelength structure of RISs and the associated design constraints and shaping capabilities of the radio waves. \textbf{Constrained system design and optimization}. One of the potential novelties of RISs is the possibility of manipulating the radio waves impinging upon them without the need of relying on on-board power amplifiers and signal processing units. Some advantages of these assumptions lie in the opportunity of reducing the EM field exposure of human beings and in making the metasurfaces easier to recycle. These assumptions introduce, however, constraints on the operation of RISs when they are deployed in wireless networks. Usually, the restrictions on performing signal processing operations on the metasurfaces have an impact on the overhead that is associated with gathering the necessary environmental information for optimizing and configuring RISs. The fundamental trade-off between the complexity and power consumption of RISs, as well as the associated overhead needs to be carefully investigated and assessed. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_23.pdf} \caption{Electromagnetic-based routing in smart radio environments (reproduced from \cite{MDR_Survey_EURASIP}).} \label{Fig_23} \end{centering} \end{figure} \textbf{EM-based communications: ``Layer-0'' networking}. RISs may open the possibility of designing wireless networks in which the entire protocol stack for communication is realized through an appropriate shaping and manipulation of the radio waves at the EM level. This does not encompass only physical layer functionalities, which have been the main focus of research to date, but the medium access control layer and the routing layer as well. In scenarios with a high density of mobile terminals and devices, for example, RISs may be employed to create a large number of orthogonal wireless channels that may be employed for achieving high spatial capacities through EM-based medium access control protocols with reduced overhead and contention time, as well as for enabling spatial multiplexing gains in rank-deficient wireless environments. RIS-empowered SREs, in addition, may be viewed as an opportunity to realize EM-based routing protocols (see, e.g., Fig. \ref{Fig_23}), according to which the radio waves are routed from the transmitter to the receiver via controlled reflections and refractions at low latencies, low transmission delays/jitters, and high reliability, since all operations are realized directly at the EM level. Research on the potential uses, advantages, and limitations of capitalizing on RISs for the design of communication protocols beyond the physical layer is almost unexplored to date but deserves major attention and research efforts. \textbf{Large-scale networks: Deployment, analysis, and optimization}. RIS-empowered SREs have several potential applications, which encompass indoor and outdoor environments. The vast majority of research activities conducted so far have considered the analysis of optimization of ``small-size'' networks, usually networks that are made of a single RIS. This is the natural starting point for assessing the potential benefits of new technologies. In addition, the analysis of these simple scenarios is based on modeling assumptions that may not necessarily be sufficiency realistic for the assessment of sub-wavelength metasurfaces. It instrumental to quantify, however, the performance limits of SREs in large-scale deployments. For example, a relevant question may be to identify the density of RISs to be deployed for increasing the coverage probability or the energy efficiency in a large industrial factory or even in the downtown of a city. This is an almost unexplored research problem to be tackled. \textbf{Ray tracing and system-level simulators}. The deployment phase of new technologies is usually preceded by extensive system-level simulation studies and field test trials. In this context, the use of ray tracing and system-level simulators plays a crucial role for overcoming the limitations of simplified analytical studies, and for taking into account realistic spatial topologies, e.g., three-dimensional maps for territories, cities, streets, buildings, and floor plants of apartments, offices, etc. Current tools that are employed to this end are not suitable for application to RIS-empowered SREs because the wave transformations and the scattering models of metasurfaces are not integrated into them. In simple terms, the so-called generalized laws of reflection and refraction that can be viewed as approximations of the response of metasurfaces to impinging radio waves according to the assumptions of geometric optics are not available in commercial ray tracing tools and system-level simulators. \textbf{Beyond far-field communications}. Most research works conducted in the recent present on RIS-empowered SREs rely upon far-field assumptions. RISs, however, may be made of geometrically large surfaces of the order of a few square meters. This implies that RISs may operate in the near-field regime in relevant application scenarios, e.g., in indoor environments. The use of geometrically large RISs opens the possibility of building new wireless networks that operate in the near-field regime, which is not a conventional design assumption in wireless communications. Research on the fundamental performance limits, design constraints, and potential applications and benefits of near-field communications in RIS-empowered SREs has not received significant attention so far. In light of the potential applications that may be unlocked, e.g., highly focusing capabilities, the near-field regime is worthed of further attention from the research community. \textbf{Beyond communications}. Most research works conducted in the recent present on RIS-empowered SREs are focused on applications that are related to communications. RISs, however, offer opportunity for research that go beyond communications. For example, the high focusing capability of electrically large RISs offers the opportunity of using them for high-precision radio localization and mapping (i.e., the construction of a model or map of the environment). The capabilities of RISs for these applications and the expected performance as a function of their size, sub-wavelength structure, and near-field vs. far-field operation constitute an open research problem. In addition, radio localization and mapping can be considered to be important enablers for realizing important communication-related tasks. \textbf{Advantages and limitations}. This can be considered to be the ultimate goal of conducting research on RIS-empowered SREs: ``\textit{Do RISs bring any (substantial) gains as compared with other well-established technologies in wireless networks}?'' At the time of writing, there is no precise answer to this question, and it will probably take a few years of multi-disciplinary research to uncover the tip of the iceberg. \begin{figure}[!t] \begin{centering} \includegraphics[width=\columnwidth]{Fig_Maci.pdf} \caption{Towards 3G metasurfaces (slide: Prof. Stefano Maci \cite{Maci_Huawei}).} \label{Fig_Maci} \end{centering} \end{figure} \textbf{6G wireless vs. 3G metasurfaces}. Finally, we conclude this section by emphasizing that the potential benefits of RIS-empowered SREs are conditioned upon the availability of reconfigurable multi-function metasurfaces with exceptional capabilities of manipulating EM waves. Research and development on this enabling technological field of SEM has just began, as illustrated in Fig. \ref{Fig_Maci}. \section{Conclusion} \label{End} For more than seven decades, communication and information theorists have built their theories and algorithms upon \textbf{C. E. Shannon}'s seminal work reported in the monograph ``\textit{A (The) Mathematical Theory of Communication}'' (1948). The present article constitutes a first preliminary attempt that elaborates on the need of reconciling and reuniting Shannon's mathematical theory of communication with \textbf{G. Green}'s landmark essay in the field of mathematical physics ``\textit{An Essay on the Application of Mathematical Analysis to the Theories of Electricity and Magnetism}'' (1828) and \textbf{J. C. Maxwell}'s fundamental treatise on the theory of electromagnetism ``\textit{A Dynamical Theory of the Electromagnetic Field}'' (1865). \\ We conclude the present article by quoting the last paragraph of the preface of \textbf{G. Green}'s essay: ``\textit{Should the present Essay tend in any way to facilitate the application of analysis to one of the most interesting of the physical sciences, the author will deem himself amply repaid for any labour he may have bestowed upon it; and it is hoped the difficulty of the subject will incline mathematicians to read this work with indulgence, more particularly when they are informed that it was written by a young man, who has been obliged to obtain the little knowledge he possesses, at such intervals and by such means, as other indispensable avocations which offer but few opportunities of mental improvement, afforded}". \bibliographystyle{IEEEtran}
{'timestamp': '2020-04-21T02:28:44', 'yymm': '2004', 'arxiv_id': '2004.09352', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09352'}
arxiv
\section{Network Structures} \label{app:net} \paragraph{Feature Pyramid} The feature pyramid learns to extract feature maps that measures the channel consistency for objective function and serve as the image context features for subspace prediction. We use DRN-22~\cite{DRN} as the backbone network for efficiency and denote the last residual blocks of conv3, conv4, conv5, conv6 in DRN-22 as $\{C^4,C^3,C^2,C^1\}$, with strides $\{4,8,16,32\}$ respectively. We upsample a feature map $C^{k}$ by a factor of 2 with bilinear interpolation and concatenate the upsampled feature map with $C^{k+1}$ in the next level. This procedure is iterated until the finest level. Finally, we apply a $3\times3$ convolution on the concatenated feature maps to reduce its dimensionality to 128 to balance the expressiveness and computational complexity, which leads to the final feature pyramid ${\mathbb{F}}=\{F^{1},F^2,F^3,F^{4},F^{5}\}$. \paragraph{Subspace Predictor} The subspace predictor is learned to predicted the basis $\mathcal{V}$ from the image context and the minimization context features. Before feeding the features to the subspace predictor, we average pool the context features with different kernel size to aggregate the spatial information at different scale. Instead of first average pooling with stride and upsampling as in spatial pyramid pooling~\cite{PSPNET,SPP}, we first compute the integral image of each features channel and calculate the pooled features for each pixel coordinate based on the integral image, which gives better efficiency as in computer vision literature~\cite{HARR,GF}. We illustrate the subspace predictor at the finest level in~\figref{SL}, and this design of the subspace predictor is simple yet effective as demonstrated in the experiments and can serve as the baseline for future works. Please refer to the \emph{appendix} for more details. \subsection{Applications} \label{sec:app} We now show how the proposed LSM framework unifies various low-level vision tasks. We implement four tasks for demonstration, and only introduce the data term for each task. For~\emph{all} tasks, we initialize ${\bm{x}}$ as a zero vector. According to the difference of data term formulation, these tasks are divided to two categories.~\label{sec:app} In the first category, we introduce two binary image labeling tasks: interactive segmentation and video segmentation, both of which share the same formulation as: \vspace{-5pt} \begin{equation} D({\bm{x}})=\sum_{{\bm{p}}}\alpha_{\bm{p}}\|\tau({\bm{x}}_{\bm{p}})-1\|_{2}^{2}+\beta_{\bm{p}}\|\tau({\bm{x}}_{\bm{p}})+1\|_{2}^{2}, \label{equ:edge} \vspace{-5pt} \end{equation} where ${\bm{p}}=[x,y]$ is a pixel coordinate, $\tau(\cdot)$ is an activation function to relax and constrain the binary label and constrain $\tau({\bm{x}}_{\bm{p}})$ between $(-1,+1)$, while $\alpha_{\bm{p}}$ and $\beta_{\bm{p}}$ are the probabilities that $\tau({\bm{x}}_{{\bm{p}}})=+1 \text{ or}-1$. \begin{itemize} \vspace{-5pt} \item For \textbf{interactive segmentation}, $\tau({\bm{x}}_{\bm{p}})$ indicates whether a pixel ${{\bm{p}}}$ is on the foreground object ($+1$) or background scene ($-1$), and the corresponding probabilities ${\alpha_{\bm{p}}}$ and $\beta_{\bm{p}}$ are estimated as nonparametric probabilities~\citep{Wu_2018_CVPR} from the foreground scribble points and the background scribble points respectively. \vspace{-5pt} \item For \textbf{video segmentation}, $\tau({\bm{x}}_{\bm{p}})$ indicates whether a pixel ${{\bm{p}}}$ belongs to an previously labeled foreground object ($+1$) or not ($-1$), and ${\alpha_{\bm{p}}}$ and $\beta_{\bm{p}}$ are the corresponding average probabilities estimated from ${\bm{p}}$'s correlation with its foreground and background neighbors in previous labeled frames respectively. \vspace{-5pt} \end{itemize} In the second category, we introduce two dense correspondence estimation tasks on two images: stereo matching and optical flow, both of which can be formulated as: \vspace{-5pt} \begin{equation} D({\bm{x}})=\sum_{{\bm{p}}}\|F_{S}({\bm{p}}+{\bm{x}}_{{\bm{p}}})-F_{T}({\bm{p}})\|_{2}^{2}, \label{equ:corr} \vspace{-5pt} \end{equation} where ${\bm{p}}=[x,y]$ is the pixel coordinate in the target (template) image $T$, and ${\bm{x}}_{{\bm{p}}}$ is the warping vector that warps ${{\bm{p}}}$ to ${\bm{p}}+{\bm{x}}_{{\bm{p}}}$ in the source image $S$. Similar to the brightness constancy assumption for image channels~\citep{HS},~\equref{corr} assumes that the warped feature channels $F$ will also be consistent. \begin{itemize} \vspace{-5pt} \item For~\textbf{stereo matching}, $S$ and $T$ are two images viewing the same scene. Therefore, ${\bm{x}}_{{\bm{p}}}=[u,0]$ only contains horizontal displacement and warps ${\bm{p}}$ to $[x+u,y]$ in the target image $T$. \vspace{-5pt} \item For~\textbf{optical flow}, $S$ and $T$ are two neighboring video frames. Therefore, ${\bm{x}}_{{\bm{p}}}=[u,v]$ is the 2D motion vector that warps ${\bm{p}}$ to $[x+u,y+v]$ in the $S$. Since optical flow is a two-dimensional labeling problem compared with stereo matching (one-dimensional, \ie ${\bm{x}}_{{\bm{p}}}$ is a scalar) and the two image labeling tasks, we apply Cramer's rule~\citep{Higham} to unify the network structures and parameters of optical flow with others. Please refer to the~\emph{supplementary} for more implementation details. \vspace{-5pt} \end{itemize} \section{Conclusions} We propose the learning subspace minimization (LSM) framework to address low-level vision problems that can be formulated as an energy minimization of a data term and a regularization term. We learn convolution neural networks to generate a content-aware subspace constraint to replace the regularization term which is often heuristic and hinders performance. At the same time, we exploit the data term and minimize it to solve a low-level task, because the data term is often derived from the first principle of a task and captures the underlying nature of a problem. This approach nicely combines domain knowledge (\ie minimizing data terms derived from first principles) and the expressive power of CNNs (\ie learning to predict content-aware subspace constraint). Our LSM framework supports joint multi-task learning with completely shared parameters and also generate state-of-the-art results with much smaller network and faster computation. It even enables zero-shot task generalization, where a trained network can be generalized to unseen tasks. This capability demonstrates our LSM framework can be applied to a wide range of computer vision tasks. \section{Experiments} \subsection{Implementation Details} \label{sec:training} \paragraph{Training Loss} Loss design is beyond the scope of this paper, so we use existing losses for all tasks. For~\emph{interactive segmentation} and~\emph{video segmentation}, we use the Intersection of Union (IoU) loss from~\cite{IOU}. For~\emph{stereo matching} and~\emph{optical flow} we use the end-point-error (EPE) loss as in DispNet~\citep{SYNDATA} and FlowNet~\citep{FLOWNET}. Since our solution is estimated coarse-to-fine, we downsample the ground-truth to multiple scales and sum the loss over all scales as in~\citep{PWCNET}. \paragraph{Hyperparamters} We use AdamW optimizer~\citep{ADAMW} with the default settings where $\beta_{1}=0.9$, $\beta_{2}=0.999$. The learning rate is initialized as $3\times10^{-4}$ and reduced during training using cosine decay~\citep{SGDR} without warm restarts. This set of hyperparameters are fixed for all experiments. \paragraph{Dataset} For \emph{interactive segmentation}, we use the PASCAL VOC Semantic Boundaries Dataset~\citep{BharathICCV2011} for training and the VGG interactive segmentation dataset~\citep{Gulshan10} for testing, and the overlapped 99 images are excluded from the training set. For \emph{video segmentation}, we use the DAVIS-2017 dataset~\citep{2017} for training and the DAVIS-2016~\citep{2016} for testing. For~\emph{stereo matching}, we use the training/testing split of FlyingThings3D~\citep{SYNDATA} from~\citep{CRL}, and for~\emph{optical flow} we use FlyingThings3D for training and Sintel~\citep{SINTEL} for testing. \subsection{Comparison with State-of-the-art} \label{sec:multi_task} Our framework can be applied to a low-level vision task as long as its first-order and second-order differentiable data term can be formulated. So we first test the multi-task capability of our network. Note that the \emph{whole} network structure and \emph{all} parameters are shared for all tasks, while previous works~\citep{MULTI1,MULTI2,UBER} \emph{only} share the backbone and use different decoders/heads to handle different tasks. We train our model on all four tasks jointly using a workstation with four TITAN-Xp GPUs. For implementation simplicity, we deploy one task on each GPU and update the network parameters on CPU. The batch size are 12 for interactive segmentation, 6 for video segmentation, and 4 for stereo matching and optical flow. The training runs for 143.2K iterations. To make a fair comparison with other state-of-the-art single-task methods, we also train each task individually and denote the corresponding result as `Single', while the results of joint training are denoted as `Joint'. \paragraph{Interactive Image Segmentation} For interactive segmentation, we compare our LSM framework to several conventional methods including ESC and GSC by~\cite{Gulshan10}, and Random walk~\citep{RANDOMWALK}, as well as recent CNN based methods Deep Object Selection (DIOS)~\citep{DIOS}, Latent Diversity (LD)~\citep{LATENT} and Backpropagation Refinement (BRS)~\citep{BRS}. We randomly sample a few points from the scribbles as inputs for the CNN based methods, since they only supports clicks. We evaluate all methods by the plots required to make IoU greater than 0.85. As shown in~\figref{seg1}, our method achieves better results among both recent CNN based methods and the conventional ones. We also compare with the LD qualitatively when user only interact once. We also subsample scribbles and successively send annotations to LD for a fair comparison.~\figref{seg2} shows that our results are superior than Latent Diversity~\citep{LATENT}. It is because the existing CNN based methods only supports spatial distance maps as inputs, which are less precise than scribbles. While our LSM supports scribbles by feature distribution estimation and~\equref{edge}. \begin{figure}[h] \vspace{-5pt} \centering \vspace{-5pt}\subfigure[Average plots required to make IoU>0.85.]{\includegraphics[width=\linewidth,page=1]{figures/compare.pdf}\label{fig:seg1}} \vspace{-7pt}\subfigure[Our result is superior than LD~\citep{LATENT} when user interact only once.]{\includegraphics[width=\linewidth]{figures/seg2.png}\label{fig:seg2}} \vspace{-5pt} \caption{Interactive image segmentation result on VGG interactive segmentation benchmark.} \vspace{-10pt} \label{fig:seg} \end{figure} \paragraph{Video Segmentation} For video segmentation, we compare our LSM framework to several conventional minimization based methods including BVS~\citep{BVS}, OFL~\citep{OFL} and DAC~\citep{DAC}, as well as recent CNN based methods that do not require fine-tuning for a fair comparison, including MaskRNN~\citep{MASKRNN}, VideoMatch~\citep{VIDEOMATCH} and FEELVOS~\citep{FEELVOS}.~\figref{vidseg1} shows that our LSM performs better than conventional methods and comparable to CNN based methods. We also show a qualitative comparison to FEELVOS on the challenging dance-twirl sequence. As shown in~\figref{vidseg2}, our LSM generates more false positive regions than FEELVOS~\citep{FEELVOS} because the skin and the cloth colors of the dancer and the audiences are similar, but ours is able to track the dancer consistently while FEELVOS lost the dancer's torso during twirl. \begin{figure}[h] \centering \vspace{-5pt}\subfigure[Average IoU for video segmentation.]{\includegraphics[width=\linewidth,page=4]{figures/compare.pdf}\label{fig:vidseg1}} \vspace{-7pt}\subfigure[Our result is qualitatively comparable to FEELVOS~\citep{FEELVOS}.]{\includegraphics[width=\linewidth]{figures/video_zero.png}\label{fig:vidseg2}} \vspace{-5pt} \caption{Video segmentation result on DAVIS 2016.} \label{fig:vidseg} \vspace{-5pt} \end{figure} \paragraph{Stereo Matching} For stereo matching, we compare our LSM framework with several conventional methods including SGM~\citep{DSPSGM}, SPS~\citep{Yamaguchi14} and MC-CNN~\citep{MCNET} which uses CNN features~\emph{only} for data term evaluation in a MRF, as well as some fully CNN based methods including DispNet~\citep{SYNDATA}, CRL~\citep{CRL}, PSMNet~\citep{PSMNET} and GANet~\citep{GANET}. When compared with other CNN based methods, our LSM is comparable for joint training and better for single-task training as shown in~\figref{things_epe_disp}. As shown in~\figref{l2r}, we are able to estimate both the left-to-right and the right-to-left disparities in the same accuracy because we do not assume the direction or the range of the disparity in~\equref{corr}. Altough~\citep{PDS} has been proposed to achieve range flexibility, the fully CNN based methods still only deal with single directional pairs because of the cost-volume. \begin{figure}[ht] \vspace{-5pt} \centering \vspace{-5pt}\subfigure[Average End-Point-Error for disparity.]{\includegraphics[width=\linewidth,page=2]{figures/compare.pdf}\label{fig:things_epe_disp}} \vspace{-7pt}\subfigure[Our LSM supports both left-to-right and right-to-left stereo matching while most of fully CNN based methods only support left-to-right.]{\includegraphics[width=\linewidth]{figures/disp.png}\label{fig:l2r}} \vspace{-5pt} \caption{Stereo matching results on FlyingThings 3D.} \vspace{-5pt} \label{fig:things} \end{figure} \paragraph{Optical Flow} For optical flow, we compare our LSM framework with conventional methods including LDOF~\citep{LARGFLO}, EpicFlow~\citep{EPIC} and PCA-Layers~\citep{PCAFLO} which also adopts a basis representation but the basis is static and specifically learned for optical flow using PCA~\citep{PCABook}, as well as CNN based methods including LiteFlowNet~\citep{LITEFLOW}, PWC-Net~\citep{PWCNET}, and FlowNet2-CSS~\citep{FLOWNET2} which is a stack of three FlowNets. As shown in~\figref{flow1}, our result are comparable to LiteFlowNet~\citep{LITEFLOW} and PWC-Net~\citep{PWCNET} without refinement sub-net. FlowNet2 is more accurate by stacking networks, which is less efficient, more difficult to train, and increases the model size dramatically. Comparing with FlowNet2, our method is $12\times$ smaller in model size, $4\times$ faster in inference, and $32\times$ less in training time. Our LSM is better than LDOF~\citep{LARGFLO} and PCA-Layers~\citep{PCAFLO}, but less accurate than EpicFlow~\citep{EPIC}. However, conventional method are usually based on variational approaches and take 5-20 seconds to run, while our LSM takes only 25ms. \begin{figure}[h] \vspace{-5pt} \centering \vspace{-5pt}\subfigure[Average End-Point-Error]{\includegraphics[width=\linewidth,page=3]{figures/compare.pdf}\label{fig:flow1}} \vspace{-7pt}\subfigure[Our optical flow is comparable to PWC-Net.]{\includegraphics[width=\linewidth]{figures/flow2.png}\label{fig:flow2}} \vspace{-5pt} \caption{Flow trained on Flythings3D and tested on Sintel.} \vspace{-5pt} \label{fig:flow} \end{figure} \vspace{-10pt} \subsection{Zero-shot Task Generalization} Our LSM framework even generalizes the learned network to unseen tasks. It is different from the zero-shot task transfer~\citep{ZEROTANSFER}, where the network parameters are interpolated from existing tasks, and the interpolation coefficients is defined by a correlation matrix during training. In contrast, we fix the learned parameters and do not require any extra information between tasks. To demonstrate this capability, we train the network on three tasks with the same settings as the joint multi-task training, and leave one out for testing. \vspace{-10pt} \begin{figure}[h] \centering \includegraphics[width=\linewidth]{figures/disp_zero.png} \vspace{-15pt} \caption{Our zero-shot generalized LSM model performs better than PWC-Net for stereo matching.} \vspace{-5pt} \label{fig:stereo0} \end{figure} \paragraph{Stereo Matching} The first task left out for testing is stereo matching. Since none of existing CNN based method supports this test, we approximate it by estimating optical flow using PWC-Net~\citep{PWCNET} on stereo image pairs, and only consider the EPE on the horizontal direction. The average EPE is 2.47 for our LSM model learned on the other three tasks and tested on stereo matching, which is superior than the 5.29 EPE of PWC-Net as shown in~\figref{stereo0}. Note that our LSM consistently performs better than conventional methods~\citep{DSPSGM,Yamaguchi14,MCNET}, while PWC-Net is worse than SGM~\citep{DSPSGM}. \vspace{-10pt} \begin{figure}[h] \centering \includegraphics[width=\linewidth]{figures/flow_zero.png} \vspace{-15pt} \caption{Our zero-shot generalized LSM model performs better than LDOF for optical flow.} \vspace{-5pt} \label{fig:flow0} \end{figure} \paragraph{Optical Flow} For optical flow, none of CNN based method supports this zero-shot test, and the average EPE is 4.6 for our LSM model learned on the other three tasks, which is better than LDOF~\citep{LARGFLO}. However, LDOF requires computationally expensive dense HOG~\citep{HOG} feature matching as external input, while our LSM estimates the optical flow efficiently only by minimizing the feature-metric alignment error in~\equref{corr}.~\figref{flow0} shows that our zero-shot optical flow maintains the object-aware discontinuities, which indicates that the subspace generator learned from the other three tasks is general, while LDOF generates over-smoothed results because it uses the $L2$ smoothness regularization term. \vspace{-10pt} \begin{figure}[h] \centering \includegraphics[width=\linewidth]{figures/vidseg_zero.png} \vspace{-15pt} \caption{Our zero-shot generalized LSM model is more robust to occlusion than OFL~\citep{OFL} for video segmentation.} \vspace{-5pt} \label{fig:vidseg0} \end{figure} \paragraph{Video Segmentation} The third task left out for testing is video segmentation. The average IoU is 0.682 for our LSM model learned on the other tasks and tested on video segmentation, which is comparable to conventional methods such as OFL~\citep{OFL}. However, as shown in~\figref{vidseg0}, our method is more robust to partial occlusions, while OFL lost tracking of the bus when partially occluded by trees. Please refer to the~\emph{supplementary} for the zero-shot generalization test on interactive image segmentation due to the page limit. \subsection{Ablation Studies} \vspace{-10pt} \begin{figure}[ht] \centering \includegraphics[width=\linewidth,height=0.6\linewidth]{figures/ablation.pdf} \vspace{-20pt} \caption{Ablation studies on (a) solving~\equref{iter0} using CNNs as implicit solver, (b) generating subspace $\mathcal V$ without minimization context, and (c) minimization without subspace projection, \ie directly use~\equref{lsm}.} \vspace{-5pt} \label{fig:wo} \end{figure} \paragraph{CNN as Implicit Solver} The first question is whether the explicit minimization is necessary, i.e can we use CNN as an implicit solver and predict the solution directly from the image and the minimization context features? To answer this question, we keep the same network structure except the last convolution layer of the subspace generators, \ie the output of the subspace generator is reduced to one-channel and directly serves as the solution~${\bm{x}}$. Then the subspace generator becomes an implicit minimization solver, and the modified network is trained with the same training protocol. As shown in~\figref{wo}, without minimization, the interactive segmentation and the video segmentation's get lower IoU while the stereo matching and the optical flow get higher EPE, which indicates the explicit minimization is preferred than learning to minimize via CNNs for our LSM framework. \paragraph{Without Minimization Context} The second question is whether it is necessary to incorporate the minimization context into the subspace generation, i.e can we predict the subspace solely from the image features as in Code-SLAM~\citep{CODESLAM} and BA-Net~\citep{BA}? To answer this question, we predict the subspace without minimization context and keep the same network structure except the first several convolution layers after the multi-scale context features. The modified network is also trained with the same training protocol in~\secref{training}. As shown in~\figref{wo}, all the four tasks performs significantly worse without the minimization context, which indicates the minimization context is necessary for subspace generation. It is difficult to learn an unified subspace generator solely from image context, because different tasks requires different subspace even on the same image. \paragraph{Without Subspace Projection} Finally, we evaluate the effectiveness of the subspace projection proposed in~\secref{minimize}, \ie minimizing~\equref{lsm} instead of ~\equref{min_proj}. We also train the modified network for a fair comparison. As shown in~\figref{wo}, the network without the subspace projection performs worse than the original full pipeline, which indicates that maintaining the subspace constraint via projection is necessary not only in theory but also in practice for better performance. It is because, with the subspace projection, the predicted subspace $\mathcal{V}$ is learned to be consistently towards the ground truth solution. In contrast, learning without projection violates the subspace constraint, and make the minimization less constrained and training more difficult. \subsection{Visualization of Generated Subspaces} \vspace{-15pt} \begin{figure}[h] \includegraphics[width=\linewidth]{figures/png.png} \vspace{-20pt} \caption{Visualization of generated subspaces for optical flow and interactive segmentation.} \vspace{-5pt} \end{figure} As introduced in~\secref{intro}, the intuition of using a subspace constraint is the solution of a low-level task is usually composed of several layers. To verify whether the generated subspaces satisfy this intuition, we visualize some basis vectors as heat maps for the optical flow and the interactive segmentation tasks. As we can see, the basis vectors are consistent with the motion layers for optical flow and the foreground/background layers for segmentation, which also indicates that our subspace generation network captures the intrinsic characteristics of each task. \subsection{Optical Flow} The second task is optical flow, a two-dimensional dense correspondence estimation problem. \paragraph{Problem Formulation} Let $(u,v)$ be the 2D motion vector that warps the pixel coordinate ${\bm{p}}$ to ${\bm{w}}=(x+u,y+v)$ in the source image S. The feature channels should also be consistent and yield the pixel-wise objective function: \begin{equation} E(u,v)=\sum_{c=1}^{C}\|S_c({\bm{w}})-T_c({\bm{p}})\|_{2}^{2}. \end{equation} Simiar to disparity estimation, we also apply coarse-to-fine strategy and solve for an incremental update at each iteration by the feed-forward algorithm: \begin{equation} \begin{aligned} \Delta u^{*},\Delta v^{*}&=\argmin\sum_{c=1}^{C}\|S_c({\bm{w}}+\begin{bmatrix} \Delta u\\ \Delta v \end{bmatrix})-T_c({\bm{p}})\|_{2}^{2}\\ &\approx\argmin\sum_{c=1}^{C}\|S_c({\bm{w}})+[\frac{\partial S_c}{\partial {\bm{w}}_{x}},\frac{\partial S_c}{\partial {\bm{w}}_{y}}]\begin{bmatrix} \Delta u\\ \Delta v \end{bmatrix}-T_c({\bm{p}})\|_{2}^{2}\\ &={\left[ {\begin{array}{cc} \sum g_{x}^{2} & \sum g_{x}g_{y} \\ \sum g_{x}g_{y} & \sum g_{y}^{2} \\ \end{array} } \right]}^{-1} \left[ {\begin{array}{c} \sum s_{x}\\ \sum s_{y}\\ \end{array}} \right], \end{aligned} \label{equ:flow0} \end{equation} where $g_{x}$ and $g_{y}$ represent the spatial gradient of feature maps along x-axis and y-axis respectively, and $s_{x}$ and $s_{y}$ is the steepest descent update along x-axis and y-axis. Then the dense flow field update $\Delta {\bm{f}}$ can be solved by an unconstrained quadratic minimization: \begin{equation} \Delta{\bm{f}}^{*}=\argmin\frac{1}{2}\Delta {\bm{f}}^{\top}\left[ {\begin{array}{cc} {\bm{H}}_{xx} & {\bm{H}}_{xy} \\ {\bm{H}}_{xy} & {\bm{H}}_{yy} \\ \end{array} } \right]\Delta{\bm{f}}-[{\bm{s}}_x^{\top},{\bm{s}}_y^{\top}]\Delta {\bm{f}}, \label{equ:flow1} \end{equation} where ${\bm{H}}_{xx}=diag(G_{xx})$, ${\bm{H}}_{yy}=diag(G_{yy})$, ${\bm{H}}_{xy}=diag(G_{xy})$ are the corresponding diagonal matrix containing the gradient quantities for all pixels.\\ Solving~\equref{flow1} is also equivalent to operating~\equref{flow0} at all pixels. Following the formulation in~\equref{lsm_d}, we constraint the horizontal and vertical components of the dense flow field update $\Delta{\bm{f}}=[u_{1},u_{2}\cdots u_{N},v_{1},v_{2}\cdots v_{N}]^{\top}$ onto two independent subspaces and solve for the linear combination coefficients ${\bm{c}}_{u}$ and ${\bm{c}}_{v}$: \begin{equation} \begin{aligned} {\bm{c}}_{u}^{*},{\bm{c}}_{v}^{*}=\argmin\frac{1}{2}\left[\begin{array}{c}{\bm{c}}_{u}\\{\bm{c}}_{v}\end{array}\right]^{\top}\left[ {\begin{array}{cc} {\bm{V}}_{u}^{\top}{\bm{H}}_{xx}{\bm{V}}_{u} & {\bm{V}}_{u}^{\top}{\bm{H}}_{xy}{\bm{V}}_{v} \\ {\bm{V}}_{v}^{\top}{\bm{H}}_{xy}{\bm{V}}_{u} & {\bm{V}}_{v}^{\top}{\bm{H}}_{yy}{\bm{V}}_{v} \\ \end{array} } \right]\left[\begin{array}{c}{\bm{c}}_{u}\\{\bm{c}}_{v}\end{array}\right]-[{\bm{s}}_x^{\top}{\bm{V}}_{u},{\bm{s}}_y^{\top}{\bm{V}}_{v}]\left[\begin{array}{c}{\bm{c}}_{u}\\{\bm{c}}_{v}\end{array}\right]. \end{aligned} \label{equ:flow2} \end{equation} \paragraph{Learning Subspace} We apply the same principles and reuse the same network structures as in disparity estimation. However, concatenating the quantites in~\equref{flow0} generates minimization context features with different number of channels. In order to unify the subspace prediction for both disparity estimation and optical flow, we transform~\equref{flow0} by Cramer's rule~\citep{Higham}: \begin{equation} \begin{aligned} \Delta u^{*}&=det\left|{\begin{array}{cc} \sum s_{x} & \sum g_{x}g_{y} \\ \sum s_{y} & \sum g_{y}^{2} \\ \end{array} } \right|\bigg/det\left|{\begin{array}{cc} \sum g_{x}^{2} & \sum g_{x}g_{y} \\ \sum g_{x}g_{y} & \sum g_{y}^{2} \\ \end{array} } \right|\\ \Delta v^{*}&=det\left|{\begin{array}{cc} \sum g_{x}g_{y} &\sum s_{x}\\ \sum g_{y}^{2} &\sum s_{y}\\ \end{array} } \right|\bigg/det\left|{\begin{array}{cc} \sum g_{x}^{2} & \sum g_{x}g_{y} \\ \sum g_{x}g_{y} & \sum g_{y}^{2} \\ \end{array} } \right|, \end{aligned} \label{equ:flow3} \end{equation} where $det|\bigcdot|$ denotes the determinant value of a matrix.~\equref{flow3} enables sharing network structures between disparity estimation and optical flow because averaging the determinant values in~\equref{flow3} every $G$ channels generates $M$ channel minimization context features for the horizontal and the vertical components $\Delta {\bm{f}}$ respectively, which is identical to the disparity estimation. In addition,~\equref{flow3} even enables sharing network parameters because the determinant value gives the scaling factor and the orientation induced by a matrix, which has similar interpretations as the steepest descent update and the gradient norm. Please refer to the~\emph{supplementary materials} for detailed proof. \section{Introduction} \label{sec:intro} Many low-level vision tasks (\eg image segmentation~\citep{IMGSEG,TVSEG,Gulshan10}, video segmentation~\citep{BVS,OFL,DAC}, stereo matching~\citep{VARSTEREO1,VARSTEREO2,VARSTEREO3} and optical flow~\citep{HS,FLOWARP,Sun2014}) are conventionally formulated as an energy minimization problem: \vspace{-5pt} \begin{equation} \min_{{\bm{x}}}D({\bm{x}})+R({\bm{x}}), \label{equ:1} \vspace{-5pt} \end{equation} where ${\bm{x}}$ is the desired solution (\eg a disparity field for stereo matching), and the two terms $D({\bm{x}})$ and $R({\bm{x}})$ are the data term and regularization term respectively. The data term $D({\bm{x}})$ is usually well designed following the first principle of a task, such as the color consistency assumption in stereo and optical flow. However, the regularization term $R({\bm{x}})$ is often heuristic. Typically, it regularizes ${\bm{x}}$ at the~\emph{pixel-level} and encourages similar pixels to have similar solution values. The regularization term is necessary because low-level vision tasks are usually ill-posed~\citep{ILLPOSE}, and a standalone data term is often insufficient,~\eg the aperture problem in optical flow. However, a vanilla $L^2$ smoothness regularization~\citep{TAREG} may cause over-smoothed results at object boundaries. Ideally, the regularization term should smooth out noises in ${\bm{x}}$ and preserve sharp edges. Thus, many edge-preserving regularization terms have been developed, such as the Total Variation (TV) regularization~\citep{ROF,TVINTRO}, the anisotropic diffusion~\citep{PM}, the bilteral filter~\citep{BL} which focuses on designing better similarity measurements between pixels, and the distance in a learned feature embedding space~\citep{ROTH2009,LEARNFLO,SPN} has also been adopted for the same purpose. But it is still an unsolved problem to design an ideal similarity measurement for efficient and accurate energy minimization. We study this energy minimization problem from a different perspective. Instead of focusing on the \emph{pixel-level} similarity, we exploit \emph{image-level} context information. Specifically, we preserve the data term $D({\bm{x}})$ but replace the heuristic regularization term $R({\bm{x}})$ with a subspace constraint: \vspace{-5pt} \begin{equation} \min_{{\bm{x}}}D({\bm{x}}), \text{~s.t.~} {\bm{x}}\in\mathcal V=\text{span}\{{\bm{v}}_{1},\cdots{\bm{v}}_{K}\}, \label{equ:2} \vspace{-5pt} \end{equation} where $\mathcal V$ is a $K$-dimensional subspace, and~$\{{\bm{v}}_{1},\cdots{\bm{v}}_{K}\}$ is the corresponding basis vectors. Our motivation is different from the regularization term $R({\bm{x}})$: we use the~\emph{image-level} context information to regularize the problem by assuming the desired solution ${\bm{x}}$ is composited of several layers~\citep{LAYER1,LAYER2,LAYER3},~\eg motion layers for optical flow, and each basis vector ${\bm{v}}_k$ will correspond to one of these layers. Therefore, we can represent the solution ${\bm{x}}$ as a linear combination of these basis vectors and solve the combination coefficients, leading to a compact minimization that~\emph{not only} is efficient~\emph{but also} enables end-to-end training and outperforms the conventional regularization term $R({\bm{x}})$. To this end, we propose the \emph{learning subspace minimization} (LSM) framework that progressively evolves $\mathcal V$ and solves~\equref{2} on a feature pyramid coarse-to-fine. At each pyramid level, we employ a convolutional neural network (CNN) to update $\mathcal V$ from both the image features and the derivatives of the data term $D({\bm{x}})$ respect to the intermediate solution ${\bm{x}}$. Since the generation of $\mathcal V$ receives the task-specific data term as the~\emph{input}, it decouples the task-specific characteristics from the subspace generation and unifies the network structures and the parameters for various tasks. As a consequence, our LSM framework enables joint multi-task learning with~\emph{completely} shared network structures as well as parameters, and even makes zero-shot task generalization possible, where a trained network is plug-and-play for an unseen task without any parameter modification, as long as the corresponding data term $D({\bm{x}})$ is formulated. In the experiments, we implement four low-level vision tasks in an unified paradigm, including interactive image segmentation, video segmentation, stereo matching and optical flow. Our LSM framework has achieved better or comparable results with state-of-the-art methods. Our network structures and parameters can be unified into a compact model, which yields higher efficiency in training and inference. We also demonstrate zero-shot task generalization by leaving one task out for testing and train on the other tasks. All these benefits come from our methodology that integrates domain knowledge (\ie minimizing a data term derived from the first principle) with convolutional neural networks (\ie learning to generate subspace constraint). \subsection{Subspace Generation} \label{sec:lsm} \begin{figure*}[h] \vspace{-5pt} \centering \includegraphics[width=\textwidth]{figures/subspace.pdf} \vspace{-15pt} \caption{Subspace generation from the image and the minimization context features. The spatial sizes of all feature maps are the same to the $F$ from a feature pyramid level. Integral image is used for the efficient construction of the multi-scale features.} \vspace{-5pt} \label{fig:SL} \end{figure*} Before introducing the network that generates $\mathcal{V}$, we first propose two principles for the subspace generation: \begin{itemize} \vspace{-5pt} \item First, \emph{the image context matters.} Standalone data terms are often insufficient for low-level vision tasks as introduced in~\secref{intro}, because these tasks are usually ill-posed~\citep{ILLPOSE,TAREG}. So it is necessary to consider the image context information to generate the subspace $\mathcal{V}$, which enforces each basis vector ${\bm{v}}_{k}$ to be spatially smooth except for discontinuities at object boundaries. \vspace{-5pt} \item Second, \emph{the minimization context matters}. The objective function (data term) is minimized iteratively. At each iteration, the intermediate solution ${\bm{x}}$ is at a different location on the objective function landscape, and the local curvature of the objective function decides the direction and magnitude of the desired incremental solution $\Delta {\bm{x}}$ for the minimization. So it is also necessary to incorporate the minimization context into the subspace generation, which learns to narrow the gap between the estimated solution and the ground truth. \end{itemize} \vspace{-5pt} Following these two principles, we learn to generate the subspace $\mathcal{V}$ as illustrated in~\figref{SL}: \begin{itemize} \vspace{-5pt} \item First, we compute a $m$-channel image context from the original $c$-channel feature map $F$ by $1\times1$ convolution, where $m=c/8$ and is $\{64,32,16,8\}$ at the corresponding pyramid level. This step reduces the computation complexity for the following up procedures and balances the impact between the image context and the minimization context. \vspace{-5pt} \item Second, we compute a $2m$-channel minimization context. Specifically, we split the $c$-channel feature map(s) into $m$ groups. Within each group, we evaluate the data term $D(x)$ with the associated feature maps, compute the first-order derivative $\frac{\partial D}{\partial{\bm{x}}}$ and the second-order derivatives $\frac{\partial^{2}D}{{\bm{x}}^{2}}$, which approximate the objective landscape neighborhood. We concatenate these derivatives to form a $2m$-channel minimization context features. \vspace{-5pt} \item In the next, we normalize the intermediate solution ${\bm{x}}$ with its mean and variance, and concatenate the normalized ${\bm{x}}$, the image context, and the minimization context to form a $(3m+1)$-channel input features for subspace generation. To aggregate the context information in multi-scale, we average pool the context features in $4$ different kernel sizes without stride, which maintains the spatial size of a feature map. Specifically, we first compute the integral images~\citep{HARR,GF} of the context features and then average neighboring features at each pixel coordinate, which gives better efficiency. \vspace{-5pt} \item Finally, we apply a $1\times1$ convolution to project a feature map to $2m$-channel at each scale individually and concatenate them to get the $8m$-channel multi-scale features. Therefore, we can generate the $K$-dimensional subspace $\mathcal{V}$ from the multi-scale features via four residual blocks~\citep{RESNET} followed by a $1\times1$ convolution, and $K$ is $\{2,4,8,16\}$ at the corresponding pyramid level. \end{itemize} \subsection{Subspace Minimization} \label{sec:minimize} \begin{figure}[h] \vspace{-20pt} \centering \subfigure[${\bm{x}}\leftarrow{\bm{x}}+{\bm{V}}{\bm{c}}$]{\includegraphics[height=0.17\textwidth,trim = 0cm 0cm 11.6cm 0cm,clip]{figures/project.pdf}\label{fig:project_off}} \subfigure[${\bm{x}}\leftarrow{\bm{x}}+{\bm{r}}+{\bm{V}}{\bm{c}}$]{\includegraphics[height=0.17\textwidth,trim = 11.0cm 0cm 0cm 0cm,clip]{figures/project.pdf}\label{fig:project_on}} \vspace{-5pt} \caption{A 2D example where (a): the subspace constraint is violated, \ie the 2D vector ${\bm{x}}+{\bm{V}}{\bm{c}}$ is not on the 1D subspace $\mathcal V$, and (b): the subspace constraint is maintained, \ie ${\bm{x}}+{\bm{r}}+{\bm{V}}{\bm{c}}$ is on $\mathcal V$, by considering the residual ${\bm{r}}$ between ${\bm{x}}$ and its projection on $\mathcal V$.} \vspace{-5pt} \label{fig:project} \end{figure} After the subspace $\mathcal V$ is generated, we can solve~\equref{lsm} directly as ${\bm{c}}=-({\bm{V}}^{\top}{\bm{D}}{\bm{V}})^{-1}{\bm{V}}^{\top}{\bm{d}}$ because ${\bm{V}}^{\top}{\bm{D}}{\bm{V}}$ is positive-definite by definition, and update the current intermediate solution as ${\bm{x}}\leftarrow{\bm{x}}+{\bm{V}}{\bm{c}}$. However, it will violate the subspace constraint as shown in~\figref{project_off}, because the subspace $\mathcal{V}$ is generated progressively, i.e, the current solution ${\bm{x}}$ belongs to the subspace from last iteration but is not guaranteed to be on the newly generated $\mathcal{V}$, so is ${\bm{x}}+{\bm{V}}{\bm{c}}$. To address this issue, we propose to project ${\bm{x}}$ onto the current subspace $\mathcal V$ and reformulate~\equref{lsm} as follows: \vspace{-5pt} \begin{itemize} \item Denoting ${\bm{P}}={\bm{V}}({\bm{V}}^{\top}{\bm{V}})^{-1}{\bm{V}}^{\top}$ is the projection matrix that projects an arbitrary vector onto the the subspace $\mathcal V$, we can compute its projection onto $\mathcal V$ as ${\bm{x}}^{\prime}={\bm{P}}{\bm{x}}$, and the residual vector from ${\bm{x}}$ to ${\bm{x}}^{\prime}$ is ${\bm{r}}=({\bm{P}}-{\bm{I}}){\bm{x}}$. \vspace{-5pt} \item Theoretically, we can reevaluate ${\bm{D}}$ and ${\bm{d}}$ respect to ${\bm{x}}^{\prime}$ and solve~\equref{lsm}, but it requires extra computation. So we reparameterize the incremental solution $\Delta{\bm{x}}$ as ${\bm{r}}+{\bm{V}}{\bm{c}}$ and transform~\equref{lsm} into: \vspace{-5pt} \begin{equation} \min_{{\bm{c}}}\frac{1}{2}({\bm{r}}+{\bm{V}}{\bm{c}})^{\top}{\bm{D}}({\bm{r}}+{\bm{V}}{\bm{c}})+{\bm{d}}^{\top}({\bm{r}}+{\bm{V}}{\bm{c}}), \vspace{-5pt} \label{equ:min_proj} \end{equation} \vspace{-5pt} where we can compute ${\bm{c}}$ as \begin{equation} \vspace{-5pt} {\bm{c}}=-({\bm{V}}^{\top}{\bm{D}}{\bm{V}})^{-1}{\bm{V}}^{\top}({\bm{d}}+{\bm{D}}{\bm{r}}) \vspace{-2pt} \end{equation} without recomputing ${\bm{D}}$ and ${\bm{d}}$, and update ${\bm{x}}$ as ${\bm{x}}+{\bm{r}}+{\bm{V}}{\bm{c}}$ as shown in~\figref{project_on}. \end{itemize} \section{Model Efficiency} Our LSM model is efficient in terms of model size, training time, and inference time, which are contributed by integrating data terms explicitly. \subsection{Model Size} We implement our LSM framework with the aforementioned settings, which contains about 15M parameters and costs 57.26 MB in memory. As shown in~\figref{size}, our LSM model maintains a relatively small model size when compared with other CNN based methods. But our LSM model handles multiple tasks within the same parameters while others are designed specifically for single tasks. \subsection{Training Efficiency} We train our model with 143.2K iterations for all the experiments, which tasks roughly 20 hours and is relatively faster compared to existing CNN based methods. For example, training FlowNet2~\citep{FLOWNET2} tasks more than 14 days and PWC-Net~\citep{PWCNET} takes 4.8 days. We initialize the backbone DRN-22 from the ImageNet pre-trained model, which also helps the training converges faster~\citep{RETHINK}. \subsection{Inference Efficiency} Our LSM framework is also efficient during inference. Since we unify different tasks into a single network, the inference times for various tasks are roughly the same, which consume about 25ms for $512\times384$ images. The computation is dominated by the feature pyramid construction, the subspace generation and the minimization. \section{Learning Subspace Minimization} \subsection{Overview} As illustrated in~\figref{pyramid}, we first build a feature pyramid $\mathcal F$ for~\emph{each} image $I$ from a set, where the number of images in a set depends on the task,~\eg the interactive segmentation is defined on a single image, the stereo matching and the optical flow are defined on two images, and the video segmentation processes three or more images. The output of the pyramid $\mathcal F$ are feature maps in four levels $\{F^{1},F^2,F^3,F^{4}\}$ with strides $\{32,16,8,4\}$ and channels $\{512,256,128,64\}$ respectively, which are constructed by similar strategy as FPN~\citep{FPN} but using DRN-22~\citep{DRN} as the backbone network. At each pyramid level, we define the data term $D({\bm{x}})$ of a task on CNN features (\secref{app}) and solve~\equref{2}.~$D({\bm{x}})$ is approximated using the second-order Taylor expansion at the intermediate solution ${\bm{x}}$ and yields the following quadratic minimization problem: \vspace{-5pt} \begin{equation} \min_{\Delta{\bm{x}}}\frac{1}{2}\Delta {\bm{x}}^{\top}{\bm{D}}\Delta{\bm{x}}+{\bm{d}}^{\top}\Delta {\bm{x}}, \vspace{-5pt} \label{equ:iter0} \end{equation} where ${\bm{D}}$ is the matrix that contains the (approximated) second-order derivatives $\frac{\partial^{2}D}{{\bm{x}}^{2}}$ of the data term, ${\bm{d}}$ is the vector that contains the first-order derivatives $\frac{\partial D}{\partial{\bm{x}}}$, and $\Delta {\bm{x}}$ is the desired incremental solution. The structure of ${\bm{D}}$ is task dependent: it is a diagonal matrix for one-dimensional tasks or block diagonal for multi-dimensional tasks. To maintain the subspace constraint of~\equref{2}, we represent the incremental solution $\Delta {\bm{x}}$ as a linear combination of a set of underlying basis vectors,~\ie $\Delta {\bm{x}}=c_1{\bm{v}}_{1}+c_2{\bm{v}}_{2}\cdots+c_K{\bm{v}}_{K}$, and then solve the combination coefficients ${\bm{c}}=[c_1,c_2\cdots c_K]^{\top}$ as: \vspace{-5pt} \begin{equation} \begin{aligned} \min_{{\bm{c}}}\frac{1}{2}{\bm{c}}^{\top}({\bm{V}}^{\top}{\bm{D}}{\bm{V}}){\bm{c}}+({\bm{d}}^{\top}{\bm{V}}){\bm{c}}, \end{aligned} \vspace{-5pt} \label{equ:lsm} \end{equation} where ${\bm{V}}$ is a dense matrix, and its columns correspond to the $K$ basis vectors from $\mathcal{V}$. As shown in~\figref{singleiter}, we generate this $\mathcal{V}$ from the image and the minimization context information (\secref{lsm}), solve minimization with subspace constraint (\secref{minimize}), and move to the next pyramid level after updating the intermediate solution as ${\bm{x}}\leftarrow{\bm{x}}+\Delta{\bm{x}}$. This formulation is easy and efficient to implement because multiplying the dense matrix ${\bm{V}}$ with the (block) diagonal matrix ${\bm{D}}$ can be done by column-wise product, yielding a compact $K\text{-by-}K$ linear system, which can be solved using direct solver such as Cholesky decomposition~\citep{MATRIX}, instead of iterative solvers such as conjugate gradient descent~\citep{NUMOPT}. Therefore,~\equref{lsm} is differentiable and supports end-to-end training without unrolling or implicit gradient~\citep{Domke2012}. \section{Related Works} \paragraph{Regularization in Variational Method} Many computer vision problems can be formulated to~\equref{1}. We only review the continuous settings (\ie variational method) because it is more relevant to our work and refer readers to~\citep{kohli2012higher-order} for the review about the discrete settings. One of the main focuses of these works is on designing appropriate objective function, especially the regularization term. \cite{ROF} first proposed the TV regularization for image denoising, which has also been proven to be successful for image super-resolution~\citep{TVSUP}, interactive image segmentation~\citep{TVSEG}, stereo matching~\citep{VARSTEREO1}, optical flow~\citep{TVFLOW1,TVFLOW2}, multi-view stereo~\citep{TVMV},~\emph{etc}.~\citet{PM} pioneered to use partial differential equations (PDE) for anisotropic diffusion, which is equivalent to minimizing an energy function with edge-aware regularization~\citep{EDGEAW1,BL}. Non-local regularizations~\citep{nonlocals2} have also been proposed for image super-resolution~\citep{nonlocalsup}, image inpainting~\citep{nonlocal2}, optical flow~\citep{NONLOCALS},~\emph{etc}, which performs better by connecting longer range pixels but is usually computational expensive. Our LSM framework also minimizes an objective function. But we only preserve the data term since it is usually derived from the first principle of a task, and replace the heuristic regularization term to a learned subspace constraint that captures the structure of the desired solution at the whole image context level and enables end-to-end training to boost the performance from data. \paragraph{Convolutional Neural Networks} Inspired by the success of CNNs in high-level tasks~\citep{ALEXNET,VGG,RESNET}, numerous CNN based methods have been proposed for low-level vision tasks.~\cite{SRCNN} pioneered to use a CNN to upsample image patches for super-resolution. \cite{zbontar2016stereo} and~\cite{7780983} used CNN features to measure image patches' similarity for stereo matching,~\cite{XRK2017} and~\cite{FF} also used CNN based similarity for optical flow. All these methods used CNNs in the patch level, which is computationally expensive and requires post-processing to composite the final result. So more recent works used whole images as inputs.~\cite{FLOWNET} used an encoder-decoder structure for optical flow, which is then extended to stereo matching~\citep{SYNDATA} and further evolved in~\cite{FLOWNET2,FLOWNET3} and other works~\citep{PWCNET,PSMNET,Yin_2019_CVPR}. Some recent works~\citep{DIOS,LATENT,BRS} enabled interactive image segmentation by feeding an image and an user annotation map to CNNs. Meanwhile, CNN based methods~\citep{MASKRNN,VIDEOMATCH,FEELVOS,MASKTRACK} have also achieved leading performance for video segmentation. Our LSM framework also employs CNNs but for different purposes. Instead of predicting the solution directly, we use CNNs to constraint the solution onto a subspace to facilitate the minimization of the data term. The data term is derived from the first principle of each task and decouples the task-specific formulation from the network parameters. Therefore, our framework unifies the network structures as well as parameters for different tasks and even enables zero-shot task generalization, which are difficult for fully CNN based methods. Although some recent works~\citep{CODESLAM,BA} also learn to generate subspace via CNNs, they are designed specifically for 3D reconstruction, which is ad-hoc and unable to generalize to broader low-level vision tasks. \section{Derivatives of Various Data Terms $D({\bm{x}})$} \label{sec:a_app} In Sec~3.4, we introduced two categories of tasks. Now, we show the first-order and the (approximated) second-order derivatives of the data terms, which compose the vector ${\bm{d}}$ and the (block) diagonal matrix ${\bm{D}}$ at each iteration. \paragraph{Binary Image Labeling} Recall that the first category is binary image labeling (interactive segmentation and video segmentation) as: \begin{equation} D({\bm{x}})=\sum_{{\bm{p}}}\alpha_{\bm{p}}\|\tau({\bm{x}}_{\bm{p}})-1\|_{2}^{2}+\beta_{\bm{p}}\|\tau({\bm{x}}_{\bm{p}})+1\|_{2}^{2}, \label{equ:bin} \end{equation} where ${\bm{p}}=[x,y]^{\top}$ is a pixel coordinate, $\tau$ is an activation function to relax the binary label $\tau({\bm{x}}_{\bm{p}})$ between $(+1,-1)$, and $\alpha_{\bm{p}}$ and $\beta_{\bm{p}}$ are the probabilities that $\tau({\bm{x}}_{{\bm{p}}})=+1 \text{ or}-1$. Therefore, the first-order and the second-order derivatives at an intermediate solution ${\bm{x}}$ are: \begin{equation} \begin{aligned} \frac{\partial D}{\partial{\bm{x}}_{\bm{p}}}=&[(\alpha_{{\bm{p}}}+\beta_{{\bm{p}}})\tau({\bm{x}}_{\bm{p}})+(\beta_{{\bm{p}}}-\alpha_{{\bm{p}}})][\frac{\partial\tau({\bm{x}}_{\bm{p}})}{\partial{\bm{x}}_{\bm{p}}}],\\ \frac{\partial^{2} D}{\partial{\bm{x}}_{\bm{p}}^{2}}=&(\alpha_{{\bm{p}}}+\beta_{{\bm{p}}})[\frac{\partial\tau({\bm{x}}_{\bm{p}})}{\partial{\bm{x}}_{\bm{p}}}]^{2}, \end{aligned} \end{equation} where we ignore the scale factor $2$ for simplicity, and $\frac{\partial\tau({\bm{x}}_{\bm{p}})}{\partial{\bm{x}}_{\bm{p}}}$ can be $1-\tau^{2}({\bm{x}}_{\bm{p}})$ for $tanh$ activation function. \paragraph{Dense Correspondence Estimation} The second category is the dense correspondence estimation (stereo matching and optical flow) where the data term is: \begin{equation} D({\bm{x}})=\sum_{{\bm{p}}}\|F_{S}({\bm{p}}+{\bm{x}}_{{\bm{p}}})-F_{T}({\bm{p}})\|_{2}^{2}. \label{equ:corr} \end{equation} For stereo matching, the derivatives are derived as: \begin{equation} \begin{aligned} \frac{\partial D}{\partial{\bm{x}}_{\bm{p}}}=&\nabla_{x} F_{S}({\bm{p}}+{\bm{x}}_{{\bm{p}}})^{\top}[F_{S}({\bm{p}}+{\bm{x}}_{{\bm{p}}})-F_{T}({\bm{p}})],\\ \frac{\partial^{2} D}{\partial{\bm{x}}_{\bm{p}}^{2}}=&\|\nabla_{x} F_{S}({\bm{p}}+{\bm{x}}_{{\bm{p}}})\|_{2}^{2}, \end{aligned} \label{equ:stereo0} \end{equation} where $\nabla_{x}$ is the gradient operator along the horizontal direction. $\nabla_{x} F_{S}({\bm{p}}+{\bm{x}}_{{\bm{p}}})$ and $[F_{S}({\bm{p}}+{\bm{x}}_{{\bm{p}}})-F_{T}({\bm{p}})]$ are vectors, so $\frac{\partial D}{\partial{\bm{x}}_{\bm{p}}}$ and $\frac{\partial^{2} D}{\partial{\bm{x}}_{\bm{p}}^{2}}$ are scalars, which is also an one-dimensional problem and can be unified with the binary image label tasks with the same network and the parameters. \begin{figure*} \vspace{-5pt} \centering \includegraphics[width=\textwidth,page=1]{figures/size.pdf}\label{fig:size} \vspace{-5pt} \caption{Our LSM model handles multiple tasks in a relatively small model.} \vspace{-5pt} \label{fig:size} \end{figure*} For optical flow, ${\bm{x}}_{{\bm{p}}}=[u,v]^{\top}$ is a 2D vector and the derivatives are: \begin{equation} \begin{aligned} \frac{\partial D}{\partial{\bm{x}}_{\bm{p}}}=&\nabla F_{S}({\bm{p}}+{\bm{x}}_{{\bm{p}}})^{\top}[F_{S}({\bm{p}}+{\bm{x}}_{{\bm{p}}})-F_{T}({\bm{p}})],\\ \frac{\partial^{2} D}{\partial{\bm{x}}_{\bm{p}}^{2}}=&\nabla F_{S}({\bm{p}}+{\bm{x}}_{{\bm{p}}})^{\top}\nabla F_{S}({\bm{p}}+{\bm{x}}_{{\bm{p}}}), \end{aligned} \label{equ:flow0} \end{equation} where $\nabla$ is the gradient operator along both the horizontal and vertical direction. Therefore, $\frac{\partial D}{\partial{\bm{x}}_{\bm{p}}}$ is a $2\times1$ vector, and $\frac{\partial^{2} D}{\partial{\bm{x}}_{\bm{p}}^{2}}$ is a $2\times2$ matrix, which makes unification with other one-dimensional tasks difficult. To address this problem, we apply Cramer’s rule~\citep{Higham} as follows: \begin{itemize} \vspace{-5pt} \item First, we compute the determinant of $\frac{\partial^{2} D}{\partial{\bm{x}}_{\bm{p}}^{2}}$ as $det_{{\bm{p}}}$. \vspace{-5pt} \item Next, we replace the first column of $\frac{\partial^{2} D}{\partial{\bm{x}}_{\bm{p}}^{2}}$ with $\frac{\partial D}{\partial{\bm{x}}_{\bm{p}}}$, and denote the determinant of the modified matrix as $det^{x}_{{\bm{p}}}$. Similarly, $det^{y}_{{\bm{p}}}$ is computed by replacing the second column of $\frac{\partial^{2} D}{\partial{\bm{x}}_{\bm{p}}^{2}}$ with $\frac{\partial D}{\partial{\bm{x}}_{\bm{p}}}$. \vspace{-5pt} \item Finally, we collect $det^{x}_{{\bm{p}}}$ and $det_{{\bm{p}}}$ at all pixel locations as the minimization context, concatenate it with the image context to generate the subspace $\mathcal{V}_{x}$ for the horizontal component of the flow field. Similarly, the $det^{y}_{{\bm{p}}}$ and the $det_{{\bm{p}}}$ are collected as the minimization context for the vertical subspace $\mathcal{V}_{y}$. Thus the subspace generation for optical flow is unified with other one-dimensional tasks by generating the subspace for the horizontal and the vertical components of flow individually. \end{itemize} \section{Zero-shot Interactive Segmentation} Similar to the other zero-shot generalization tests in Sec. 4.3, we also leave the interactive segmentation out for testing and train on the other tasks. When interact only once, the average IoU is 0.802 for our LSM model learned on the other tasks and tested on the interactive segmentation. Which is still superior than the conventional method~\citep{Gulshan10,RANDOMWALK} as shown in~\figref{int0}. \begin{figure}[h] \vspace{-5pt} \centering \includegraphics[width=0.99\linewidth]{figures/intseg_zero.png} \vspace{-5pt} \caption{Our zero-shot generalized LSM model performs better than GSC~\citep{Gulshan10} for interactive segmentation.} \vspace{-5pt} \label{fig:int0} \end{figure}
{'timestamp': '2020-04-21T02:24:58', 'yymm': '2004', 'arxiv_id': '2004.09197', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09197'}
arxiv
\section{Introduction} Humans and animals are capable of continually acquiring and updating knowledge throughout their lifetime. The ability to accommodate new knowledge while retaining previously learned knowledge is referred to as \emph{incremental or continual learning}, which is essential to building scalable and reusable artificially intelligent systems. Current deep neural networks have achieved impressive performance on many benchmarks, comparable or even better than humans (e.g. image classification~\cite{he2015delving}). However, when trained for new tasks, these networks almost completely forget the previous ones due to the problem of \textit{catastrophic forgetting}~\cite{mccloskey1989catastrophic} between the new and previously-learned tasks. \introfigure To overcome \textit{catastrophic forgetting} several approaches, inspired in part by biological systems, have been proposed. The first category of approaches use regularizers that limit the plasticity of the network while training on new tasks so the network remains stable on previous ones~\cite{aljundi2018memory,kirkpatrick2017overcoming,li2018learning,liu2018rotate,zenke2017continual}. Another type of approach involves dynamically increasing the capacity of the network to accommodate new tasks~\cite{lee2017lifelong,rusu2016progressive}, often combined with task-dependent masks on the weights~\cite{mallya2018piggyback,mallya2018packnet} or activations~\cite{serra2018overcoming} to reduce the chance of catastrophic forgetting. A third category of approaches relies on memory replay, i.e. replaying samples of previous tasks while learning with the samples of the current task. These samples could be real ones ('exemplars'), like in~\cite{chaudhry2018riemannian,lopez2017gradient,rebuffi2017icarl} in which we refer to the process as 'rehearsal' or could be synthethic ones obtained through generative mechanisms, in which case we refer to the process as 'pseudo-rehearsal'~\cite{robins1995catastrophic,shin2017continual,wu2018memory}. Incremental learning methods are typically evaluated and designed for a particular testing scenario~\cite{van2019three}. Task-incremental learning considers the case where the task ID is given at inference time~\cite{lopez2017gradient, mallya2018packnet, serra2018overcoming}. Class-incremental learning considers the more difficult scenario in which the task ID is unknown at testing time \cite{hou2019learning,rebuffi2017icarl,wu2019large}. Recently, research attention has shifted from task-incremental to class-incremental learning. The main additional challenge, which class-incremental methods have to address, is balancing the different classifier heads. The imbalance problem occurs because during training of the current task there is none or only limited data available from previous tasks, which biases the classifier towards the most recently learned task. Various solutions to this problem have been proposed. iCarL\cite{rebuffi2017icarl} stores a fixed budget of exemplars from previous tasks in a way that exemplars approximate the mean of classes in the feature space. The nearest-mean classifier is used for inference. Wu et al.~\cite{wu2019large} found that the last fully-connected layer has a strong bias towards new classes, and corrected the bias with a linear model estimated from exemplars. Hou et al.~\cite{hou2019learning} replace the softmax with a cosine similarity-based loss, which, combined with exemplars, addresses the imbalance problem. All these methods have in common that they require storage of exemplars. However, for many applications -- especially due to privacy concerns or storage restrictions -- it is not possible to store \emph{any} exemplars from previous tasks. The only methods which successfully addresses the imbalance problem without requiring any exemplars are methods performing generative replay~\cite{shin2017continual,wu2018memory}. These methods train a generator continuously to generate samples of previous tasks, and therefore prevent the imbalance problem. Thus, these methods report excellent results for class-incremental learning. However, they have one major drawback: the generator should accurately generate images from previous task distributions. For small data sets like MNIST and CIFAR-10 this is feasible, however, for larger datasets with more classes and larger images (like CIFAR-100 and ImageNet) these methods yield unsatisfactory results. In this paper, we propose a novel approach based on generative feature replay to overcome catastrophic forgetting in class-incremental continual learning. Our approach is motivated by the fact that image generation is a complex process when the number of images is limited or the number of classes is high. Therefore, instead of image generation we adopt feature generation which is considerably easier than accurately generating images. We split networks into two parts: a feature extractor and a classifier. To prevent forgetting in the entire network, we combine generative feature replay (in the classifier) with feature distillation on the feature extractor. To summarize, our contributions are: \begin{itemize} \item We design a hybrid model for class-incremental learning which combines generative feature replay at the classifier level and distillation in the feature extractor. \item We provide visualization and analysis based on Canonical Correlation Analysis (CCA) of how and where networks forget in order to offer better insight. \item We outperform other methods which do not use exemplars by a large margin on the ImageNet and CIFAR-100 datasets. Notably, we also outperform methods using exemplars for most of the evaluated settings. Additionally, we show that our method is computationally efficient and scalable to large datasets. \end{itemize} \section{Related Work} \label{sec:related} \subsection{Continual learning} Continual learning can be divided into three main categories as follows (more details in the surveys~\cite{de2019continual,parisi2019continual}): \minisection{Regularization-based methods.} A first family of techniques is based on regularization. They estimate the relevance of each network parameter and penalize those parameters which show significant change when switching from one task to another. The difference between these methods lies on how the penalization is computed. For instance, the EWC approach in~\cite{kirkpatrick2017overcoming,liu2018rotate}, weights network parameters using an approximation of the diagonal of the Fisher Information Matrix (FIM). In~\cite{zenke2017continual}, the importance weights are computed online. They keep track of how much the loss changes due to a change in a specific parameter and accumulate this information during training. A similar approach is followed in \cite{aljundi2018memory}, but here, instead of considering the changes in the loss, they focus on the changes on activations. This way, parameter relevance is learned in an unsupervised manner. Instead of regularizing weights, ~\cite{jung2018less,li2018learning} align the predictions using the data from the current task. \minisection{Architecture-based methods.} A second family of methods to prevent catastrophic forgetting produce modifications in a network's morphology by growing a sub-network for each task, either logically or physically~\cite{lee2017lifelong,rusu2016progressive}. Piggyback~\cite{mallya2018piggyback} and Packnet~\cite{mallya2018packnet} and learn a separate mask for each task, while HAT~\cite{serra2018overcoming} and Ternary Feature Masks~\cite{masana2020ternary} learn a mask on the activations instead of for each parameter. \minisection{Rehearsal-based methods.} The third and last family of methods to prevent catastrophic forgetting are rehearsal-based. Existing approaches use two strategies: either store a small number of training samples from previous tasks or use a generative mechanism to sample synthetic data from previously learned distributions. In the first category, iCaRL~\cite{rebuffi2017icarl} stores a subset of real data (called \emph{exemplars}). For a given memory budget, the number of exemplars stored should decrease when the number of classes increases, which inevitably leads to a decrease in performance. A similar approach is pursued in~\cite{lopez2017gradient}, but the gradients of previous tasks are preserved. An improved version of this approach overcomes some efficiency issues~\cite{chaudry2019AGEM}. In~\cite{hou2019learning} the authors propose two losses called the less-forget constraint and inter-class separation to prevent forgetting. The less-forget constraint minimizes the cosine distance between the features extracted by the original and new models. The inter-class separation separates the old classes from the new ones with the stored exemplars used as anchors. In~\cite{wu2019large,belouadah2019il2m}, a bias correction layer to correct the output of the original fully-connected layer is introduced to address the data imbalance between the old and new categories. In~\cite{pellegrini2019latent}, they propose to store activations for replay and a slow-down learning at all the layers below the replay layer. Methods in the second category do not store any exemplars, but introduce a generative mechanism to sample data from. In~\cite{shin2017continual}, memory replay is implemented with an unconditional GAN, where an auxiliary classifier is required in order to determine which class the generated samples belong to. An improved version of this approach was introduced in~\cite{wu2018memory}, where they use a class-conditional GAN to generate synthetic data. In contrast, FearNet~\cite{kemker2017fearnet} uses a generative autoencoder for memory replay and ~\cite{xiang2019incremental} generates intermediate features. Using the class statistics from the encoder, synthetic data for previous tasks is generated based on the mean and covariance matrix. The main limitation of this approach is the assumption of a Gaussian distribution of the data and the reliance on pretrained models. \subsection{Generative adversarial networks} Generative adversarial networks (GANs)~\cite{goodfellow2014generative} are able to generate realistic and sharp images conditioned on object categories \cite{grinblat2017class,perarnau2016invertible}, text \cite{reed2016text2image,zhang2017text2image}, another image (image translation) \cite{kim2017image2image,zhu2017image2image} and style transfer \cite{dumoulin2017artistic}. In the context of continual learning, they were successfully been used for memory replay, by generating synthetic samples from previous tasks \cite{wu2018memory}. Here we are going to analyze the GANs limitations and argue why GANs for feature generation are preferable over image generation. \minisection{Adversarial image generation.} Although GANs achieved impressive performance recently, in order to generate high-resolution images \cite{brock2019biggan,Karras2018progressivegan}, they are not immune to common GAN problems such as stability (solutions are available at a high computational costs) and the need for a large training set of real images. Additionally, the generation of high-resolution images does not guarantee that they are able to capture a large enough variety of visual concepts with a good discriminative power \cite{dai2017badgan}. Only recently, the authors in \cite{lucic2019hifigan} proposed to uses high resolution images. However, they are not yet sufficient to generate high quality images for the downstream tasks, for instance training a deep neural network classifier. In the case of few-shot and zero-shot learning, only few samples or no sample are existing to train the GANs, which results in even more challenges to generate useful images. \minisection{Adversarial feature generation.} Recently, feature generation has appeared as an alternative to image generation, especially for the cases of few-shot learning, demonstrating superior performance. In \cite{xian2018feature}, they propose a GAN architecture with a classifier on top of the generator, in order to generate features that are better suited for classification. The same idea is further improved in \cite{xian2019f}, where they combine a better feature generator by combining the strength of a VAE and a GAN. In the current work, we use adversarial feature generation for memory replay in a continual learning framework. As demonstrated in~\cite{xian2018feature,xian2019f}, feature generation has achieved superior performance compared to image generation for zero-shot and few-shot learning. \ccafigure \section{Forgetting in feature extractor and classifier \label{sec:analyzing} In this section, we take a closer look at how forgetting occurs at different levels in a CNN. \subsection{Class-incremental learning} \minisection{Classification model and task.} We consider classification tasks learned from a dataset $\mathcal{D}=\left\{\left(\mathbf{x}_i,y_i\right)\right\}_{i=1}^{N}$, where $\mathbf{x}_i\in \mathcal{X}$ is the $i$th image, $y_i\in \mathcal{C}$ is the corresponding label (from a vocabulary of $K$ classes) and $N$ is the size of the dataset. The classifier network has the form $\mathbf{\tilde y}=M\left(\mathbf{x};\theta,V\right)=H\left(F\left(\mathbf{x};\theta\right);V\right)$ , where we explicitly distinguish between \textit{feature extractor} $F\left(\mathbf{x};\theta\right)$, parametrized by $\theta$, and \textit{classifier} $H\left(\mathbf{u}; V \right)=\mathcal{A}\left(V\mathbf{u}\right)$, where $V$ is a matrix projecting the output of the feature extractor $\mathbf{u}$ to the class scores (in the following we omit parameters $\theta$ and $V$), and $\mathcal{A}$ is the softmax function that normalizes the scores to class probabilities. During training we minimize the cross-entropy loss between true labels and predictions $\mathcal{L}_{\textnormal{CE}}\left(\mathcal{D}\right)=-\Sigma_{i=1}^{N}\mathbf{y}_i \cdot \log \mathbf{\tilde y}_i$, where $\mathbf{y}_i$ is the one-hot representation of class label $y_i \in \mathcal{C}$. \minisection{Continual learning.} We consider the continual learning setting where $T$ classification tasks are learned independently and in sequence from the corresponding datasets $\mathcal{D}_1,\ldots,\mathcal{D}_t,\ldots,\mathcal{D}_T$. The resulting model $M_t$ after learning task $t$ has feature extractor $F_t$ and classifier $H_t$ . We assume that the classes in each task are disjoint, i.e. $\mathcal{C}_t \bigcap \mathcal{C}_{t'}=\emptyset$ for all $t'\neq t$. Ideally, after learning task $t$, the model can perform inference on all tasks $t'\leq t$ (i.e. it remembers current and previous tasks). We consider class-incremental learning in this work, where task-ID is unknown and it requires predictions over all the classes learned so far. \subsection{Forgetting analysis of various methods} \minisection{Fine-tuning.} In Figure~\ref{fig:feature_correlation_analysis} (far left) we illustrate the effect of continual learning (via simply fine-tuning the network on new tasks) on features extracted at different layers of the network. Forgetting is measured using Canonical Correlation Analysis (CCA) similarity\footnote{\label{foot:cca}CCA similarity computes the similarity between distributed representations even when they are not aligned. This is important, since learning new tasks may change how different patterns are distributed in the representation. We use SVCCA~\cite{raghu2017svcca} which first removes noise using singular value decomposition (SVD).} between the features extracted for task $t'\leq t$ by model $M_t$ and the optimal model $M_{t'}$ (i.e. trained at time $t'$ with $\mathcal{D}_{t'}$). Earlier features remain fairly correlated, while the correlation decreases progressively with increasing layer depth. This suggests that forgetting in higher-level features is more pronounced, since they become progressively more task-specific, while lower features are more generic. \minisection{Learning without forgetting.} A popular method to prevent forgetting is \textit{Learning without Forgetting} (LwF)~\cite{li2018learning}, which keeps a copy of the model $M_{t-1}$ before learning the new task and distills its predicted probabilities into the new model $M_{t}$ (which may otherwise suffer interference from the current task $t$). In particular, LwF uses a modified cross-entropy loss over each head of previous tasks given by $ \mathcal{L}_{\textnormal{LwF}}\left(\mathcal{X}_t \right )=-\mathbb{E}_{\mathbf{x}\sim \mathcal{X}_t}\Sigma_{j=1}^{t-1}\tilde{\mathbf{y}}^{t-1,j} \cdot \log \tilde{\mathbf{y}}^{t,j} $. Note that the probabilities $\mathbf{\tilde y}^{t-1,j}$ and $\mathbf{\tilde y}^{t,j}$ are always estimated with current input samples $\mathbf{x}\in\mathcal{X}_t$, since data from previous tasks is not available. Since tasks are different, there is a distribution shift in the visual domain (i.e. $\mathbf{\tilde y}^{t-1,j}$ if extracted from $\mathbf{x}\in \mathcal{X}_{t-1}$ instead of $\mathbf{x}\in \mathcal{X}_t$), which can reduce the effectiveness of distillation when the domain shift from $\mathcal{X}_{t-1}$ to $\mathcal{X}_t$ is large. Figure~\ref{fig:feature_correlation_analysis} shows how LwF helps to increase the CCA similarity for previous tasks at the classifier, effectively alleviating forgetting and maintaining higher accuracy for previous tasks than fine tuning. However, the correlation at middle and lower-level layers in the feature extractor remains similar or lower to the case of fine tuning. This may be caused by the fact that the distillation constraint on the probabilities is too loose to enforce correlation in intermediate features. \frameworkfigure \minisection{Generative image replay.} The lack of training images for previous tasks in continual learning has been addressed with a generator of images from previous tasks and using them during the training of current and future tasks~\cite{nguyen2017variational,ostapenko2019learning,shin2017continual,wu2018memory}. We consider conditional GAN with Projection Discriminator ~\cite{miyato2018cgans}, which can control the class of generated images. At time $t$, the image generator samples images $\hat{\mathbf{x}}=G_{t-1}\left(c,\mathbf{z}\right)$ where $c$ is the desired class and $\mathbf{z}$ is a random latent vector sampled from a simple distribution (typically a normalized Gaussian). These generated images are combined with current data in an augmented dataset $\mathcal{D}'_t=\{(\hat{\mathbf{x}}_i,{y}_i)\}_{i=1}^{N_R}\cup \mathcal{D}_t$, where $\hat{\mathbf{x}_i}=G_{t-1}({y}_i,\mathbf{z}_i)$ and $N_R$ is the number of replayed images for previous tasks (typically distributed uniformly across tasks and classes). Generative image replay, while appealing, has numerous limitations in practice. First, real images are high dimensional representations and the image distribution of a particular task lies in a narrow yet very complex manifold. This complexity requires deep generators with many parameters and are computationally expensive, difficult to train, and often highly dependent on initialization~\cite{lucic2017gans}. Training these models requires large amounts of images, which is rarely the case in continual learning. Even with enough training images, the quality of the generated images is often unsatisfactory as training data for the classifier, since they may not capture relevant discriminative features. Figure~\ref{fig:feature_correlation_analysis} shows the CCA similarity for class-conditional GAN. It shows a similar pattern to LwF and fine tuning with the similarity decreasing especially in intermediate layers. \section{Feature distillation and generative feature replay} \label{sec:distillation} In the previous analysis of forgetting in neural networks, we saw that generative image replay yields unsatisfactory results when applied to datasets that are difficult to generate (like CIFAR-100). We also observed that feature distillation prevents forgetting in the feature extractor. Therefore, to obtain the advantage of replay methods, which do not have the imbalance problem arising from multiple classification heads, we propose \emph{feature} replay as an alternative to image replay. We combine feature distillation and feature replay in a hybrid model that is effective and efficient. (see Figure~\ref{fig:motivation} right). Specifically, we use distillation at the output of the feature extractor in order to prevent forgetting in the feature extractor, and use feature replay of the same features to prevent forgetting in the classifier and to circumvent the classifier imbalance problem. Note that feature distillation has also been used in other applications~\cite{michieli2019incremental,tung2019similarity,yu2019learning}. Our framework consists of three modules: feature extractor, classifier, and feature generator. To prevent forgetting we also keep a copy of the feature extractor, classifier and feature generator from the previous set of tasks. Figure~\ref{fig:framework} illustrates continual learning in our framework. The classifier $H_t$ and feature extractor $F_t$ for task $t$ are implicitly initialized with $H_{t-1}$ and $F_{t-1}$ (which we duplicate and freeze) and trained using feature replay and feature distillation. When the feature extractor and classifier are trained, we then freeze them and then train the feature generator $G_t$. A detailed algorithm is given in Algorithm~\ref{table:algorithm}. \tablealgorithm \subsection{Feature generator} To prevent forgetting in the classifier we train a feature generator $G_t$ to model the conditional distribution of features $p_\mathbf{u}\left(\mathbf{u}\vert c\right)$ as $\hat{\mathbf{u}}=G_t\left(c, \mathbf{z}\right)$, and sample from it when learning future tasks. We consider two variants: \textit{Gaussian class prototypes}, \textit{conditional GAN with replay alignment}. \minisection{Gaussian class prototypes.} We represent each class $c$ of a task $t$ as a simple Gaussian distribution $G_t(c,\mathbf{z})=\mathcal{N}(\mathbf{u} ; \mathbf{\mu}_t^{(c)},\mathbf{\Sigma}_t^{(c)})$, where $\mathcal{N}(\cdot; \cdot, \cdot)$ is a Gaussian distribution whose parameters are estimated using $\left\{\mathbf{u}_i=F_t\left(\mathbf{x}_i\right), \forall\left(\mathbf{x}_i,y_i\right)\in \mathcal{D}_t, y_i=c\right\}$. This variant has the advantage of compactness and efficient sampling. \minisection{Conditional GAN with replay alignment.} To generate more complex distributions and share parameters across classes and tasks, we propose to generate the feature extractor distribution with GANs. We use the Wasserstein GAN and adapt it to feature generation and continual learning using the following losses (between learning tasks $t$ and $t+1$): \begin{eqnarray} \mathcal{L}_{D_t}^{\textnormal{WGAN}}\left(\mathcal{X}_t\right) &=& +\mathbb{E}_{\mathbf{z}\sim p_{z},c \in C_t }\left [ D_t\left(c,G_t\left (c, \mathbf{z} \right )\right) \right ] \\ \nonumber & & -\mathbb{E}_{\mathbf{u}\sim \mathcal{D}_t}\left [ D_t\left(c,F_t\left(\mathbf{x}\right)\right) \right ] \\ \mathcal{L}_{G_t}^{\textnormal{WGAN}}\left(\mathcal{X}_t\right) &=& -\mathbb{E}_{\mathbf{z}\sim p_{z},c\in C_t }\left[ D_t\left(c,G_t\left (c, \mathbf{z} \right )\right) \right]. \end{eqnarray} A replay alignment loss $\mathcal{L}_{G_t}^{\textnormal{RA}}$ is also added: \begin{equation} \mathcal{L}_{G_t}^{\textnormal{RA}} = \Sigma_{j=1}^{t-1}\Sigma_{c\in C_j }\mathbb{E}_{\mathbf{z}\sim p_\mathbf{z}}\left[\left\lVert G_t\left(c,\mathbf{z}\right) - G_{t-1}\left(c,\mathbf{z}\right)\right\rVert_2^2\right]. \end{equation} which can be seen as a type of distillation~\cite{wu2018memory}. This replay alignment loss encourages the current generator $G_t$ to replay exactly the same features as $G_{t-1}$ when conditioned on a given previous class $c$ and a given latent vector $\mathbf{z}$. We use a discriminator $D_t$ during the adversarial training, which alternates updates of $D_t$ and $G_t$ (i.e. $\min_{D_t} \mathcal{L}_{D_t}^{\textnormal{WGAN}}\left(\mathcal{X}_t\right)$ and $\min_{G_t} \mathcal{L}_{G_t}^{\textnormal{WGAN}}\left(\mathcal{X}_t\right)+\mathcal{L}_{G_t}^{\textnormal{RA}}$, respectively). \subsection{Feature extractor with feature distillation} We prevent forgetting in $F_t$ by distilling the features extracted by $F_{t-1}$ via the following L2 loss: \begin{eqnarray} \mathcal{L}_{F_t}^{\textnormal{FD}}\left(\mathcal{X}_t\right) = \mathbb{E}_{\mathbf{x}\sim \mathcal{X}_t}\left[\left\lVert F_t\left(\mathbf{x}\right) - F_{t-1}\left(\mathbf{x}\right)\right\rVert_2\right]. \end{eqnarray} Note that there are no separate losses for each head (like in~\cite{li2018learning}) because the feature $\mathbf{u}=F\left(\mathbf{x}\right)$ is shared among tasks. Also, the loss can be applied on any feature (e.g. tensors). Note in Fig.~\ref{fig:feature_correlation_analysis} (center) how the CCA similarity of our approach compared to LwF increases, which indicates that there is less forgetting. \subsection{Algorithm of class-incremental learning} We are interested in a single head architecture that provides well-calibrated, task-agnostic predictions, which naturally arises if all tasks are learned jointly when all data is available. In our case we extend the last linear layer $V_{t-1}$ to $V_t$ by increasing its size to accommodate the new classes $C_t$. The softmax is also extended to this new size. During training we combine the available real data for the current task (fed to $F_t$) with generated features for previous tasks $\{(\hat{\mathbf{u}}_i,{y}_i)\}_{i=1}^{N_R}$. Since we only train a linear layer with features, this process is efficient. Figure~\ref{fig:feature_correlation_analysis} (far right) shows that our method preserves similar representations for previous tasks at all layers, including the classifier. Our combination of distillation and replay maintains higher accuracy across all tasks, effectively addressing the problems of forgetting and task aggregation. \imagenetsubfigure \section{Experimental results} \label{sec:experiments} We report experiments evaluating the performance of our approach compared to baselines and the state-of-the-art. \minisection{Datasets.} We evaluate performance on ImageNet~\cite{imagenet_cvpr09} and CIFAR-100~\cite{krizhevsky2009learning}. ImageNet-Subset contains the first 100 classes in ImageNet in a fixed, random order. We resize ImageNet images to 256$\times$256, randomly sample 224$\times$224 crops during training, and use the center crop during testing. CIFAR-100 images are padded with 4 pixels, from which 32$\times$32 crops are randomly sampled. The original center crop is used for testing. Random horizontal flipping is used as data augmentation for both datasets. \minisection{Training.} We use Pytorch as our framework ~\cite{paszke2017automatic}. For CIFAR-100, we modify the ResNet-18 network to use 3$\times$3 kernels for the first convolutional layer and train the model from scratch\footnote{This network setting was also used for the computation of Figure~\ref{fig:feature_correlation_analysis}.}. We train each classification task for 201 epochs and GANs for 501 epochs. For ImageNet, we use ResNet-18 and also train the model from scratch. We train each classification task for 101 epochs and GANs for 201 epochs. The Adam optimizer is used in all experiments, and the learning rate for classification and GANs are 1e-3 and 1e-4, respectively. The classes for both datasets are arranged in a fixed random order as in~\cite{hou2019learning, rebuffi2017icarl}. The coefficient of distillation loss is set to 1. \minisection{Evaluation.} The first evaluation metric is the average overall accuracy as in~\cite{hou2019learning, rebuffi2017icarl}. It is computed as the average accuracy of all tasks up to the current task. The second evaluation metric is the average forgetting measure as in~\cite{chaudhry2018riemannian}. It defines forgetting for a specific task as the difference between the maximum accuracy achieved on that task throughout the learning process and the accuracy the model currently achieves for it. The average forgetting is computed by averaging the forgetting for all tasks up to the current one. More evaluation metrics can be found in ~\cite{diaz2018don, lesort2020continual} \subsection{Class-incremental learning experiments} We first compare our approach with other methods on ImageNet-Subset and CIFAR-100. We use half of the classes from each dataset as the first task and split the remaining classes in 5, 10 and 25 tasks with equally distributed classes (as also done in~\cite{hou2019learning}). In figures and tables ``Ours Gaussian'' indicates our method with Gaussian replay and ``Ours'' indicates our method with generative feature replay. We compare our approach with several methods: LwF~\cite{li2018learning}, EWC~\cite{kirkpatrick2017overcoming}, MAS~\cite{aljundi2018memory}, iCaRL~\cite{rebuffi2017icarl} and Rebalance~\cite{hou2019learning}. iCaRL-CNN uses a softmax classifier while iCaRL-NME uses the nearest mean classifier. The first three methods are trained without exemplars and iCaRL and Rebalance store 20 samples per class. For the first three methods, we train a multi-head network, where each task has a separate head since they will not work with single-head when there are no exemplars. We simply pick the maximum probability across all heads as the chosen output. \cifarfigure \memorytable \minisection{Comparative analysis on ImageNet-Subset.} We report the average accuracy and the average forgetting on ImageNet-Subset in Figure~\ref{fig:imagenet100_50}. It is clear that using exemplars for iCaRL and Rebalance is superior to most methods without exemplars, such as LwF, MAS and EWC. Our method with Gaussian replay performs similarly to iCaRL-NME and much better than iCaRL-NME in the 5 and 10 task setting. Surprisingly, it outperforms both iCaRL-CNN and iCaRL-NME by a large margin in the 25-task setting. By using GANs for replay, our method shows significant improvement compared to Gaussian replay and outperforms the state-of-the-art method Rebalance by a large margin. The gain increases with increasing number of tasks. It achieves the best results in all settings in terms of both average accuracy and forgetting. It is important to note that for our methods we do not need to store any exemplars from previous tasks and generated features are dynamically combined with current data. A comparison with other methods on ImageNet-1000 is in Appendix~\ref{image_full}. \minisection{Comparative analysis on CIFAR-100.} Results for CIFAR-100 are shown in Figure~\ref{fig:cifar100_50}. Our method with generative feature generation outperforms iCaRL, LwF, MAS and EWC by a large margin and achieves comparable results as Rebalance in the case of 5 and 10 tasks. We achieve slightly worse results in the 25-task setting compared to Rebalance, which might be because features from low resolution images are not as good as those learned from ImageNet. In contrast, for both iCaRL and Rebalance, 2000 exemplars in total must be stored. It is interesting that our method with Gaussian replay performs quite well compared to iCaRL, but slightly worse than Rebalance. \subsection{Comparison of storage requirements} In Table~\ref{tab:memory} we compare the memory usage of exemplar-based methods iCaRL~\cite{rebuffi2017icarl} and Rebalance~\cite{hou2019learning}, the generative image replay method MeRGAN~\cite{wu2018memory}, and our generative feature replay. Exemplar methods normally store 20 images per class (from ImageNet or CIFAR-100), and the memory needed thus increases dramatically from 6.2MB to 375MB for 100 classes. Our approach, however, requires only a constant memory of 4.5MB for the generator and discriminator. For 256$\times$256$\times$3 images, our model is equivalent to only 24 total exemplars. Note that it is hard for exemplar-based methods to learn with only 24 exemplars. For larger numbers of classes such as full ImageNet-1000, it takes 3.8GB to store 20 samples per class. MeRGAN requires 8.5MB of memory, which is almost double the memory usage of ours. However, MeRGAN has difficulty generating realistic images for both CIFAR-100 and ImageNet and therefore obtains inferior results. \subsection{Generation of features at different levels} For our ablation study we use CIFAR-100 with 4 tasks with an equal number of classes. In Table~\ref{tab:cifar-feat} we look for the best depth of features to apply replay and distillation. We found that replaying at shallower depth results in dramatically lower performance. This is probably caused by: (1) the complexity of generating convolutional and lower-level features compared to the generation of linear high-level features from Block 4 (Ours); and (2) the difficulty of keeping the head parameters unbiased towards the last trained task when moving replay down in the network. \ablationFeatureReplay \section{Conclusions} \label{sec:discussion} We proposed a novel continual learning method that combines generative feature replay and feature distillation. We showed that it is computationally efficient and scalable to large datasets. Our analysis via CCA shows how catastrophic forgetting manifests at different layers. The strength of our approach relies on the fact that the distribution of high-level features is significantly simpler than the distribution at the pixel level and therefore can be effectively modeled with simpler generators and trained on limited samples. We perform experiments on the ImageNet and CIFAR-100 datasets. We outperform other methods without exemplars by a large margin. Notably, we also outperform storage-intensive methods based on exemplars in several settings, while the overhead of our feature generator is small compared to the storage requirements for exemplars. For future work, we are especially interested in extending the theory to feature replay for continual learning of embeddings~\cite{yu2020semantic}. \minisection{Acknowledgement} We acknowledge the support from Huawei Kirin Solution, the Industrial Doctorate Grant 2016 DI 039 of the Generalitat de Catalunya, the EU Project CybSpeed MSCA-RISE-2017-777720, EU's Horizon 2020 programme under the Marie Sklodowska-Curie grant agreement No.6655919 and the Spanish project RTI2018-102285-A-I00. {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2020-04-21T02:25:03', 'yymm': '2004', 'arxiv_id': '2004.09199', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09199'}
arxiv
\section{Algorithm} Given a 2D caricature, we aim to automatically reconstruct its 3D face shape and obtain landmarks around its eyes, nose, mouse, and so on, as shown in Fig.~\ref{fig:showpic}. To this end, we construct a 2D caricature dataset, including manually labeled figures and machine-generated figures. We then build a 3D caricature dataset via an optimization method proposed in~\cite{wu2018alive} with around 8K 2D caricatures and their corresponding labeled landmarks. In this way, we obtain its 3D shape and parameters of weak perspective projection for each caricature. Lastly, we propose a CNN-based algorithm to directly recover the 3D face shape parameters and orientation parameters from the input 2D caricature image. Notably, we use the principal component analysis (PCA) basis to initialize the weight of the last fully connected layer. The algorithm pipeline is shown in Fig.~\ref{fig:pipeline}. In the following, we give the algorithm details for each component. \subsection{Dataset Construction and Augmentation} Currently, there exist some public available caricature datasets. For the study of caricature recognition, Huo \emph{et al.}~\cite{huo2017webcaricature} constructed a WebCaricature database including 6042 caricatures and 5974 photographs from 252 persons with 17 labeled facial landmarks for each image. Mishra \emph{et al.}~\cite{mishra2016iiit} built IIIT-CFW database for face classification and caricature generation, which contains 8928 cartoon faces of 100 public figures with annotation of various attributes, e.g., face bounding box, age group, facial expression, and so on. However, these datasets can not be directly used for our task as they do not supply enough labeled landmarks for 3D reconstruction. \begin{figure}[!b] \begin{center} \includegraphics[width=1.0\linewidth]{selected.pdf} \end{center} \caption{The first row shows some examples of our collected images with manually labeled landmarks, while the second row shows some examples of our augmented images and corresponding landmarks generated by~\cite{cao2018carigans}.} \label{fig:selected} \end{figure} By searching and selecting nearly 6K various caricatures from different artists on the Internet, we construct a caricature dataset with $68$ labeled landmarks. The landmark positions are initialized via the Dlib library~\cite{king2009dlib}, and then manually refined. To further increase the diversity of our dataset, we design a data augmentation method based on CariGANs~\cite{cao2018carigans}. It is able to translate normal facial images to caricatures with two generative adversarial networks (GANs), namely CariGeoGAN and CariStyGAN. CariGeoGAN learns a mapping to exaggerate the shape by adjusting facial landmarks, while CariStyGAN learns another mapping to translate the appearance from normal facial image style to caricature style. With trained CariGANs, we can generate a caricature and its corresponding 68 landmarks from a given normal facial image. In this way, we generate around 2K caricatures and add them to our dataset. Some examples of our collected data and augmented data are shown in Fig.~\ref{fig:selected}. \subsection{3D Caricature Representation and Recovery} \label{sec:construction} Parametric models such as 3DMM~\cite{blanz1999morphable} are popularly used in 3D face reconstruction to represent complex face shapes with a low dimensional parametric vector. This kind of representation makes optimization and learning based 3D face reconstruction easier. However, linear parametric models are only good for \emph{interpolation} in the shape space of normal 3D faces but do not work well for \emph{extrapolation} in 3D caricature shape space. Therefore, to reconstruct 3D models from 2D caricatures, we adopt the deformation representation to recover 3D caricature shape, which is used in~\cite{wu2018alive}. Compared with 3D Euclidean coordinates, this deformation representation is suitable to represent local and large deformation in a natural way, which makes the reconstructed exaggerated meshes more natural and match the input 2D caricature quite well. To make our paper self-contained, we first introduce the deformation representation between two models with consistent connectivity and then give the algorithm details on how to recover the 3D caricature shape from the 2D landmarks. Firstly, we treat one model as a template and another as a target deformed model. We denote the position of the $i^{\rm th}$ vertex $v_i$ on the template as $\mathbf{p}_i$ and the $i^{\rm th}$ vertex $v_i$ on the target as $\mathbf{p}_i'$. We can define the deformation gradient in the one-ring neighborhood of $v_i$ from the template to the target as an affine transformation matrix $\mathbf{T}_i$ by minimizing \begin{equation} \mathop{\arg\min_{\mathbf{T}_{i}}}\sum_{j\in{\mathcal{N}_i}} c_{ij}\|{(\mathbf{p}_{i}^{\prime}-\mathbf{p}_{j}^{\prime})-\mathbf{T}_{i}(\mathbf{p}_{i}-\mathbf{p}_{j})}\|_{2}^2, \end{equation} where $\mathcal{N}_i$ is the neighborhood index set of $v_i$, and $c_{ij}$ is the cotangent weight~\cite{botsch2007linear} to avoid discretization bias in deformation. With polar decomposition, the deformation matrix $\mathbf{T}_i$ can be decomposed into a rigid component represented by a rotation matrix $\mathbf{R}_i$ and a non-rigid component represented by a real symmetry matrix $\mathbf{S}_i$, as $\mathbf{T}_i$ = $\mathbf{R}_i$$\mathbf{S}_i$. To obtain efficient linear combination, we use the axis-angle representation~\cite{diebel2006representing} to replace the rotation matrix $\mathbf{R}_i$. Following Rodrigues' rotation formula, for the $i^{\rm th}$ vertex $v_i$, we denote the cross-product matrix and rotation angle by $\mathbf{K}_i$, $\theta_i$. We can convert $\mathbf{R}_i$ to a matrix logarithm notation: \begin{equation} \log \mathbf{R}_i = \theta_i\mathbf{K}_i, \end{equation} \begin{equation} \mathbf{K}_i ={ \left[ \begin{array}{ccc} 0 & -k_{i,z} & k_{i,y} \\ k_{i,z} & 0 & -k_{i,x} \\ -k_{i,y} & k_{i,x} & 0 \\ \end{array} \right ]}, \end{equation} where $\mathbf{k}_i\in {\mathbb{R}^3}$ and $\|\mathbf{k}_i\|_2 =1$. This representation has many advantages, especially for our method, it can be used for linear combination~\cite{alexa2002linear} of two rotation matrices $\mathbf{R}_i^{\rm 0}$ and $\mathbf{R}_i^{\rm 1}$ by $\exp(\log \mathbf{R}_i^{\rm 0}+\log \mathbf{R}_j^{\rm 1})$. We choose a reference model and $n$ deformed models which have the same connectivities with the reference model. For the $i^{\rm th}$ vertex of each deformed model, we obtain its deformation representation ${\{\log \mathbf{R}_i^{\rm k}, \mathbf{S}_i^{\rm k}\}}(k=1,2,\ldots, n)$. Following~\cite{gao2019sparse}, the logarithm rotation matrix can be represented by a vector $\mathbf{r}_{i}\in {\mathbb{R}^3}$ and the scalar matrix can be represented by a vector $\mathbf{s}_{i}\in {\mathbb{R}^6}$. To handle the ambiguity of axis-angle representation, Gao \emph{et al.}~\cite{gao2019sparse} proposed an integer programming approach to make all $\mathbf{r}_{i}$ as consistent as possible globally. Then, corresponding to an essential deformation representation, a target mesh can be approximately reconstructed by a linear combination of several known deformation gradients. With the method of~\cite{wu2018alive}, we obtain the latent deformation representation for vertices' coordinates and the weak perspective parameters for each caricature. Based on a reference model and $n$ deformed models, we propose a linear combination of deformation gradients for the $i^{\rm th}$ vertex as \begin{equation} \mathbf{T}_i(\mathbf{w}) = \exp(\sum_{k=1}^n{w_{R,k}}\log \mathbf{R}_i^{\rm k}){(\mathbf{I} + \sum_{k=1}^nw_{S,k} (\mathbf{S}_i^{\rm k}-\mathbf{I}))}, \label{eq:DRCombination} \end{equation} where $\mathbf{w} = (\mathbf{w}_R, \mathbf{w}_S)$ is the combination weight vector, consisting of weights of rotation $\mathbf{w}_R = \{w_{R,k}|k=1,\cdots,n\}$ and weights of scaling/shear $\mathbf{w}_S = \{w_{S,k}|l=1,\cdots,n\}$. \begin{figure}[!h] \begin{center} \includegraphics[width=1.0\linewidth]{laplacian.pdf} \end{center} \caption{Left to right: input caricature, 3D mesh reconstructed by our optimization model in Eq.~\eqref{eq:optimization_caricature}, 3D mesh reconstructed by the optimization model in~\cite{wu2018alive}. We can see that the result by~\cite{wu2018alive} contains spikes around landmarks (highlighted with ellipses).} \label{fig:laplacian} \end{figure} Given a caricature with labeled landmarks, we reconstruct the corresponding 3D caricature mesh by minimizing the following energy: \begin{equation} \begin{aligned} \min_{\mathbf{P',w,\Pi,R,t}}&\sum_{v_i\in{\mathcal{V}}}\sum_{j\in{\mathcal{N}_i}} c_{ij}\|{({\mathbf{p}_i^{\prime}}-{\mathbf{p}_j^{\prime}})-\mathbf{T}_{i}(\mathbf{w})(\mathbf{p}_i-\mathbf{p}_j)}\|^2\\ +\alpha_1&\sum_{v_i \in \mathcal{L}}\|\mathbf{\Pi} \mathbf{R} \mathbf{p}_i' +\mathbf{t}-\mathbf{q}_i\|^2\\ +\alpha_2&\sum_{v_i\in{\mathcal{L}}} \|{\sum_{j\in{\mathcal{N}_i}}c_{ij}({\mathbf{p}_i^{\prime}}-{\mathbf{p}_j^{\prime}})-\sum_{j\in{\mathcal{N}_i}}c_{ij}(\mathbf{p}_i-\mathbf{p}_j)}\|^2, \end{aligned} \label{eq:optimization_caricature} \end{equation} \begin{comment} \begin{equation} \begin{aligned} \min_{\mathbf{P',w,\Pi,R,t}}&\sum_{v_i\in{\mathcal{V}}}\sum_{j\in{\mathcal{N}_i}} c_{ij}\|{({\mathbf{p}_i^{\prime}}-{\mathbf{p}_j^{\prime}})-\mathbf{T}_{i}(\mathbf{w})(\mathbf{p}_i-\mathbf{p}_j)}\|^2\\ &+\lambda \sum_{v_i \in \mathcal{L}}\|\mathbf{\Pi} \mathbf{R} \mathbf{p}_i' +\mathbf{t}-\mathbf{q}_i\|^2, \end{aligned} \label{eq:optimization_caricature} \end{equation} \end{comment} where $\mathcal{L}$ and $\mathcal{Q}=\{\mathbf{q}_i,v_i\in\mathcal{L}\}$ are the set of 3D landmarks and 2D landmarks separately, $\mathbf{\Pi}$ is the scaled projection matrix, $\mathbf{R}$ is the rotation matrix constructed from Euler angles \emph{pitch}, \emph{yaw}, \emph{roll} and $\mathbf{t} = [t_x, t_y]^\mathrm{T}$ is the translation vector. The third term of Eq.~\eqref{eq:optimization_caricature} is the Laplacian smoothing term~\cite{sorkine2004laplacian}, and $c_{ij}$ is the cotangent Laplacian weight of the neutral face mesh. The hyperparameters $\lambda_1$ and $\lambda_2$ are set as $\alpha_1 = 0.01$, $\alpha_2 = 1$. Note that, the optimization formulation in~\cite{wu2018alive} does not include the third term, and it will cause spikes around the landmarks, as shown in Fig.~\ref{fig:laplacian}. An alternative optimization strategy is applied to solve the problem in Eq.~\eqref{eq:optimization_caricature} by fixing one set of variables while optimizing another set of variables, and alternating this process. After optimization, we can obtain the 3D coordinates $\mathbf{P}'$ of target caricature mesh, weak perspective parameters, face orientation, and the combination parameters $\mathbf{w} = (\mathbf{w}_R, \mathbf{w}_S)$. As the deformation representation for each vertex contains 9 variables, the deformation representation of the 3D caricature model with $n_v$ vertices can be represented as a $9n_v$ vector. Therefore, given a 2D caricature, training a CNN model that ends with several fully connected layers to directly regress its corresponding $9n_v$ deformation representation vector is quite natural. \begin{figure}[!h] \begin{center} \includegraphics[width=1.0\linewidth]{weight.pdf} \end{center} \caption{First row: Input 2D caricatures. Second row: 3D models generated by~\cite{wu2018alive}. Third row: 3D models recovered by the linear combination coefficients $\mathbf{w} = (\mathbf{w}_R, \mathbf{w}_S)$ of latent deformation representation as the result of~\cite{wu2018alive}. Fourth row: 3D models generated by our algorithm.} \label{fig:weight} \end{figure} \subsection{Landmark Detection and Reconstruction} Although we adopt the deformation representation to recover the 3D caricature shape from the 2D image, the shape recovered only by $\mathbf{T}_i(\mathbf{w})$ can not represent the exaggerated part. Specifically, we can obtain the optimal linear combination coefficients $\mathbf{w} = (\mathbf{w}_R, \mathbf{w}_S)$ of latent deformation representation by solving Eq.~\eqref{eq:optimization_caricature} and recover a 3D shape from $\mathbf{w}$ via Eq.~\eqref{eq:DRCombination}. However, this shape can not match the ground truth caricature shapes, as shown in the third row of Fig.~\ref{fig:weight}. This is because their methods are based on FaceWareHouse, a real face database. The reason why their final face shapes in~\cite{wu2018alive} match the caricature shapes quite well is that the shape is further deformed based on the 2D landmarks, as the second term in Eq.~\eqref{eq:optimization_caricature}. Therefore, directly regressing the $\mathbf{w}$ parameters can not satisfy our needs. To solve this problem, we propose a CNN-based approach to directly regress the intrinsic deformation representation and the weak perspective projection parameters with a single 2D caricature image. As shown in Fig.~\ref{fig:pipeline}, we utilize ResNet-34 backbone~\cite{he2016deep} to encode the input 2D caricature into a latent vector $\bm{\chi}\in \mathbb{R}^{216}$. The latent vector contains two parts, where $\bm{\chi}_{s}\in \mathbb{R}^{210}$ represents the 3D shape and $\bm{\chi}_{p}\in \mathbb{R}^{6}$ represents the parameters of weak perspective projection. We propose a decoder composed of $3$ fully connected layers to convert $\bm{\chi}_{s}$ to the estimated latent deformation representation $\{[\hat{\mathbf{r}}_{i},\hat{\mathbf{s}}_{i}], i = 1,\ldots,n_{v}\}$, where $n_{v}$ is the number of mesh vertices. The deformation gradients $\{(\log\hat{\mathbf{R}}_{i},\hat{\mathbf{S}}_{i}),i=1,\ldots,n_{v}\}$ and $\hat{\mathbf{T}}_{i}$ then can be recovered accordingly. To help the model training, we initialize the weights of the last fully connected (FC) layer by a PCA basis extracted from the training dataset. The first 500 principal components are used to initialize the weights of the last FC layer.\\ \noindent{\bf Loss for Caricature Shape.} As before, the estimated vertex coordinate $\{\hat{\mathbf{p}}_i'\}$ of target mesh can be obtained by solving \begin{equation} \mathop{\arg\min_{\{\hat{\mathbf{p}}_{i}^{\prime}\}}}\sum_{j\in{\mathcal{N}_i}} c_{ij}\|{(\hat{\mathbf{p}}_{i}^{\prime}-\hat{\mathbf{p}}_{j}^{\prime})-\hat{\mathbf{T}}_{i}(\mathbf{p}_{i}-\mathbf{p}_{j})}\|_{2}^2, \end{equation} which is equivalent to solve the following linear system: \begin{equation} 2\sum_{j\in{\mathcal{N}_i}}c_{ij}(\hat{\mathbf{p}}_{i}^{\prime} - \hat{\mathbf{p}}_{j}^{\prime}) = \sum_{j\in{\mathcal{N}_i}}c_{ij}(\hat{\mathbf{T}}_{i} + \hat{\mathbf{T}}_{j})(\mathbf{p}_{i}-\mathbf{p}_{j}). \end{equation} As the deformation representation is translation independent, and thus we need to specify the position of mesh center or exactly one vertex. As the ground truth 3D caricature meshes are under the same specification, we construct a loss term to constrain the coordinate difference between the reconstructed mesh and the ground truth mesh as \begin{equation} \mathbf{E}_{ver}(\bm{\chi}_{s}) = \sum_{v_i\in\mathcal{V}} \|\hat{\mathbf{p}}_{i}^{\prime} - \mathbf{p}_{i}^{\prime}\|_{2}^2, \end{equation} where $\mathbf{p}_{i}^{\prime}$ presents the ground truth coordinate of the $i^{\rm th}$ vertex of 3D mesh, and $\mathcal{V}$ represents the vertex set.\\ \noindent{\bf Loss for Landmarks.} Reconstructing the 3D mesh from a 2D image is the inverse process of observing a 3D object by projecting it to 2D visual space. As before, we assume that the projection plane is the \emph{z}-plane and thus the scaled projection matrix can be written as $\mathbf{\Pi} = s{ \left[ \begin{array}{ccc} 1 & 0 & 0 \\ 0 & 1 & 0 \\ \end{array} \right ]},$ where $\mathbf{s}$ is the scale factor. To better recover the landmark positions, we construct a landmark loss term to measure the difference between the projected landmarks and the ground truth landmarks: \begin{equation} \mathbf{E}_{lan}(\bm{\chi}) = \sum_{v_i\in\mathcal{L'}}\|\hat{\mathbf{\Pi}}\hat{\mathbf{R}}\hat{\mathbf{p}}_{i}^{\prime}+\hat{\mathbf{t}}-\mathbf{q}_i'\|_{2}^2, \end{equation} where $\mathcal{L'}$ and $\mathcal{Q'} = \{\mathbf{q}_i',v_i\in\mathcal{L'}\}$ are the set of 3D landmarks and 2D landmarks separately, $\hat{\mathbf{\Pi}}$ is the estimated scaled projection matrix, $\hat{\mathbf{R}}$ is the estimated rotation matrix, and $\hat{\mathbf{t}}$ is the estimated translation vector. As our 3D caricature meshes have the same connectivities, the indices of 3D landmarks are the same for different caricature shapes. \begin{figure}[!h] \begin{center} \includegraphics[width=1\linewidth]{silhouette.pdf} \end{center} \caption{For non-frontal face caricatures, we need to update the indices of silhouette landmarks on the 3D face shape to better match the corresponding 2D landmarks (shown in cyan in upper-left). The default 3D silhouette landmarks are shown in green in the lower-left. We construct an optional landmark set from each horizontal line (shown in yellow in lower-middle) that has a vertex lying on the silhouette and select among them a set of the updated silhouette landmarks according to the estimated rotation matrix $\hat{\mathbf{R}}$ in each training time. The vertices of the silhouette are updated in the end as shown in red on the upper right and lower-right.} \label{fig:silhouette} \end{figure} Compared with normal face, the positions of caricature silhouette landmarks have large variance, and thus it is quite challenging to detect their positions accurately. Moreover, the 3D vertices corresponding with these silhouette landmarks are labeled on the mean neutral face with a frontal view, which causes the problem that the correspondences between 3D vertices and 2D landmarks are not correct for non-frontal faces as shown in Fig.~\ref{fig:silhouette}. To solve this problem, we update the indices of 3D silhouette landmarks each training time according to the estimated rotation matrix and vertices' coordinates. In each time, we select some vertices from each horizontal line that has a vertex lying on the silhouette and project them onto the image plane according to the estimated rotation matrix $\hat{\mathbf{R}}$. Then for each 2D silhouette landmark, we set the vertex whose projection is closet to it (see Fig.~\ref{fig:silhouette}) as its current corresponding 3D silhouette landmark.\\ \noindent{\bf Loss for Projection Parameters.} To recover the 2D landmarks from the 3D shape, we also need to regress the parameters of weak perspective projection for each caricature. We find that the MSE between predicted parameters and ground truth parameters can not generate a good result. A better way is to constrain the projection difference between the ground truth 3D landmark with ground truth projection parameters ($\mathbf{s,R,t}$) and estimated parameters ($\mathbf{\hat{s},\hat{R},\hat{t}}$): \begin{equation} \mathbf{E}_{srt} (\bm{\chi}_p) = \sum_{v_i\in\mathcal{L'}}\|(\hat{\mathbf{\Pi}}\hat{\mathbf{R}}\mathbf{p}_{i}^{\prime} + \hat{\mathbf{t}}) - (\mathbf{\Pi}\mathbf{R}\mathbf{p}_{i}^{\prime} + \mathbf{t})\|_{2}^2, \end{equation} where $\mathbf{p}_{i}^{\prime}$ represents the ground truth 3D landmark position. The total loss function is given in the following form: \begin{equation} \begin{aligned} \mathbf{E}= \lambda_1\mathbf{E}_{ver} + &\lambda_2\mathbf{E}_{lan} + \lambda_3\mathbf{E}_{srt}, \end{aligned} \end{equation} where $\lambda_1,\lambda_2,\lambda_3$ are hyperparameters and their setting will be discussed in the experiment section. \section{Conclusion} We have presented an effective and efficient algorithm for automatic landmark detection and 3D reconstruction for 2D caricature images. This challenging problem is well solved by separately regressing the 3D face shape and face pose, and then 2D landmarks and 3D shape can both be obtained. To represent the non-regular 3D caricature face, we construct a 3D caricature shape dataset to learn the latent representation. Extensive experimental results show that the detected 2D landmarks and reconstructed 3D face shape fit the caricature quite well, which outperforms the state-of-the-art methods in both computation speed and accuracy. \section{Experiments} In this section, we conduct qualitative and quantitative evaluation of our proposed landmark detection and 3D reconstruction method for caricature and compare it with several baseline methods.\\ \noindent{\bf Implementation Details} We train our model via the PyTorch~\cite{paszke2017automatic} framework. CNN takes the input of a color caricature image with size $224\times224\times3$. We use Adam solver~\cite{kingma:adam} with the mini-batch size of 32 and train the model with 2K iterations. The base learning rate is set to 0.0001. We set $\lambda_1 = 1, \lambda_2 = 0.00001, \lambda_3 = 0.00001$ during the first 1K iterations, and set $\lambda_1 = 1, \lambda_2 = 0.001, \lambda_3 = 0.00001$ during the last 1K iterations. The reason why the magnitudes of parameters are quite different is that the magnitude of vertices' coordinates has a big difference with that of 2D pixels. All the tests, including our method, baseline methods and comparison methods, were conducted on a desktop PC with a hexa-core Intel CPU i7 at 3.40 GHz, 16GB of RAM and NVIDIA TITAN Xp GPU. As for the running time for each caricature, our method takes about 10ms to obtain both 3D mesh and 68 2D landmarks. The number of vertices of our reconstructed mesh is 6144. \subsection{Landmark Detection Comparison} \begin{figure*}[!h] \begin{center} \includegraphics[width=1.0\linewidth]{compare_land.pdf} \end{center} \caption{We provide visual landmark detection results on the test dataset using DAN~\cite{kowalski2017deep}, ERT~\cite{kazemi2014one}, VCNN~\cite{wu2017facial} and some baselines including Landmark PCA (L-PCA), Vertex PCA (V-PCA), and DR-PCA.} \label{fig:compare_land} \end{figure*} As far as we know, there is no existing method for landmark detection for general caricatures. We compare our method with some baseline methods. The first type is the face alignment methods, which are designed for normal human faces, and we select three typical methods, including DAN~\cite{kowalski2017deep}, ERT~\cite{kazemi2014one}, and vanilla CNN (VCNN) designed by~\cite{wu2017facial}. As their released trained models are trained with normal facial images, we retrain their models based on the author's training code. For a fair comparison, their methods are trained and tested with the same training and testing dataset as our method. We randomly split our dataset into 80\% for training and 20\% for testing. \begin{figure}[!h] \begin{center} \includegraphics[width=1\linewidth]{CED.pdf} \end{center} \caption{Comparisons of cumulative errors distribution (CED) curves on the test set.} \label{fig:CED} \end{figure} \noindent\textbf{DAN:} Deep Alignment Network (DAN)~\cite{kowalski2017deep} is a robust face alignment method based on deep neural network architecture. Its algorithm pipeline includes multiple stages, where each stage improves the locations of the facial landmarks estimated by the previous stage. \noindent\textbf{ERT:} In~\cite{kazemi2014one}, an ensemble of regression trees (ERT) has been used to directly estimate the facial landmark positions from a sparse subset of pixel intensities. This method achieves super-realtime performance with high-quality predictions. It has been integrated into Dlib library~\cite{king2009dlib}. \noindent\textbf{VCNN:} Vanilla CNN is proposed in~\cite{wu2017facial}, which introduces hierarchical and discriminative processing to existing CNN design for facial landmark regression. \noindent\textbf{L-PCA:} Except for the above three methods, we also implement some baseline methods. Inspired by~\cite{cao2018carigans}, we extract the PCA basis of 2D caricature landmarks from the labeled landmark dataset. In this way, the landmarks of caricature image can be represented by the coefficient of PCA basis. We use the same ResNet framework in our method to directly regress the coefficient. \noindent\textbf{V-PCA:} We extract the PCA basis of 3D caricature shape set represented by the Euclidean coordinates. The network structure is the same with our algorithm pipeline in Fig.~\ref{fig:pipeline}, and regresses the PCA coefficient and orientation. \noindent\textbf{DR-PCA:} We extract the PCA basis of 3D caricature shape set represented by the deformation representation. The pipeline is the same as ours by replacing the decoder part with the extracted PCA basis. \begin{table} \centering \caption{Statistics of landmark detection errors and computation time (ms/image) on the test set. Values of mean error with normalization are shown as the percentage of the normalization metric.} \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{tabular}{|c|c|c|c|c|c|c|} \hline &\tabincell{c}{mean\\error}&\tabincell{c}{inter\\-pupil}&\tabincell{c}{inter\\-ocular}&diagonal&\tabincell{c}{time\\(ms)} \\ \hline DAN&$5.78$&$9.93$&$6.80$&$2.59$&$25.9$ \\ \hline ERT&$8.24$&$14.52$&$9.95$&$3.71$&$2.7$ \\ \hline VCNN&$14.04$&$24.33$&$16.67$&$6.39$&$1.6$ \\ \hline L-PCA&$5.87$&$10.08$&$6.91$&$2.64$&$5.0$ \\ \hline V-PCA&$6.20$&$10.68$&$7.32$&$2.79$&$6.7$ \\ \hline DR-PCA&$5.75$&$9.89$&$6.77$&$2.58$&$10.0$\\ \hline Ours&$5.06$&$8.60$&$5.89$&$2.27$&$10.5$\\ \hline \end{tabular} \label{table:fitting} \end{table} We compare our method with state-of-the-art methods and baselines. Fig.~\ref{fig:compare_land} shows some visual results of landmark detection. It can be observed that the detected landmarks of ERT~\cite{kazemi2014one} and VCNN~\cite{wu2017facial} can not match the face shape. The method of DAN~\cite{kowalski2017deep} performs quite well for the facial feature parts, including eyes, nose and mouth. However, its silhouette landmarks may deviate from the accurate positions. V-PCA and L-PCA are also not good for the landmarks on the silhouette. Though DR-PCA representation shows nice performance, it still can not match the facial feature parts precisely. In contrast, the detection results by our method are quite close to the ground truth landmarks, even for the silhouette landmarks. We also quantitatively compare our method with these methods on several frequently used landmark error metrics and average computation time. We show the statistics in Tab.~\ref{table:fitting} and the cumulative errors distribution (CED) curves of these methods on the mean error in Fig.~\ref{fig:CED}. We can see that the mean error, mean error normalized separately by inter-pupil distance, inter-ocular distance and bounding box diagonal of our methods are all smaller than those of other methods. \begin{comment} In addition, we also test our model on some normal facial images with exaggerated expressions. As shown in Fig.~\ref{fig:compare_normal}, our method (trained with caricatures) performs even better than a robust face alignment method~\cite{kowalski2017deep} and a state-of-the-art face alignment methods~\cite{wang2019adaptive} on non-caricature images with exaggerated expressions. It shows our method can help some related researches, such as emotion analysis. \end{comment} The reason why our method performs better includes the following aspects. First, rather than directly regressing the 2D landmarks, we regress the 3D shape and orientation. In this way, a hard problem is decomposed into two easier problems. Second, to better represent the 3D caricature shape, we learn a nonlinear parametric model, which is more suitable to represent the 3D caricature shape than 3D morphable model~\cite{blanz1999morphable} and FaceWareHouse~\cite{cao2013facewarehouse}. \begin{comment} \begin{figure}[!h] \begin{center} \includegraphics[width=1.0\linewidth]{normal_face.pdf} \end{center} \caption{Results of landmark detection on non-caricature images with exaggerated expressions. First row: results by DAN~\cite{kowalski2017deep} (the pre-trained model by authors). Second row: results by AWing~\cite{wang2019adaptive} (the pre-trained model by authors). Third row: results by our method (trained with 6,240 caricatures).} \label{fig:compare_normal} \end{figure} \end{comment} \begin{figure}[!h] \begin{center} \includegraphics[width=1.0\linewidth]{texture.pdf} \end{center} \caption{Left to right: input caricature, predicted mesh overlaying on the image, predicted mesh in two different views, predicted mesh with texture.} \label{fig:texture} \end{figure} \subsection{3D Reconstruction Comparison} Reconstructing 3D caricature shape from caricature image is also a challenging problem, and the only related work is~\cite{wu2018alive}. We adopt the method of~\cite{wu2018alive} to construct the 3D caricature dataset. As shown in their paper, parametric models like 3DMM~\cite{paysan20093d,zhu2015high} and FaceWareHouse~\cite{cao2013facewarehouse} cannot reconstruct exaggerated meshes well due to their limited extrapolation ability. The algorithm of~\cite{wu2018alive} is given in Sec.~\ref{sec:construction}, and we compare our 3D reconstruction results with this method. In Fig.~\ref{fig:texture}, we show two reconstruction examples from the test set. The reconstructed mesh is overplayed on the image, and we can observe that the shape is recovered quite well. The recovered mesh from two different views and with texture are also shown to demonstrate the effectiveness of our method. Furthermore, from Fig.~\ref{fig:compare_alive}, we can find that the reconstructed 3D meshes by our method are quite close to the results by~\cite{wu2018alive}. As their results supervise the ground truth meshes during training, it demonstrates the nice performance of our trained model to fit the ground truth 3D shapes. One advantage of our method over~\cite{wu2018alive} is the computation time. It takes around 10ms to produce the result with our method, while 12.5s for their method. Moreover, our reconstruction method does not need to label the landmarks manually. From the above quantitative and qualitative experiments, we can see that our proposed method performs quite well on landmark detection and reconstruction for caricatures and non-caricature faces with exaggerated expressions. In Fig.~\ref{fig:compare1_all} and Fig.~\ref{fig:compare2_all}, more experimental results and comparisons with the-state-of-the-art landmark detection methods~\cite{kowalski2017deep,kazemi2014one,wu2017facial} and 3D caricature reconstruction method~\cite{wu2018alive} on $20$ test caricatures are given. These results further validate the superior effect of our proposed method on the tasks of landmark detection and 3D reconstruction on caricature. \begin{figure}[!h] \begin{center} \includegraphics[width=1.0\linewidth]{compare_alive.pdf} \end{center} \caption{Reconstruction results by our method and~\cite{wu2018alive}. From the first column to the last column are input images, reconstruction results by~\cite{wu2018alive}, reconstruction results by our method, and the projected 2D landmarks by our method respectively.} \label{fig:compare_alive} \end{figure} \begin{figure*} \begin{center} \includegraphics[width=0.9\linewidth]{compare1_all.pdf} \end{center} \caption{Landmark detection comparisons with state-of-art methods DAN~\cite{kowalski2017deep}, ERT~\cite{kazemi2014one}, VCNN~\cite{wu2017facial} and reconstruction comparisons with Alive~\cite{wu2018alive} which needs labeled landmarks. It can be seen that our method can detect landmarks and reconstruct 3D face shapes quite well.} \label{fig:compare1_all} \end{figure*} \begin{figure*} \begin{center} \includegraphics[width=0.9\linewidth]{compare2_all.pdf} \end{center} \caption{Landmark detection comparisons with state-of-art methods DAN~\cite{kowalski2017deep}, ERT~\cite{kazemi2014one}, VCNN~\cite{wu2017facial} and reconstruction comparisons with Alive~\cite{wu2018alive} which needs labeled landmarks. It can be seen that our method can detect landmarks and reconstruct 3D face shapes quite well.} \label{fig:compare2_all} \end{figure*} \begin{comment} \begin{figure*} \begin{center} \includegraphics[width=1.0\linewidth]{show_models.pdf} \end{center} \caption{A gallery of 3D caricature models generated by our method directly from input images. The first row shows the input images, and the second and third rows show the reconstructed face shapes by our method under different views.} \label{fig:show_models} \end{figure*} \end{comment} \section{Introduction} As a vivid artistic form that represents human faces in abstract and exaggerated ways, caricature is mainly used to express satire and humor for political or social incidents. It also has many applications in our daily life, including advertisements, electronic games, and so on. Since Brennan developed the first caricature generator in 1985~\cite{brennan1985caricature}, the studies of caricatures have mainly focused on some specific tasks, such as caricature generation~\cite{liang2002example,shumsample,cao2018carigans,shi2019warpgan}, caricature recognition~\cite{klare2012towards,ouyang2014cross,abaci2015matching}, and caricature reconstruction~\cite{lewiner2011interactive,vieira2013three,han2017deepsketch2face,wu2018alive}. Most of these tasks need facial landmarks to help to preprocess the caricatures. As a fundamental process for various caricature processing tasks, automatic facial landmark detection can greatly improve the efficiency and accuracy of other caricature processing tasks. As there is no automatic landmark detection method for caricature, all the present related works rely on manually labeling landmarks, which is tedious and time-consuming. Meanwhile, the reconstructed 3D model of caricature can be used for many applications, such as face animation, face editing and 3D printing, which need 3D geometry information Compared with other tasks like 3D caricature modeling and caricature recognition, there is little research on automatic landmark detection for caricatures. As far as we know, one related work is proposed by Sadimon and Haron~\cite{sadimon2015neural}, which adopted the neural network to predict a facial caricature configuration. However, it can not process a single 2D caricature without its original facial image because the training dataset is constructed by image pairs- one normal facial image and its corresponding caricature image. Besides, their training and testing caricatures are all from exactly one artist, and thus the trained model can not be adapted to other caricatures with different art styles. There exist two main reasons to explain the difficulty of facial landmark detection for caricature. One reason is that caricatures have abstract and exaggerate patterns, and another is that caricatures have large representation varieties among different artists. As pointed out in~\cite{huo2017webcaricature}, compared with landmark detection on normal facial images, it is much more challenging on landmark detection for caricatures. \begin{figure} \begin{center} \includegraphics[width=1.0\linewidth]{showpic.pdf} \end{center} \caption{Some examples of automatic landmark detection and 3D reconstruction on test set. Given a single caricature image (first row), our algorithm generates its 3D model with orientation (second row) and corresponding 68 landmarks (third row).} \label{fig:showpic} \end{figure} In comparison to normal facial images, caricatures have two fundamental attributes- exaggeration and variety, and thus approaches for standard landmark detection can not be directly applied to solve this problem. One straightforward way is to regress the 2D landmarks' coordinates of caricature directly. However, 2D landmarks are controlled by facial shape and expression, facial orientation, and artistic style, which makes it a challenging problem to detect 2D landmarks. In order to alleviate the problem difficulty, we propose to decouple these factors. By regressing the 3D face model of caricature and face orientation, 2D landmarks can be recovered by projecting the 3D landmarks with the orientation. Therefore, it is quite essential to propose a method to represent the 3D face model of caricature. In 3D face reconstruction, parametric models, such as 3D Morphable Model (3DMM)~\cite{blanz1999morphable}, are usually used to represent 3D face shapes. However, such models are designed to represent normal face shapes and do not work well for caricature faces due to their limited capability of extrapolation~\cite{wu2018alive}. In this paper, to solve this challenging problem, we specifically design a parametric model for 3D caricature faces, and propose a method for landmark detection and 3D reconstruction of caricature based on this model. To this end, we manually label landmarks of about 6K caricature images with different styles. We further automatically generate nearly 2K caricatures with labeled landmarks from standard facial images via the method described in~\cite{cao2018carigans}. Based on the labeled landmarks, we recover the corresponding 3D caricature shape and orientations using an optimization method. With the large scale training dataset, we propose a novel convolutional neural network based method to regress the 3D caricature shape and orientation from the input 2D caricature. To well represent the 3D exaggerated face, we propose to regress its deformation representation rather than the Euclidean coordinates, which helps to improve the landmark detection and 3D reconstruction ability. In summary, the main contributions of this paper include the following aspects: \begin{itemize} \item To the best of our knowledge, this is the first work for automatic landmark detection and 3D face reconstruction for general caricatures. \item Rather than directly regress the 2D landmarks, we regress the 3D caricature shape and orientation from input 2D caricature image. 3D caricature shape is represented by a nonlinear parametric model learned from our constructed 3D caricature dataset. \item Comparisons with baseline methods and ablation studies demonstrate the effectiveness of each module of our proposed method. Extensive qualitative and quantitative experiments demonstrate that our method can automatically produce high accuracy results of 2D landmark detection and 3D shape reconstruction for caricature. \end{itemize} \section{Related Work} \begin{figure*} \begin{center} \includegraphics[width=1.0\linewidth]{pipeline.pdf} \end{center} \caption{Overview of our proposed Framework for Landmark Detection and 3D Reconstruction on general caricatures. Our network includes two parts, an encoder and a decoder. We use ResNet-34~\cite{he2016deep} backbone as the encoder, and 3 Fully Connected(FC) layers as the decoder to recover the 3D caricature shape. The PCA basis of deformation presentation ${\{\log \mathbf{R}_i, \mathbf{S}_i\}}$ is used to initialize the last FC layer.} \label{fig:pipeline} \end{figure*} This section briefly reviews some works that related to this paper, with a special focus on face alignment and 3D face reconstruction for normal facial images, and face alignment and 3D face reconstruction for caricatures. \noindent{\bf Face Alignment.} Face alignment and landmark detection for normal facial images have achieved great success in the last few years with the power of convolution neural networks. Kazemi and Sullivan~\cite{kazemi2014one} used an Ensemble of Regression Trees to estimate the facial landmark positions, and their method has been integrated into Dlib library~\cite{king2009dlib}, a modern C++ toolkit containing some machine learning algorithms. Wu \emph{et al.}~\cite{wu2017facial} proposed \emph{vanilla} CNN, which is naturally hierarchical and requires no auxiliary labels beyond landmarks. Kowalski \emph{et al.}~\cite{kowalski2017deep} developed Deep Alignment Network (DAN), a robust deep neural network architecture that consists of multiple stages. By adopting a coarse-to-fine Ensemble of Regression Trees, Valle \emph{et al.}~\cite{valle2018deeply} proposed a real-time facial landmark regression algorithm. Liu \emph{et al.}~\cite{liu2019semantic} noticed that the semantic ambiguity degrades the detection performance and addressed this issue by latent variable optimization methods. Dong \emph{et al.}~\cite{dong2018supervision} presented an unsupervised approach to improving facial landmark detectors, and Honari \emph{et al.}~\cite{honari2018improving} showed a new architecture and training procedure for semi-supervised landmark localization. To solve the occlusion problem, Zhu \emph{et al.}~\cite{zhu2019robust} developed an occlusion-adaptive deep network, which contains a geometry-aware module, a distillation module, and a low-rank learning module. Merget \emph{et al.}~\cite{merget2018robust} proposed a novel network architecture that has an implicit kernel convolution between a local-context subnet and a global-context subnet composed of dilated convolutions \noindent{\bf 3D Face Reconstruction from A Single Image.} 3D face reconstruction from a single image is to recover 3D facial geometry from a given facial image, which has applications like face recognition~\cite{blanz2003face,tuan2017regressing}, face alignment~\cite{zhu2016face, feng2018joint} and expression transfer~\cite{thies2015realtime,thies2016face2face}. Since Blanz and Vetter proposed a 3D Morphable Model (3DMM) in 1999~\cite{blanz1999morphable}, model-based methods have become popular in solving problems of 3D face reconstruction. Earlier, a large number of model-based algorithms considered some significant facial parts between 2D images and 3D templates, such as facial landmarks~\cite{cao2014displaced,jeni2015dense,grewe2016fully,thies2016face2face,JiangZDLL18}, latent representation~\cite{huber2015fitting} and so on. Cao \emph{et al.}~\cite{cao2013facewarehouse} utilized some RGBD sensors to create an extensive face database named FaceWareHouse, which contains 150 identities and 47 expressions of each identity. In recent years, deep learning-based methods have shown promising results in terms of computation time, robustness to occlusions and reconstruction accuracy. Guo \emph{et al.}~\cite{guo2018cnn} proposed a real-time dense face reconstruction method by constructing a large scale dataset augmented based on traditional optimization methods and adopting a coarse-to-fine CNN framework. Gecer \emph{et al.}~\cite{gecer2019ganfit} harnessed Generative Adversarial Networks (GANs) for reconstructing facial texture and shape from single images by training a generator of facial texture in UV space. Feng \emph{et al.}~\cite{feng20183d} presented a model-free method to rebuild the 3D facial geometry from a single light field image with a densely connected network. \noindent{\bf Face Alignment and Reconstruction of Caricature.} Compared with researches on normal facial images, there are fewer works about caricatures~\cite{o1997three,o19993d}. For face reconstruction, existing methods mainly focus on constructing a 3D caricature model from a normal 3D face model. Lewiner \emph{et al.}~\cite{lewiner2011interactive} introduced a caricature tool that interactively emphasizes the differences between two 3D meshes by utilizing the manifold harmonic basis of a shape to control the deformation and scales intrinsically. Vieira \emph{et al.}~\cite{vieira2013three} proposed a method based on deformations by manipulation of moving spherical influence zones. Sela \emph{et al.}~\cite{sela2015computational} presented a framework to scale the gradient fields of the surface coordinates by a function of the Gaussian curvature of the surface and solve a corresponding Poisson equation to find the exaggerated shape. Besides, there are some works on modeling 3D caricatures from images. Liu \emph{et al.}~\cite{liu2009semi} chose a semi-supervised manifold regularization(MR) method to learn a regressive model between 2D normal faces and enlarged 3D caricatures. With the power of deep learning, Han \emph{et al.}~\cite{han2017deepsketch2face} developed a CNN based sketching system that allows users to draw freehand imprecise yet expressive 2D lines representing the contours of facial features. With an intrinsic deformation representation that enables considerable face exaggeration, Wu \emph{et al.}~\cite{wu2018alive} introduced an optimization framework to address this issue. We adopt this approach to construct the training set of 3D caricatures. Landmark detection on caricature images is also a fundamental problem of caricature perception, but there are few works on this topic. As a related research direction, manga images have aroused Stricker \emph{et al.}'s~\cite{stricker2018facial} interest. Based on DAN~\cite{kowalski2017deep} framework, they proposed a new landmark annotation model for manga images and a deep learning approach to detect them. Huo \emph{et al.}~\cite{huo2017webcaricature} shows that caricature landmark detection is of great interest, but researches on this topic are still far from saturated. Besides, most studies on caricature generation need facial landmarks as control points ~\cite{liang2002example,cao2018carigans,shi2019warpgan}, which demonstrate that facial landmarks play an essential role in caricature related researches.
{'timestamp': '2020-04-21T02:24:48', 'yymm': '2004', 'arxiv_id': '2004.09190', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09190'}
arxiv
\section{Introduction} \label{sec:intro} \begin{figure}[t!] \centering\scriptsize \vspace*{-2ex} \begin{tabular}{@{}c@{}} \includegraphics[width=0.65\linewidth]{hook.jpg} \\ \begin{tabular*}{0.72\linewidth}{@{}l@{\extracolsep{\fill}}r@{}} \textbf{Question} & \textbf{Answer} \\ \cmidrule{1-1} \cmidrule{2-2} How old is the baby? & About 2 years old \\ What color is the remote? & White \\ Where is the train? & On the road \\ How many cows are there? & Three \\ \end{tabular*} \end{tabular} \vspace*{-2ex} \caption{% Failures in \emph{visual} dialogue (from~\citet{massiceti2018novd})---answers are unrelated to the image. Biases in the \textit{VisDial} dataset, compounded by a rank-based evaluation, can mislead progress on the \acrshort{VD} task. } \label{fig:another-vd-fail} \vspace*{-1ex} \end{figure} The growing interest in visual conversational agents~\citep{Antol_VQA,Das_VisualDialog,de2017guesswhat,johnson2017clevr} has motivated the need for automated evaluation metrics for the responses generated by these agents. Robust evaluation schemes, however, are an open research challenge~\citep{mellish1998evaluation,reiter2009investigation}. This is the case for \textit{VisDial}~\citep{Das_VisualDialog}, a dataset targeting the \gls{VD} task---answering a sequence of questions about an image given a history of previous questions and answers. At test time, a trained model is used to score fixed sets of candidate answers for each test question, and a suite of rank-based metrics are computed on the ranked sets: single-candidate metrics which are a function of the ground-truth (\textsc{gt}) answer's position, and a multi-candidate metric which weighs the ranked set with relevance scores assigned from human annotation. A limit of this scheme is that a simple model~\citep{massiceti2018novd} based on \gls{CCA}, which learns to maximise correlation between questions and answers while completely ignoring the image and dialogue history, is comparable in \gls{MR}---one of the dataset's primary rank-based metrics---to \gls{SOTA} models, all of which employ complex neural network architectures of millions of parameters, requiring many hours of \textsc{gpu}(s) training. This suggests that exploitable biases exist within the \textit{VisDial} dataset, whose effects are compounded by a rank-based evaluation ill-suited to the \gls{VD} task. Motivated by this, we propose a revised, more robust, evaluation scheme for the \gls{VD} task, informed by the key shortfalls of the current evaluation, namely that \begin{inparaenum}[1)] \item the candidate sets contain multiple, \emph{equally feasible} answers, rendering both single- and multi-candidate ranking metrics less meaningful, and \item the evaluation is an indirect ranking task, rather than a direct assessment of the answers \emph{generated} by a model---the goal of a \gls{VD} agent. \end{inparaenum} Our revised evaluation instead adopts standard metrics from \textsc{nlp} to measure the similarity between an answer \emph{generated} by a model and a reference set of answers for the image and question. This aligns better with the generative nature of a true \gls{VD} agent, and with established evaluation set-ups for other language generations tasks, including \acrshort{VQA}~\citep{Antol_VQA} and image captioning~\citep{ChenFLVGDZ15,young2014image}. Unlike the current evaluation, it also accounts for diversity in answer generations, which we compare across models. For \textit{VisDial}, however, the answer relevance scores used to construct the reference sets are only available for a small subset of the dataset. Drawing on the pseudo-labelling literature for semi-supervised learning~\citep{lee2013pseudo,wu2006fuzzy,iscen2019label}, we develop a semi-supervised approach which leverages these human annotations, and automatically learns to extract the relevant answers from a given candidate set. We apply \gls{CCA} between pre-trained question and answer features, channelling~\citet{massiceti2018novd}, and use a clustering heuristic on the resulting correlations to extract the candidate answers most correlated with the ground-truth answer---the reference sets, or pseudo-labels. This was inspired by prior work showing the surprising strength of simple, non-deep baselines~\citep{ZhouTSSF15,massiceti2018novd,strang2018don,anand2018blindfold}. Using this approach, we automatically construct sets of relevant answers for the entire \textit{VisDial} dataset, which we validate in multiple ways, including with human judgements via \gls{AMT}, and release as \textit{DenseVisDial}{}---a dense version of \textit{VisDial}. Using this data and the revised scheme, we re-evaluate existing \gls{SOTA} models and gain new insights into model differences, specifically generation diversity, otherwise unavailable with the existing evaluation. The scheme also improves on the existing multi-candidate ranking evaluation, only applicable for \(1/10\) of the dataset due to the cost and time of collecting relevance scores from humans. Finally, while we use these reference sets exclusively for better evaluation purposes, we also show that using them as (for-free) additional training data can improve performance, which is promising for future progress on the \gls{VD} task. \noindent% To summarise, our contributions are: \begin{compactenum} \item A revised evaluation scheme for the \textit{VisDial} dataset based on metrics from \textsc{nlp} which measure the similarity between a \emph{generated} answer and a reference set of feasible answers. % \item A semi-supervised method for automatically extracting these reference sets from given candidate sets at scale, verified using human annotators. % \item An expanded \textit{DenseVisDial}{} data with the automatically constructed reference sets, released for future evaluation and model development. \end{compactenum} \section{Preliminaries} \label{sec:prelim} We first define generative \gls{VD} (for \textit{VisDial}), and how~\citet{massiceti2018novd} employ \gls{CCA} for this. \subsection{Visual Dialogue (\acrshort{VD}) \& \textit{VisDial} dataset} \label{sec:prelim-vd} Given image~\(I\) and dialogue history \([(Q_1, A_1), (Q_2, A_2), \ldots, Q_i]\), the generative \gls{VD} task involves generating answer \(A_i\). The principal approach towards \gls{VD} has been facilitated by the \textit{VisDial} dataset~\citep{Das_VisualDialog}, a large corpus of images paired with question-answer dialogues, sequentially collected by pairs of annotators in an interactive game on \gls{AMT}. {\it VisDial v1.0} comprises \(123,287/2064/8000\) train/val/test images, each paired with dialogues of up to 10 exchanges\footnote{10 exchanges for train/val, and \(\leq\) 10 exchanges for test.}. Each question is coupled with a candidate set of 100 answers~\(\bm{A}\) including a ground-truth answer~\(A_{\text{gt}} \in \bm{A}\). For a subset (2000/2064/8000), one question per image contains human-annotated relevance scores~\(\rho(A) \in [0,1] \, \text{where\,} A \in \bm{A}\). The generative \gls{VD} task learns to \emph{generate} answers conditioned on image-question pairs using only \((I,Q,A_{\text{gt}})\) triplets~\citep{Das_VisualDialog}. At test time, given an image-question pair, each answer in its associated candidate answers \(\bm{A}\) is scored under the model's learned likelihood. The rank of~\(A_{\text{gt}}\) is then used to judge the model's effectiveness at the \gls{VD} task, averaged over the dataset to get the \gls{MR}. Other metrics also computed include \gls{NDCG} on the candidate answers' human-annotated relevance scores. In a second paradigm introduced by~\citet{Das_VisualDialog}, the model instead uses the full \((I,Q,\bm{A})\) at train time, and simply frames the predictive task as a classification problem of selecting~\(A_{\text{gt}}\) out of~\(\bm{A}\). At test time, the candidates are then directly scored by the classifier's \textit{softmax} probabilities. We argue that this discriminative setting is an over-simplification of the \gls{VD} task: answering questions is not simply selecting the correct answer from a set. The focus of the remainder of this paper is therefore fully on the generative \gls{VD} task. \glsreset{MR} \subsection{Canonical Correlation Analysis for \gls{VD}} \label{sec:ccaforvd} \gls{CCA}, applied between question and answers, achieves near-\gls{SOTA} \gls{MR} on the \textit{VisDial} dataset~\citep{massiceti2018novd}. Inspired by this result and the extreme simplicity of \gls{CCA}, we introduce this formulation with reference to \gls{VD}. Given paired observations $\{\mathbf{x}_1 \in \mathbb{R}^{n_1}, \mathbf{x}_2 \in \mathbb{R}^{n_2}\}$, \gls{CCA} jointly learns projections \( W_1 \in \mathbb{R}^{n_1 \times k} \) and \( W_2 \in \mathbb{R}^{n_2 \times k} \), \( k \leq \min (n_1,n_2) \), which are maximally correlated~\citep{hotelling1936}. Projections are obtained via a generalised eigenvalue decomposition, \( A \bm{v} = \lambda B\bm{v}\)~\citep{kettenringMultiCCA1971,hardoonMultiCCA2004,bachkernelICA2002}, where \(A\) and \(B\) are the inter- and intra-view correlation matrices. Projection matrix \(W_i \in \real^{n_i \times k}\) embeds~\(\mathbf{x}_i\) from view~\(i\) as \(\phi(\mathbf{x}_i; W_i) = D_{\bm{\lambda}}^p W_i^{\top} \mathbf{x}_i\), { where \(D_\lambda\) is a diagonal matrix of the top \(k\) (sorted) eigenvalues~\(\bm{\lambda}\), and~\(p\) is a scalar weight. With \gls{CCA}, ranking and retrieval across views~\(\{ \mathbf{x}_i, \mathbf{x}_j \}\) is performed by computing correlation between projections~\(\mathrm{corr}(\mathbf{x}_i, \mathbf{x}_j) = \frac{\psi(\mathbf{x}_i)^\top \psi(\mathbf{x}_j) }{\norm{\psi(\mathbf{x}_i)}_2 \norm{\psi(\mathbf{x}_j)}_2}\) where \(\psi\) is a mean-centred (over \emph{train} set) version of \(\phi\). Using \gls{CCA}, learnt embeddings between answers and questions (\gls{CCA}\textsc{-aq}) are used to compute the ranking and \gls{NDCG} metrics. \gls{CCA} can also be used to \emph{generate} answers using correlations. For a given test question, its \(100\) nearest-neighbour questions (based on correlation under the A-Q model) are extracted from the train set. Their \(100\) corresponding ground-truth answers are used to construct a pseudo-candidate set. Answers are \emph{generated} by the model, denoted \gls{CCA}\textsc{-aq-g}, by sampling from this set in proportion to correlation with the test question (see Figure 3 in~\citet{massiceti2018novd}). \section{\!\!Shortfalls of Current \textit{VisDial} Evaluation\!\!} \label{sec:shortcomings} The fact that a simple, lightweight \gls{CCA} model performs favourably in \gls{MR} with current \gls{SOTA} models, while completely ignoring the image and dialogue history, and requiring an order of magnitude fewer learnable parameters and mere seconds on \textsc{cpu} to train, is a cause for concern. Not only do prior results suggest that implicit correlations between just the questions and answers exist in the data (see~\cref{fig:another-vd-fail}), but also that the current evaluation scheme generally is not flexible enough to account for variation in answers to visually-grounded questions. Here we summarise the existing evaluation scheme, discuss the hidden factors affecting it, and make the case that to better capture a model's performance on the \gls{VD} task, there must be changes to the evaluation scheme. \subsection{Current evaluation scheme} Given a test question, the current \textit{VisDial} evaluation relies on ranking its candidate answers~\citep{Das_VisualDialog}, derived from scoring the answers under the trained (generative) model's likelihood (see~\cref{sec:prelim-vd}). A suite of rank-based metrics is then computed: \acrfull{MR} and \gls{MRR} of the ground truth (\textsc{gt}) answer over data, and the average recall, measuring how often the \textsc{gt} answer falls within the top 1, 5, and 10 ranks, respectively. These {\bf single-candidate} (i.e. \textsc{gt}) ranking metrics have been the norm since \textit{VisDial}'s inception. A subsequent extension of the dataset (\textit{v1.0}) tasked 4-5 human annotators with labelling whether each answer in a candidate set is valid for a given image-question (a hard 0/1 choice) for a subset of the train and validation sets, denoted \(\mathcal{H}_t\) and \(\mathcal{H}_v\), respectively. For each candidate answer~\(A\), the mean judgement across annotators becomes a \emph{relevance} score~\(\rho(A) \in [0,1]\). A modified {\bf multi-candidate} ranking metric, the \gls{NDCG}, is then introduced: candidate answers' ranks are weighted by their relevance scores, excluding irrelevant~(\(\rho(A) = 0\)) answers. See \cref{sec:app-ndcg} for further details. \subsection{Analysing current shortfalls} The above evaluation metrics, by construction, are not flexible enough to account for the many ways a question can satisfactorily be answered. This limitation manifests in both the single- and multi-candidate ranking metrics, and hampers the measurement of a model's true ability to answer a visual question. The limitation stems from: \begin{compactenum} \item ranking candidate sets that are ill-constructed for the ranking task, and \item disregarding answers \emph{generated} by a model in favour of indirectly ranking these fixed sets. \end{compactenum} \subsubsection{Ranking ill-constructed candidate sets} Candidate answer sets in \textit{VisDial} are typically observed to contain multiple feasible answers---as they include up to 50 nearest-neighbour answers \citep{Das_VisualDialog} to~\(A_{\text{gt}}\) in \textit{GloVe}~\citep{pennington2014glove} space. Rank-based metrics, which assume a meaningful ordering of answers, are less informative when considering feasible-answer subsets. We explicitly verify this characteristic of candidate answers using correlation, through the following experiment which learns a \gls{CCA} model between the question and answer features. Computing the correlation between~\(A_{\text{gt}}\) and~\(A \in \bm{A} \setminus A_{\text{gt}}\), giving~\(\mathcal{C} = (\phi(A_{\text{gt}}, A_1), \ldots, \phi(A_{\text{gt}}, A_{100}))\), we then select the cluster of answers with correlations in~\([\mathcal{C}_{\text{max}}-\sigma, \mathcal{C}_{\text{max}}], \text{where\,\,} \mathcal{C}_{\text{max}}\!=\!\mathrm{max}(\mathcal{C}), \sigma\!=\!\mathrm{stdev}(\mathcal{C})\), roughly estimating answers which are plausibly similar to~\(A_{\text{gt}}\). Given this cluster, we compute the mean and standard deviation of the correlations, as well as the cluster size, to measure how small and tightly packed these clusters are. We average these across all candidate sets, giving an average mean correlation of \(0.58\), an average standard deviation of \(0.22\), and an average cluster size of \(12.30\). These results support the idea that an \emph{equivalence class} of feasible answers exist within each candidate set, which can then adversely affect both classes of metrics described below. {\bf Single-candidate ranking metrics} assign a single answer, the labelled \textsc{gt}, as the \emph{only} correct answer in the candidate set, and are purely a function of this privileged answer's rank. As a result, these metrics unduly penalise models that rank alternate, but equally feasible, answers highly. \Gls{MR}, \gls{MRR}, and \textsc{r@1,5,10} are thus only weakly indicative of performance on the \gls{VD} task, and are unable to differentiate between equally good models. The ill-constructed candidate sets also render single-candidate metrics unable to \emph{rule out} poor models. In other words, models with poor \gls{MR}, \gls{MRR} and \textsc{r@1,5,10} aren't necessarily poor at \gls{VD}. This is markedly the case for \gls{MRR} and \textsc{r@1,5,10} which are, by definition\footnote{While obvious for recall, \gls{MRR} as the inverse harmonic mean, weighs smaller ranks more strongly than larger ranks.}, biased toward low ranks---a model predicting five \textsc{gt} answers at rank 1, and five at rank 10, scores better \gls{MRR}/\textsc{r@1,5,10} than a model with all ten \textsc{gt} answers at rank 2 (coincidentally, these results are meaningless if the candidate set contained \(10\) equally feasible answers). This bias particularly affects models trained with a single-answer objective (i.e. all \gls{SOTA}) models. To see why, we show the distribution of \textsc{gt} answer ranks between \gls{CCA}\textsc{-aq} and a \gls{SOTA} model in~\cref{fig:histo}. The \gls{SOTA} model is skewed toward the \textsc{gt} answer achieving rank 1---the combined result of a single-answer objective and high parametrisation. This leads \gls{SOTA} models to view other feasible answers in the set as no different if ranked 2 or 100. \gls{CCA}\textsc{-aq} by contrast ignores rank and simply learns by maximising A-Q correlation, likely leading it to rank other feasible answers highly. Thus, models favouring low ranks by virtue of their learning objective may achieve better \gls{MRR}/\textsc{r@1,5,10}, but not be discernibly better than models accounting for multiple answers being correct. \begin{figure} \begin{subfigure}{.22\textwidth} \includegraphics[width=\textwidth]{images/histo_vd.png} \vspace*{-2em} \caption{\textsc{hrea-qih-g}} \end{subfigure} \begin{subfigure}{.22\textwidth} \includegraphics[width=\textwidth]{images/histo_cca.png} \vspace*{-2em} \caption{\gls{CCA}\textsc{-aq}} \end{subfigure} \vspace*{1em} \caption{% Distribution of \textsc{gt} answer ranks across \textit{VisDial v1.0} val set. Highly-parametrised \gls{SOTA} models (a) pushes the \textsc{gt} rank towards 1, ignoring other potentially feasible answers, in contrast to \gls{CCA}\textsc{-aq} (b). % } \label{fig:histo} \vspace*{-0.1em} \end{figure} These findings, together, suggest that the single-candidate metrics cannot reliably quantify performance and compare models in lieu of the \gls{VD} task. {\bf Multi-candidate ranking metrics}, or \gls{NDCG}, undoubtedly take a step in the right direction by forgoing just a single correct answer, and weighting the predicted ranking with human-annotated relevance scores for multiple answers. \gls{NDCG}, however, is still a function of a ranking, and hence assumes that a single optimal ordering of candidate answers exists. The presence of multiple \emph{equally} feasible answers in the candidate sets thus breaks this assumption and can skew the \gls{NDCG}, albeit to a lesser degree than \gls{MR}, \gls{MRR}, and \textsc{r@1,5,10}. Moreover, the degree of answer similarity within these subsets raises further concerns for the reliable computation of \gls{NDCG}. Requiring annotation of 100 valid (i.e. similar) answers is an arduous task, and converting hard 0/1 judgements into relevance scores over just a handful (4-5) of annotators can be noisy. Our analysis reveals the following quirks: \begin{compactitem} \item \(18.15\%\)\big/\(47.14\%\) of the validation/train annotated subsets (\(\mathcal{H}_v\)\big/ \(\mathcal{H}_t\)), do not have a {\em single} candidate answer with relevance score \(1.0\), not even the ground-truth, indicating poor consensus. \item 20.69\%\big/9.01\% of samples, respectively, consider the ground-truth irrelevant (\(\rho(A_{\text{gt}}) = 0\)). \end{compactitem} Coupled with this, the scale of \textit{VisDial} makes obtaining annotations a daunting (and expensive) task---reflected in the fact that only a small fraction of the data, one question per image, has annotations (see \cref{sec:prelim}), which implies evaluations effectively ignore dialogue history. Also, without more annotators (and hence cost/time), obtaining relevance scores at-scale may well be meaningless. \subsubsection{Ignoring generated answers} The ultimate goal of \gls{VD} is to produce an answer to a given question, not to pick an answer from a set---our primary motivation for focussing on the \emph{generative} \gls{VD} task. The current evaluation, rather than directly evaluating the answers generated by a model, evaluates by how well a model ranks a fixed set of candidate answers. Not only is this problematic because of the candidate sets' limitations (as described above), but also because it: \begin{inparaenum}[1)] \item disregards diversity in answer generations, a necessary feature for a human-like answering agent, and \item goes against established practice in the \acrshort{VQA} literature~\citep{Antol_VQA} which evaluates by comparing the predicted answer to answers collected from 10 human annotators. \end{inparaenum} While it is expected that scoring a valid answer by its likelihood is a reasonable measure of a model's ability to \emph{generate} a good answer, this may not necessarily be the case when there are multiple potential answers, some not even in the candidate set. Although likelihoods can serve as a \emph{relative} measure between candidates, the highest-probability answers may be entirely different or unrelated---indicating a poorly learnt model. This supports the idea that a metric which ignores generated answers may fail to account for models no less ``good'' at the \gls{VD} task. \section{A Revised Evaluation for \textit{VisDial}} \label{sec:new-eval} The analysis in \cref{sec:shortcomings} indicates that an evaluation well matched to the underlying goals of \gls{VD} should: \begin{compactenum}[i)] \item directly use answers generated by the model, \label{feat:gen} \item account for multiple valid answers, and \label{feat:multi} \item do the above at scale over the entire dataset. \label{feat:scale} \end{compactenum} We thus develop a revised evaluation scheme for \gls{VD} which meets these three criteria. Its basis lies in measuring how similar an answer \textit{generated} by a given model is to a \textit{set} of feasible reference answers for a given question and image. We describe similarity quantification in \cref{sec:measuring-similarity} and the construction of high-quality reference sets in \cref{sec:obtaining-refs}. \subsection{Measuring similarity} \label{sec:measuring-similarity} We measure similarity using established \textsc{nlp} consensus metrics between a predicted answer and a reference set of valid answers. Crucially, the predicted answer is \textit{generated} by the model directly, and the reference set contains more than one element, accounting for the presence of multiple valid answers. We use two classes of metric for capturing consensus: overlap and embedding distance. {\bf Overlap-based} metrics compute the overlap or co-occurrence of \(n\)-grams (word couplets of size~\(n\)) between pairs of sentences---here, the generated answer and each answer in the reference set. We use two such metrics: {\sc cider} \citep{Vedantam_2015cider} and {\sc meteor} \citep{Denkowski_2014meteor}, motivated by their extensive use in image captioning benchmarks~\citep{ChenFLVGDZ15,hodosh2013framing,young2014image}. Both are known to be well correlated with human judgements. {\sc cider} computes the cosine similarity between a pair of vectors, each of which is composed of the term-frequency inverse-document-frequencies (tf-idf) of the sentence's \(n\)-grams. For \(0 < n \leq i\), similarities are averaged over all \(n\)-grams up to length \(i\). {\sc meteor} is similar, but first applies a uni-gram matching function, before computing a weighted harmonic mean between uni-gram precision and recall, with a fragmentation penalty on the matching. {\bf Embedding distance-based} metrics arise from a rich literature in capturing semantic similarity between natural language expressions~\citep{bojanowski2017enriching,pennington2014glove,devlin2018bert,peters2018elmo,sharma2017relevance}. Motivated by the recent successes of {\sc bert}~\citep{devlin2018bert} and {\it FastText}~\citep{bojanowski2017enriching} in a variety of \textsc{nlp} tasks, we use each method to embed the generated answer and each reference set answer, computing the \(L_2\) and cosine similarity (CS) between them, averaging over the reference set. The embedding metrics aim to complement the overlap-based metrics and guard against limitations of the latter that might arise due to answer lengths (one- or two-word) frequently seen in the \acrshort{VD} data. \subsection{Obtaining answer reference sets} \label{sec:obtaining-refs} We now describe how to obtain reference sets for the similarity measures defined above. \subsubsection{Using humans} \label{sec:obtaining-refs-humans} For a small subset of the \textit{VisDial} validation set, \(\mathcal{H}_v\), soft relevance scores are available (from human annotators) for each of the 100 candidate answers associated with each image-question (see~\cref{sec:prelim-vd}). Using these scores, we construct answer reference sets for each image-question, composed of all the candidate set answers deemed valid by at least one annotator, i.e.\ \(\rho(A) > 0\), where to our surprise, we found multiple instances where \(\rho(A_{\text{gt}}) = 0\). Protecting against such cases, we define the human-annotated reference set \(H = \{A : \rho(A) > 0, \forall A \in \bm{A}\} \cup \{A_{\text{gt}}\}\). \subsubsection{Using semi-supervision at scale} \label{sec:obtaining-refs-at-scale} Human-annotated relevance scores, and hence reference sets, however, are available for only a fraction of the dataset---less than 1\% of questions! The scale of \textit{VisDial}---on the order of \(10^6\) questions, each with \(100\) candidate answers---makes extending these annotations to the entire dataset extremely challenging. Assuming \(\$0.05\) per question, each presented to \(10\) workers, would incur a cost of over \(\$500,000\) and substantial annotation time! We therefore propose a semi-supervised approach which harnesses the annotations we \emph{do} have: given a candidate set of answers for an image-question, we learn to extract the valid answers, and hence automatically construct a reference set. Not only does this enable us to obtain reference sets at scale, but it also circumvents the time, cost and idiosyncrasies associated with human annotation. Our approach is based on \gls{CCA}, and uses the relevance-annotated subset of the full train set, \(\mathcal{H}_t\), as training data. Similar to~\cref{sec:obtaining-refs-humans}, we construct \emph{training} reference sets \(H_t\) using \(\mathcal{H}_t\). Pairing each question with \emph{all} answers in \(H_t\), we learn a \gls{CCA} model between the questions and answers. With this model, denoted \gls{CCA}\textsc{-aq}\textsuperscript{*}, we compute correlations between~\(A_{\text{gt}}\) and \(\bm{A} \setminus A_{\text{gt}}\), giving \(\mathcal{C} = (\phi(A_{\text{gt}}, A_1), \ldots, \phi(A_{\text{gt}},A_{100}))\) similar to \cref{sec:shortcomings}. We then cluster these correlations in \(\mathcal{C}\) to construct a reference set~\(\Sigma = \{A : \phi(A_{\text{gt}}, A) \in [\mathcal{C}_{\text{max}} - \sigma, \mathcal{C}_{\text{max}}]\} \cup \{A_{\text{gt}}\} \) where \(\mathcal{C}_{\text{max}} = \mathrm{max}(\mathcal{C})\), and \(\sigma = \mathrm{stdev}(\mathcal{C})\). Intuitively, this extracts the cluster of answers with highest correlation or similarity to the ground-truth answer. With this semi-supervised approach, we easily and quickly obtain reference sets at scale for the \textit{entire} \textit{VisDial} dataset. \paragraph{Verifying automatic reference sets} The validity of the revised evaluation is contingent on the validity of the automatic reference sets---that they are composed of valid answers. We verify this by: \begin{compactenum}[(1)] \item computing intersection metrics between the human-annotated and automatic reference sets, \item using \gls{AMT} to verify the sets, and \item measuring how \textit{training} a \gls{VD} model on these sets can improve performance on \gls{VD}. \end{compactenum} For (1), we compute the \gls{IOU}, precision, recall, and set size of the automatic~\(\Sigma\) and human-annotated~\(H\) reference sets on the validation subset~\(\mathcal{H}_v\) (\cref{tab:clusters}). These metrics serve as a simple heuristic and we use them to compare clustering methods (see extended comparison in~\cref{sec:app-clustering}). Our best method, \(\Sigma\), extracts similar sized clusters to \(H\) (\(7.17\) vs \(12.77\)) with good precision (\(62.48\%\); i.e. it selects answers maximally in~\(H\)), supporting the similarity of \(\Sigma\) and \(H\). \begin{table}[t] \centering \def\hspace*{7pt}{\hspace*{7pt}} \scalebox{0.7}{ \begin{tabular}{c@{\hspace*{7pt}}c@{\hspace*{7pt}}c@{\hspace*{7pt}}c@{\hspace*{7pt}}c@{\hspace*{7pt}}} \toprule \(C\) & \(\frac{|H \cap C|}{|H \cup C|}\) & \(\frac{|H \cap C|}{|C|}\) & \(\frac{|H \cap C|}{|H|}\) & \(|C|\) \\ \midrule \(H\) & 100.00 (0.00) & 100.00 (0.00) & 100.00 (0.00) & 12.77 (7.24) \\[0.5ex] \(\Sigma\) & 24.13 (16.73) & 62.48 (31.24) & 32.91 (23.52) & 7.17 (6.94) \\ \bottomrule \end{tabular}} \vspace*{-1ex} \caption{% Evaluation of intersection metrics computed on human-annotated reference sets~\(H\) and automatic reference sets~\(\Sigma\), on the validation subset~\(\mathcal{H}_v\). % Values in parentheses denote standard deviation across the set.} \label{tab:clusters} \vspace*{1ex} \end{table} For (2), we turn to \gls{AMT}. Given an image, question and answer reference set (from either \(\Sigma\) or \(H\)) as a task, a turker is asked to de-select all infeasible answers (see~\cref{sec:app-clustering} for \gls{AMT} user interface). For each task, scores are averaged over 5 turkers. We then measure the proportion of the reference set selected, and the proportion of the set where at least 1 turker selected each answer. For a subset of tasks randomly sampled from \(\mathcal{H}_v\) or the full validation set, in~\cref{tab:mturk-cluster-val} we observe that our proposed semi-supervised reference sets are similar to the ones obtained using humans. \begin{table}[t] \centering \def\hspace*{7pt}{\hspace*{7pt}} \scalebox{0.8}{ \begin{tabular}{r@{\hspace*{7pt}}c@{\hspace*{7pt}}c@{\hspace*{7pt}}} \toprule & \(C=H\) & \(C=\Sigma\) \\ \cmidrule{2-3} \# tasks & \(1,680\) & \(5,040\) \\ \# turkers per task & 5 & 5 \\ \% \(C\) selected & \(81.48 \;(2.15)\) & \( 70.66 \;(5.45) \) \\ \% \(C\) selected (\(\ge 1\) turker) & \(98.80 \;(0.37)\) & \( 95.52 \;(2.22) \) \\ \bottomrule \end{tabular}} \vspace*{-1ex} \caption{% \Acrshort{AMT} validation of automatic reference sets \(\Sigma\) against human-annotated sets \(H\). % For each task, given an image, question and answer set (from either \(\Sigma\) or \(H\)), turkers are asked to deselect infeasible answers, with scores averaged over 5 turkers. % We measure the proportion of each set selected, and the proportion of each set where \(\geq\)1 answer was selected. Variance in brackets. } \label{tab:mturk-cluster-val} \vspace*{1ex} \end{table} Finally, in (3), we intuit that if reference sets \(\Sigma\) contain answers similar to the correct answer, then a model trained on only these sets should improve performance on the \gls{VD} task. We, therefore, pair each question in the training subset~\(\mathcal{H}_t\) with each of the answers in its corresponding~\(\Sigma\), and train a \gls{CCA}\textsc{-aq} model. As a baseline, we repeat this experiment, but pairing the questions with answers from~\(H\) instead of~\(\Sigma\). We show in~\cref{tab:ndcg-cluster} (top 2 rows), the model trained using~\(\Sigma\) performs better than that employing the human-annotated reference sets~\(H\) across the battery of ranking metrics, including \gls{NDCG}. As a further check, we train a \gls{CCA}\textsc{-aq} model on~\(\mathcal{H}_t\), but only between questions and their single ground-truth answers~\(A_{\text{gt}}\) (as opposed to {\em all} answers in \(H\) or \(\Sigma\)). As we address in \cref{sec:shortcomings}, this model surprisingly outperforms the baseline using~\(H\) as reference on the single-candidate ranking metrics, however, as expected, \gls{NDCG} paints a better picture, showing reduced performance. Finally we conduct (3) across the whole dataset, learning a \gls{CCA}\textsc{-aq} model using~\(\Sigma\), over the entire training data of \textit{VisDial (v1.0)}. The last two rows of \cref{tab:ndcg-cluster} compare this model against the standard \gls{CCA}\textsc{-aq} trained on questions and ground-truth answers. We observe a substantial improvement in \gls{NDCG}, with what is effectively a simple data augmentation procedure using~\(\Sigma\). This three-part verification supports the existence of valid answers in the automated reference set, which subsequently supports our revised evaluation scheme. \begin{table}[t] \centering \def\hspace*{7pt}{\hspace*{4ex}} \newcommand{\mr}[2]{\multirow{#1}{*}{{#2}}} \newcommand{\mc}[2]{\multicolumn{#1}{c}{{#2}}} \scalebox{0.65}{ \setlength{\tabcolsep}{3pt} \begin{tabular}{@{}cr>{$}c<{$}@{\hspace*{7pt}}*{6}{c}@{}} \toprule \mc{2}{Train} & \mr{2}{Ref} & \mr{2}{MR} & \mr{2}{R@1} & \mr{2}{R@5} & \mr{2}{R@10} & \mr{2}{MRR} & \mr{2}{NDCG} \\ \cmidrule{1-2} \text{Set} & \#QA pairs & & \(\downarrow\) & \(\uparrow\) & \(\uparrow\) & \(\uparrow\) & \(\uparrow\) & \(\uparrow\) \\ \midrule \mr{3}{\(\mathcal{H}_t\)} & 15,317 & H & 26.49 & 6.05 & 21.50 & 35.53 & 0.1550 & 0.3647 \\ & 17,055 & \Sigma & {\bf 20.36} & 8.35 & 32.88 & {\bf 48.78} & 0.2066 & {\bf 0.3715} \\ & 1996 & \{A_{\text{gt}}\} & 23.71 & {\bf 13.13} & {\bf 34.05} & 46.90 & {\bf 0.2428} & 0.2734 \\ \cmidrule(l){2-9} \mr{2}{all} & 10,419,489 & \Sigma & 17.20 & 10.73 & 34.20 & 51.80 & 0.2312 & {\bf 0.4023} \\ & 1,232,870 & \{A_{\text{gt}}\} & {\bf 17.07} & {\bf 16.18} & {\bf 40.18} & {\bf 55.35} & {\bf 0.2845} & 0.3493 \\ \bottomrule \end{tabular}} \vspace*{-1ex} \caption {% Evaluating the utility of automated reference sets~\(\Sigma\) on standard \gls{VD} evaluation. % \gls{CCA}\textsc{-aq} models were trained on the indicated subsets (\(\mathcal{H}_t\) or all) of \textit{VisDial (v1.0)}, with answers from different sets (`Ref'), and tested on the \href{https://visualdialog.org/challenge/2018}{evaluation test server} to compute standard metrics. Arrows indicate which direction is better. } \label{tab:ndcg-cluster} \end{table} \section{Experimental Analyses} Here we include experimental analyses, focussing in particular on the performance of models under our revised evaluation schemes discussed in~\cref{sec:new-eval}. We represent words in the questions/answers as 300-dimensional \textit{FastText}~\citep{bojanowski2017enriching} embeddings. To obtain sentence embeddings, we simply average word embeddings following generally received intuition~\citep{aurora2017simple,wieting2017random}, padding or truncating up to 16 words following~\citet{massiceti2018novd}. We generate answers from \gls{CCA}\textsc{-aq-g} and the following \gls{SOTA} models: \textsc{hrea-qih-g}~\citep{Das_VisualDialog}, \textsc{hciae-dis-g}~\citep{lu2017best} and \textsc{rva}~\citep{niu2019recursive}, with * indicates use of beam search. For each, we train on the full \textit{VisDial v1.0} train set, cross-validate on \gls{MRR}, and select the best epoch's model for subsequent evaluation. \subsection{Revised evaluation results} \paragraph{Testing on \(\mathcal{H}_v\)} \Cref{tab:consensus} (left) shows the overlap and embedding distance scores of answers generated by models, measured against human-annotated reference sets \(H\) for the validation subset \(\mathcal{H}_v\). Note, we report on~\(\mathcal{H}_v\) because relevance scores are available for only part of \textit{VisDial}'s full validation set and are publicly unavailable for its test set. \begin{table*}[!th] \def\hspace*{7pt}{\hspace*{3ex}} \def\mc#1#2{\multicolumn{#1}{c}{{\sc #2}}} \def\(\uparrow\){\(\uparrow\)} \def\(\downarrow\){\(\downarrow\)} \def\(^{\star}\)\!\!{\(^{\star}\)\!\!} \begin{subtable}{0.52\textwidth} \centering \scalebox{0.53}{ \setlength{\tabcolsep}{3pt} \begin{tabular}{@{}l*{4}{c}@{\hspace*{7pt}}c@{\hspace*{7pt}}*{2}{c}@{\hspace*{7pt}}*{2}{c}@{}} \toprule Model & \mc{4}{cider\(\uparrow\)} & {\sc meteor\(\uparrow\)} & \mc{2}{bert} & \mc{2}{FastText} \\ \cmidrule(r){2-5} \cmidrule(l){7-8}\cmidrule(l){9-10} & n=1 & n=2 & n=3 & n=4 & & \(L_2\)\(\downarrow\) & CS\(\uparrow\) & \(L_2\)\(\downarrow\) & CS\(\uparrow\) \\ \midrule \(\Gamma_H\) & 0.2765 & 0.2151 & 0.1810 & 0.1513 & 1.0000 & 4.7000 & 0.9334 & 1.8757 & 0.6992 \\ \cmidrule{2-10} \gls{CCA}\textsc{-aq-g} & 0.0721 & 0.0434 & 0.0298 & 0.0226 & 0.2713 & 7.1231 & 0.8690 & 3.1251 & 0.4555 \\ \textsc{hrea-qih-g} & 0.0880 & 0.0483 & 0.0333 & 0.0252 & 0.4813 & 6.2875 & 0.8927 & 2.9724 & 0.5079 \\ \textsc{hrea-qih-g*} & {\bf 0.1359} & {\bf 0.0721} & {\bf 0.0494} & {\bf 0.0372} & {\bf 0.7149} & {\bf 5.5727} & {\bf 0.9149} & 3.2664 & 0.4971 \\ \textsc{hciae-g-dis} & 0.1338 & 0.0718 & 0.0493 & {\bf 0.0372} & 0.6758 & 5.6690 & 0.9122 & 3.1551 & 0.5049 \\ \textsc{rva} & 0.1042 & 0.0563 & 0.0385 & 0.0291 & 0.5328 & 6.1466 & 0.8967 & { \bf 2.9543} & {\bf 0.5161} \\ \bottomrule \end{tabular}} \label{tab:consensus-human} \end{subtable}% \hspace*{0.5em} \begin{subtable}{0.35\textwidth} \centering \scalebox{0.53}{ \setlength{\tabcolsep}{3pt} \begin{tabular}{@{}l*{4}{c}@{\hspace*{7pt}}c@{\hspace*{7pt}}*{2}{c}@{\hspace*{7pt}}*{2}{c}@{}} \toprule & \mc{4}{cider\(\uparrow\)} & {\sc meteor\(\uparrow\)} & \mc{2}{bert} & \mc{2}{FastText} \\ \cmidrule(lr){2-5} \cmidrule(lr){7-8}\cmidrule(lr){9-10} & n=1 & n=2 & n=3 & n=4 & & \(L_2\)\(\downarrow\)& CS\(\uparrow\) & \(L_2\)\(\downarrow\)& CS\(\uparrow\) \\ \midrule \(\Gamma_\Sigma\) & 0.4212 & 0.3429 & 0.2991 & 0.2583 & 1.0000 & 4.2891 & 0.9373 & 1.6518 & 0.7614 \\ \cmidrule{2-10} & 0.0789 & 0.0461 & 0.0313 & 0.0235 & 0.1864 & 7.1873 & 0.8673 & 3.0908 & 0.4782 \\ & 0.1109 & 0.0597 & 0.0409 & 0.0308 & 0.3710 & 6.2743 & 0.8924 & {\bf 2.8815} & 0.5334 \\ & 0.1580 & 0.0835 & 0.0568 & 0.0428 & {\bf 0.5269} & {\bf 5.7023} & {\bf 0.9097} & 3.1888 & 0.5196 \\ & {\bf 0.1614} & {\bf 0.0878} & {\bf 0.0605} & {\bf 0.0457} & 0.5138 & 5.7374 & 0.9087 & 3.0389 & 0.5347 \\ & 0.1209 & 0.0650 & 0.0445 & 0.0336 & 0.4033 & 6.1629 & 0.8956 & 2.9040 & {\bf 0.5353} \\ \bottomrule \end{tabular}} \label{tab:consensus-auto} \end{subtable} \vspace*{-1.5ex} \caption {% Overlap and embedding distance metrics computed for \(k=1\) generation against human-annotated reference sets \(H\) on the validation subset \(\mathcal{H}_v\) (left), and automatic reference sets \(\Sigma\) on the \emph{entire} validation set (right). % For \textsc{hrea-qih-g}, on average \(\sim\)6 answers are the empty string, which are excluded from the computation. % Metrics marked~\(\uparrow\) indicate higher values are better, and those marked~\(\downarrow\) indicate lower values are better. } \label{tab:consensus} \vspace*{1ex} \end{table*} We define a reference baseline for the overlap metrics, estimating upper bounds for the respective scores as \(\Gamma_H\), which cycles through answers in~\(H\), measures against~\(H\) itself and takes the maximum over the resulting scores. \vspace*{-1ex} \paragraph{Testing on whole dataset} The final step is to use the validated automatic reference sets (from~\cref{sec:obtaining-refs}) to evaluate the models under the revised scheme for the complete \textit{VisDial (v1.0)} dataset. \Cref{tab:consensus} (right) shows the overlap and embedding distance scores of answers generated by models, measured against the automatic reference sets~\(\Sigma\) for the whole validation set. Again, we test on the validation set since ground-truth answers are not publicly available for the test set---something we require to construct~\(\Sigma\). Note, the baseline~\(\Gamma_{\Sigma}\) here is different from before since the reference set is different: \(\Sigma\) instead of~\(H\). \vspace*{-1ex} \paragraph{Model comparison} Comparing models which do \emph{not} employ beam search (i.e.\ no asterix), \textsc{hciae-dis-g} performs the best across all metrics except \textsc{FastText}, which \textsc{rva} wins (\cref{tab:consensus}). This is consistent on \(\mathcal{H}_v\) \emph{and} the full validation set, despite \(\mathcal{H}_v\) being \(10\)-fold smaller---a further confirmation of \(\Sigma\)'s utility. Note, results across all metrics are well below the reference baselines~\(\Gamma_H\big/\Gamma_\Sigma\), indicating there is still room for improvement. Applying a beam-search on top of these models has the ability to further enrich the generations and improve performance on all metrics, as shown by \textsc{hrea-qih-g*}. It is expected that applying a beam search to the best-performer \textsc{hciae-dis-g} would yield similar improvements. Surprisingly, these results differ from the conclusions drawn from the rank-based evaluation (see~\cref{tab:full-cca-analysis} in supplement), where \textsc{rva} supersedes all other \gls{SOTA} models on \emph{all} rank metrics. This suggests that just because a model can rank a single-ground truth answer highest, does not necessarily make it the best \emph{generative} \gls{VD} agent. Our suite of overlap metrics and embedding distance metrics may help to explain \emph{why}. For example, \textsc{cider} n=1 is a proxy for how well a model performs on one-word answers, which are highly prevalent in the dataset (e.g.\ ``Yes''/``No''). \textsc{bert}, on the other hand, may help to measure generations with the closest semantic similarity to the reference sets. Indeed, this is the sort of flexibility of purpose that is required when evaluating complex multi-modal tasks like \gls{VD}. Beyond just \(k=1\) generation, a particularly useful feature of our revised scheme is that, unlike the rank-based evaluation, it can evaluate across any \(k\) number of generations sampled from the models (see~\cref{fig:ksample}). Answer correctness can therefore be measured, without penalising diversity, even if the generations fall outside the candidate set for the given question. This yields an interesting insight: for some models (notably the \textsc{hrea-qih-g} variants) performance degrades as \(k\) increases---a useful thing to know if deploying this model as a \gls{VD} agent in the real-world! Others, like \textsc{rva}, \textsc{hciae-g-dis} and \gls{CCA}\textsc{-aq-g}, generally remain constant or improve with higher \(k\). Surprisingly, \gls{CCA}\textsc{-aq-g}, despite its poorer absolute performance across the metrics at \(k=1\), holds its own and even improves with increasing \(k\). This allows us to compare models' generation capabilities and indeed robustness in the answering task---something not possible with the rank-based evaluation. \begin{figure}[h] \centering \includegraphics[width=0.45\textwidth]{images/ksample_hv_new.pdf}\\ \includegraphics[width=0.45\textwidth]{images/ksample_av_new.pdf} \vspace*{-0.8em} \caption{% Overlap and embedding distance metrics for \(k=1,5,10,15\) generations from \gls{SOTA} models on \(\mathcal{H}_v\) (top) and the full validation set (bottom). \gls{CCA}\textsc{-aq-g} and \textsc{rva} generally show improving trends with increasing \(k\), which isn't the case for \textsc{hrea-qih-g} variants. } \label{fig:ksample} \end{figure} \section{Discussion} \label{sec:discussion} In this paper, we propose a revised evaluation suite for \textit{VisDial} drawing on existing metrics from the \textsc{nlp} community that measures similarity between answers generated by a model and a given reference set of answers. We arrive at the need for alternate evaluations through the findings of~\citet{massiceti2018novd} and our own analysis of existing evaluation metrics on the \textit{VisDial} dataset, which we show can suffer from a number of issues to do with a mismatch between the \gls{VD} task and an evaluation for it that depends on ranking metrics. While a recent update to the evaluation paradigm of \textit{VisDial} incorporates both human judgements of answer validity and multiple plausible answers into a final score, issues relating to ranking persist, albeit to a lesser extent. Here, we advocate use of answers directly \emph{generated} by a model, in concert with consensus-based metrics measuring similarity against \emph{sets} of answers marked as valid by human annotators. It is practically infeasible to obtain these validity judgements at scale, however, thus restricting the extent to which the revised scheme can be applied. To address this issue, we develop a semi-supervised automated mechanism to extract sets of relevant answers from given candidate sets, using sparse human annotations and correlations through \gls{CCA}. We verify these sets by computing their intersection with those marked by humans, asking turkers via \gls{AMT}, and measuring their utility for the \gls{VD} task. Based on such experiments, we expand the \textit{VisDial} dataset with these reference set annotations and release this and the revised evaluation scheme as \textit{DenseVisDial}{} for future evaluation and model development. We intend this to be one possible improvement in the face of inherent constraints on the \textit{VisDial} dataset, and hope that the community adopts the revised evaluation going forwards. { \vspace*{0.5ex} \small \setstretch{1.2} \noindent \textbf{Acknowledgments} This work was supported by ERC grant ERC-2012-AdG 321162-HELIOS, EPSRC grant Seebibyte EP/M013774/1, EPSRC/MURI grant EP/N019474/1, FAIR \emph{ParlAI} grant, the Skye Foundation and the Toyota Research Institute. We thank Yulei Niu for his help with the \textsc{rva} code.\par}
{'timestamp': '2020-04-27T02:07:59', 'yymm': '2004', 'arxiv_id': '2004.09272', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09272'}
arxiv
\section{Introduction} This paper addresses the computational problem of computing averages of simple functions over combinatorial structures of a graph. Can we estimate elementary statistics of combinatorial structures in polynomial-time? This genre of problems is nicely illustrated for the example of independent sets. Given a graph $G=(V,E)$ can we efficiently estimate the average size of an independent set in~$G$? For graph $G=(V,E)$, let $\mathcal{I}_G$ denote the set of independent sets of $G$, and let $\mu_G$ denote the uniform distribution over $\mathcal{I}_G$. Denote the average independent set size by $\ensuremath{\mathcal{M}}(G)=\ensuremath{\mathbf{E}}_{\sigma\sim \mu}\big[|\sigma|\big]$. Schulman \emph{et al.}~\cite{SSS} (see also~\cite{SinclairSrivastava}) proved that exactly computing the average independent set size is \#P-hard for bounded-degree graphs. We investigate approximation algorithms for the problem. For a constant $C>1$ we say there is a $C$-approximation algorithm for the average independent set size if the algorithm outputs an estimate $\mathsf{EST}$ for which $\tfrac{1}{C}\times\ensuremath{\mathcal{M}}(G)/C\leq\mathsf{EST}\leq C\times \ensuremath{\mathcal{M}}(G)$. An $\mathsf{FPTAS}$ is an algorithm which, for any input $G=(V,E)$ and $\epsilon>0$, achieves an $(1+\epsilon)$-approximation factor in time $poly(|V|,1/\epsilon)$. Weitz~\cite{Weitz} presented an $\mathsf{FPTAS}$ for estimating $|\mathcal{I}_G|$, the number of independent sets, in graphs of maximum degree $\leq 5$, and this immediately yields an $\mathsf{FPTAS}$ for the average independent set size in graphs of maximum degree $\leq 5$, see also \cite{ALO20,PR,Peters} for new algorithmic approaches. We prove that this result is optimal. In fact, we prove that approximating the average independent set size in graphs of maximum degree $6$ is hard within a constant factor. \begin{theorem}\label{thm:mainind1} There is a constant $C>1$ such that, for all integers $\Delta\geq 6$, for graphs $G$ of maximum degree $\Delta$ there is no polynomial-time $C$-approximation algorithm for computing the average independent-set size of $G$, unless \emph{P=NP}. \end{theorem} This theorem is a special case of a more general result for the hard-core model, which is a statistical physics model of particular combinatorial interest. The hard-core model is defined on independent sets weighted by a parameter $\lambda>0$, known as the fugacity. An independent set $\sigma\in\mathcal{I}_G$ has weight $w(\sigma) = \lambda^{|\sigma|}$. For a graph $G$ and fugacity $\lambda>0$, the Gibbs distribution is defined as $\mu_{G;\lambda}(\sigma)=w(\sigma)/Z_{G;\lambda}$ where the partition function $Z_{G;\lambda} = \sum_{\tau\in\mathcal{I}_G} w(\tau)$. The earlier case of unweighted independent sets corresponds to the hard-core model with $\lambda=1$. Hence we use the same notation $\ensuremath{\mathcal{M}}(G)=\ensuremath{\mathbf{E}}_{\sigma\sim \mu}\big[|\sigma|\big]$ to denote the average independent set size in the Gibbs distribution. On the $\Delta$-regular tree, the hard-core model undergoes a phase transition at the critical point $\lambda_c(\Delta)=\tfrac{(\Delta-1)^{\Delta-1}}{(\Delta-2)^{\Delta}}$. When $\lambda\leq\lambda_c(\Delta)$ there is a unique infinite-volume Gibbs measure on the $\Delta$-regular tree (roughly, this corresponds to the decay of the ``influence'' of the leaves on the root), whereas when $\lambda>\lambda_c(\Delta)$ there is non-uniqueness, i.e., there are multiple infinite-volume Gibbs measures. There is an interesting computational phase transition for graphs of maximum degree $\Delta$ that occurs at this same tree threshold. For all constant $\Delta$, all $\lambda<\lambda_c(\Delta)$, all graphs of maximum degree $\Delta$, there is an $\mathsf{FPTAS}$ for the partition function~\cite{Weitz}. On the other side, for all $\Delta\geq 3$, all $\lambda>\lambda_c(\Delta)$, there is no $\mathsf{FPRAS}$ for approximating the partition function on graphs of maximum degree $\Delta$, unless NP$=$RP~\cite{Sly10,SlySun,GSVIsing}. We prove that computing the average independent set size also undergoes a computational phase transition at the tree critical point $\lambda_c(\Delta)$. As before, Weitz's algorithmic result~\cite{Weitz} yields, for all constant~$\Delta$, all~$\lambda<\lambda_c(\Delta)$, all graphs~$G$ of maximum degree~$\Delta$, an $\mathsf{FPTAS}$ for the average independent set size $\ensuremath{\mathcal{M}}(G)$. We prove that this result is optimal: when $\lambda>\lambda_c(\Delta)$ there is no $\mathsf{FPTAS}$ for the average independent set size. \begin{theorem}\label{thm:mainind2} Let $\Delta\geq 3$ be an integer and $\lambda>\lambda_c(\Delta)$. Then, for graphs $G$ of maximum degree $\Delta$, there is no $\mathsf{FPTAS}$ for computing the average independent-set size in the hard-core distribution $\mu_{G;\lambda}$, unless \emph{P=NP}. \end{theorem} In fact, our inapproximability result for general $\lambda>\lambda_c(\Delta)$ is stronger, it actually precludes approximation algorithms with factors of $1\pm \tfrac{\delta}{\log n}$, where $n$ is the number of the vertices of the input graph and $\delta$ is an appropriate constant, see Theorem~\ref{thm:maingen2} below for the precise statement. For a dense set of $\lambda$, we actually obtain constant-factor inapproximability (analogously to Theorem~\ref{thm:mainind1}). \begin{theorem}\label{thm:mainind3} Let $\Delta\geq 3$ be an integer. Then, for every real $\lambda>\lambda_c(\Delta)$ and $\epsilon>0$, there is an algebraic number $\widehat{\lambda}$ with $|\widehat{\lambda}-\lambda|\leq \epsilon$ and a constant $C=C(\widehat{\lambda},\Delta)>1$ such that, for graphs $G$ of maximum degree $\Delta$, there is no poly-time $C$-approximation algorithm for computing the average independent-set size of $G$ in the hard-core distribution $\mu_{G;\widehat{\lambda}}$, unless \emph{P=NP}. \end{theorem} \subsection{Results for the antiferromagnetic Ising model} Our results extend to the antiferromagnetic Ising model. Let $G=(V,E)$ be a graph. For $\beta,\lambda>0$, let $\mu_{G;\beta,\lambda}$ denote the Ising distribution on $G$ with edge activity $\beta$ and external field $\lambda$, i.e., for $\sigma:V\rightarrow \{0,1\}$ we have \[\mu_{G;\beta,\lambda}(\sigma)=\frac{\lambda^{|\sigma|}\beta^{m(\sigma)}}{Z_{G;\beta,\lambda}},\] where $m(\sigma)$ denotes the number of monochromatic edges in $G$ under $\sigma$, i.e., edges whose endpoints have the same spin. The model is called antiferromagnetic if $\beta\in(0,1)$ and ferromagnetic, otherwise. We define the average magnetization of $G$ to be the average number of vertices with spin 1, i.e., \[\ensuremath{\mathcal{M}}_{\beta,\lambda}(G)=\frac{1}{Z_{G;\beta,\lambda}}\sum_{\sigma:V\rightarrow \{0,1\}}|\sigma|\lambda^{|\sigma|}\beta^{m(\sigma)}=\ensuremath{\mathbf{E}}_{\sigma\sim \mu}\big[|\sigma|\big],\] where for a configuration $\sigma:V\rightarrow \{0,1\}$, we use $|\sigma|$ to denote $\sum_{v\in V(G)} \sigma(v)$, i.e., the total number of vertices with spin $1$. In the ferromagnetic case, there is an $\mathsf{FPRAS}$ for approximating the magnetization for all $\beta>1$ and $\lambda>0$, due to the algorithm of Jerrum and Sinclair \cite{JS:ising}. For $\Delta\geq 3$, let $\beta_c(\Delta)=\tfrac{\Delta-2}{\Delta}$. It is known that the antiferromagnetic Ising model with edge activity $\beta$ and external field $\lambda$ has non-uniqueness on the infinite $\Delta$-regular tree iff $\beta\in (0,\beta_c)$ and $\lambda \in (1/\lambda^{\mathsf{Ising}}_c,\lambda^{\mathsf{Ising}}_c)$ for some explicit $\lambda^{\mathsf{Ising}}_c=\lambda^{\mathsf{Ising}}(\beta,\Delta)>1$. For all constant $\Delta$, in the tree uniqueness region there is an $\mathsf{FPTAS}$ for the partition function for graphs of maximum degree~$\Delta$~\cite{SST,LLY}, and, once again, this implies an $\mathsf{FPTAS}$ for the magnetization. In the tree non-uniqueness region, for all $\Delta\geq 3$, unless NP$=$RP there is no $\mathsf{FPRAS}$ for the partition function for graphs of maximum degree~$\Delta$~\cite{SlySun}. We prove that approximating the magnetization is also intractable in the tree non-uniqueness region. \begin{theorem}\label{thm:mainIs2} Let $\Delta\geq 3$ be an integer, $\beta\in (0,\beta_c(\Delta))$ and $\lambda\in (\tfrac{1}{\lambda_c},\lambda_c)$ with $\lambda\neq 1$, where $\lambda_c=\lambda^{\mathsf{Ising}}_c(\Delta,\beta)$. Then, for graphs $G$ of maximum degree $\Delta$, there is no $\mathsf{FPTAS}$ for computing the average magnetization in the Ising distribution $\mu_{G;\beta, \lambda}$, unless \emph{P=NP}. \end{theorem} As in Theorem~\ref{thm:mainind2}, the inapproximability factor in Theorem~\ref{thm:mainIs2} is in fact stronger, see Theorem~\ref{thm:maingen2} below for the precise statement. For a dense set of $\lambda$, we again obtain constant-factor inapproximability. \begin{theorem}\label{thm:mainIs3} Let $\Delta\geq 3$ be an integer, rational $\beta\in (0,\beta_c(\Delta))$ and $\lambda_c=\lambda^{\mathsf{Ising}}_c(\Delta,\beta)$. Then, for every $\lambda\in (\tfrac{1}{\lambda_c},\lambda_c)$ and $\epsilon>0$, there is an algebraic number $\widehat{\lambda}$ with $|\widehat{\lambda}-\lambda|\leq \epsilon$ and a constant $C=C(\beta,\widehat{\lambda},\Delta)>1$ such that, for graphs $G$ of maximum degree $\Delta$, there is no poly-time $C$-approximation algorithm for computing the average magnetization $\ensuremath{\mathcal{M}}_{\beta,\hat{\lambda}}(G)$, unless \emph{P=NP}. \end{theorem} \subsection{Results for general antiferromagnetic 2-spin systems} While the hard-core model and the Ising model are the most canonical 2-spin models, the results of the previous two sections will be obtained as special cases of the following results for general antiferromagnetic 2-spin systems. This more general perspective will also allow us to give a unified proof of Theorems~\ref{thm:mainind2},~\ref{thm:mainind3},~\ref{thm:mainIs2},~\ref{thm:mainIs3}. Let $G=(V,E)$ be a graph. For $\beta,\gamma,\lambda>0$, let $\mu_{G;\beta,\gamma,\lambda}$ denote the Gibbs distribution on $G$ with edge activities $\beta,\gamma$ and external field $\lambda$, i.e., for $\sigma:V\rightarrow \{0,1\}$ we have \[\mu_{G;\beta,\lambda}(\sigma)=\frac{\lambda^{|\sigma|}\beta^{m_{0}(\sigma)}\gamma^{m_{1}(\sigma)}}{Z_{G;\beta,\gamma,\lambda}},\] where $m_{0}(\sigma), m_{1}(\sigma)$ denotes the number of edges in $G$ whose endpoints are assigned under $\sigma$ the pair of spins $(0,0)$ and $(1,1)$, respectively. The parameter pair $(\beta,\gamma)$ is called \emph{antiferromagnetic} if $\beta\gamma\in[0,1)$ and at least one of $\beta,\gamma$ is non-zero, and it is called ferromagnetic, otherwise. Note that the hard-core model is the case $\beta=1,\gamma=0$ (under the convention that $0^0\equiv 1$) whereas the antiferromagnetic Ising model is the case $0<\beta=\gamma<1$. We next define the range of parameters $(\beta,\gamma,\lambda)$ where our inapproximability results for the magnetization apply; these are precisely the parameters where the spin system exhibits non-uniqueness on the infinite $\Delta$-regular tree, apart from the case of the antiferromagnetic Ising model with $\lambda=1$, where as noted below the magnetization can be computed trivially for all graphs $G$ (namely, it equals $\tfrac{1}{2}|V(G)|$). \begin{definition}\label{def:nonuniq} Let $\Delta\geq 3$ be an integer. We let $\ensuremath{\mathcal{U}}_{\Delta}$ be the set of $(\beta,\gamma,\lambda)$ such that $(\beta,\gamma)$ is antiferromagnetic, and the (unique) fixpoint $x^*>0$ of the function $f(x)=\lambda \big(\frac{ \beta x+1}{x+\gamma}\big)^{\Delta-1}$ satisfies $|f'(x^*)|>1$. We let $\ensuremath{\mathcal{U}}_{\Delta}^{*}=\ensuremath{\mathcal{U}}_{\Delta}\backslash \bigcup_{\beta\in (0,1)}\{(\beta,\beta,1)\}$ be the set of parameters in $\ensuremath{\mathcal{U}}_\Delta$ other than those where computing the magnetization is trivial. \end{definition} We note that Li, Lu, Yin \cite{LLY} define a notion of ``up-to-$\Delta$'' uniqueness which requires $(\beta,\gamma,\lambda)$ to be in uniqueness for every $d\leq \Delta$; they obtain an $\mathsf{FPTAS}$ for the partition function in that region. The complement of their region corresponds to non-uniqueness in the sense of Definition~\ref{def:nonuniq} for some $d\leq \Delta$. Our inapproximability results extend to this bigger region by applying our theorems for smaller values of $\Delta$. Our first inapproximability result for general antiferromagnetic 2-spin models, which is a generalization/strengthening of Theorems~\ref{thm:mainind2} and~\ref{thm:mainIs2}, is the following. The proof is given in Section~\ref{sec:maingen2}. \begin{theorem}\label{thm:maingen2} Let $\Delta\geq 3$ be an integer and $(\beta,\gamma,\lambda)\in \ensuremath{\mathcal{U}}_{\Delta}^*$. Then, for graphs $G\in \mathtt{G}_\Delta$, there is no $\mathsf{FPTAS}$ for computing the average magnetization in the Gibbs distribution $\mu_{G;\beta, \gamma, \lambda}$, unless P=NP. In fact, there is a constant $\kappa=\kappa(\Delta, \beta,\gamma, \lambda)>0$ such that there is no poly-time $\big(1+ \tfrac{\kappa}{\log n}\big)$-approximation algorithm for computing the average magnetization $\ensuremath{\mathcal{M}}_{\beta,\gamma,\lambda}(G)$, where $n=|V(G)|$. \end{theorem} We remark that a ``no-FPTAS'' result can be strengthened to an inapproximability factor of $\big(1\pm \tfrac{1}{n^{\epsilon}}\big)$ for any constant $\epsilon>0$ via standard powering techniques; the tighter hardness factor of $\big(1\pm \tfrac{\kappa}{\log n}\big)$ in Theorem~\ref{thm:maingen2} requires a substantially more delicate argument. \begin{theorem}\label{thm:maingen3} Let $\Delta\geq 3$ be an integer and $(\beta,\gamma,\lambda)\in \ensuremath{\mathcal{U}}_{\Delta}$ with $\beta,\gamma$ rational numbers. Then, for every $\epsilon>0$, there is an algebraic number $\widehat{\lambda}$ with $|\widehat{\lambda}-\lambda|\leq \epsilon$ and a constant $C=C(\beta,\gamma,\widehat{\lambda},\Delta)>1$ such that, for graphs $G$ of maximum degree $\Delta$, there is no poly-time $C$-approximation algorithm for computing the average magnetization $\ensuremath{\mathcal{M}}_{\beta,\gamma,\hat{\lambda}}(G)$, unless \emph{P=NP}. \end{theorem} \section{Proof Outline} In this section, we give some of the key elements of the techniques needed to prove our inapproximability results and conclude with the proof of Theorem~\ref{thm:mainind1}. We start by describing ``field gadgets'' and state the main lemmas that we will use in our reduction. \subsection{Gadgets with approximately equal effective fields and different averages}\label{sec:f434} For a graph $G$ and $\sigma:V\rightarrow \{0,1\}$, we say that a vertex $v\in V$ is occupied if $\sigma(v)=1$, and unoccupied otherwise.\footnote{This terminology is standard for the hard-core model, but it will be convenient to use it for general 2-spin systems.} For a subset $S\cup U$, we use $\sigma_S$ to denote the configuration on $S$ which is restriction of $\sigma$ on $S$. \begin{definition}\label{def:field} A {\em field gadget} is a rooted tree $\mathcal{T}$ whose root $\rho$ has degree one. For antiferromagnetic $(\beta,\gamma)$ and $\lambda>0$, let $\mu=\mu_{\mathcal{T};\beta,\gamma,\lambda}$. \begin{enumerate} \item The {\em effective field} of the gadget, denoted by $R_{\mathcal{T}}(\lambda)$, is $1/\lambda$ times the ratio of the weight of configurations where the root is occupied to the weight of configurations where the root is unoccupied, i.e., $R_{\mathcal{T}}(\lambda)=\tfrac{1}{\lambda}\frac{\mu(\sigma_\rho=1)}{\mu(\sigma_\rho=0)}$. \item The {\em magnetization gap} of the gadget, denoted by $M_{\mathcal{T};\beta,\gamma,\lambda}$, is the expected number of occupied vertices conditioned on the root being occupied minus the expected number of occupied vertices conditioned on the root being unoccupied (the root is included in the count), i.e., \[M_{\mathcal{T};\beta,\gamma,\lambda}=\ensuremath{\mathbf{E}}_{\sigma\sim \mu}[\,|\sigma|\mid \sigma(\rho)=1]-\ensuremath{\mathbf{E}}_{\sigma\sim\mu}[\,|\sigma|\mid \sigma(\rho)=0].\] \end{enumerate} In the special case that $\lambda=\frac{1-\beta}{1-\gamma}$ with $\beta\neq \gamma$, a field gadget consists of a rooted tree, where in addition we attach a triangle on a subset of the leaves. \end{definition} Note that, in the case that $\lambda=\frac{1-\beta}{1-\gamma}$, the effective field of any tree gadget can be shown to be equal to 1 and the magnetization gap to 0, so that is why we need to consider the ``mildly non-tree'' construction in Definition~\ref{def:field}. It will be useful to illustrate Definition~\ref{def:field} with a few examples. \begin{example}\label{eee} For example the rooted tree with one edge has effective field $R=\frac{1+\gamma\lambda}{\beta+\lambda}$. The degenerate example where the root has degree zero has effective field $R=1$. \end{example} The following more interesting example in the case of independent sets will be used to prove Theorem~\ref{thm:mainind1}; it gives a pair of field gadgets with the same effective field but different magnetization gaps. \begin{example}\label{e4f334} Consider the independent set model (with $\lambda=1$). Consider the trees $\mathcal{T}_1,\mathcal{T}_2$ with roots $\rho_1,\rho_2$ below. \begin{center} \begin{minipage}{0.3\textwidth} \scalebox{0.9}[0.9]{ \begin{tikzpicture}[ level distance=1cm, sibling distance=2.5cm, rtn/.style = {shape=circle, draw=black, fill=white, align=center, thick, minimum size=0.2cm}, edge from parent/.style={draw,thick,-}] \node[rtn,label=left:$\rho_1$] {} child [missing] child { node[rtn] {} { child [ missing ] child { node[rtn] {} } } }; \end{tikzpicture}} \end{minipage} \begin{minipage}{0.5\textwidth} \scalebox{0.9}[0.9]{ \begin{tikzpicture}[ level distance=0.6cm, sibling distance=2.5cm, rtn/.style = {shape=circle, draw=black, fill=white, align=center, thick, minimum size=0.2cm}, edge from parent/.style={draw,thick,-}] \node[rtn, label=left:$\rho_2$] {} child [missing] child { node[rtn] {} { child { node[rtn] {} { child { node[rtn] {} } child [ missing ] } } child { node[rtn] {} { child { node[rtn] {} } child { node[rtn] {} { child [ missing ] child { node[rtn] {} } } } } } } }; \end{tikzpicture}} \end{minipage} \end{center} Then $R_{\mathcal{T}_1}=R_{\mathcal{T}_2}$ since $R_{\mathcal{T}_1}=\frac{2}{3}$ and $R_{\mathcal{T}_2}=\tfrac{24}{36}$, but $M_{\mathcal{T}_1}\neq M_{\mathcal{T}_2}$ since $M_{\mathcal{T}_1}=\tfrac{3}{2}-\tfrac{2}{3}=\tfrac{5}{6}$ and $M_{\mathcal{T}_2}=\tfrac{35}{12}-\tfrac{13}{6}=\tfrac{3}{4}$. These values can be either verified by enumeration and linearity of expectation, or else using the recursions of the upcoming Lemma~\ref{lem1}. \end{example} We will be interested in finding pairs of field gadgets analogous to Example~\ref{e4f334}. Our interest in such pairs of field gadgets is justified by the following lemma. \begin{theorem}\label{thm:vanilla} Let $\Delta\geq 3$ be an integer and $(\beta,\gamma,\lambda)\in \ensuremath{\mathcal{U}}_{\Delta}^*$. Suppose that there exists a pair of field gadgets $\mathcal{T}_1, \mathcal{T}_2$ with maximum degree $\Delta$ such that $R_{\mathcal{T}_1}=R_{\mathcal{T}_2}$ but $M_{\mathcal{T}_1}\neq M_{\mathcal{T}_2}$. Then, there is constant $c=c(\Delta,\beta,\gamma,\lambda)>1$ such that, for graphs $G$ of maximum degree $\Delta$, there is no poly-time $c$-approximation algorithm for computing the average magnetization $\ensuremath{\mathcal{M}}_{\beta,\gamma,\lambda}(G)$, unless \emph{P=NP}. \end{theorem} When can we find pairs of trees as in Example~\ref{e4f334} with the same effective fields but different magnetization gaps? Even in the case of the hard-core model, a pair of trees either have the same effective field for only finitely many values of $\lambda$ or else have the same magnetization gap for all $\lambda$. Thus we cannot hope for a universal pair of gadgets. Actually, the set of $\lambda$ where the effective fields can be equal, over all pairs of trees, must be algebraic, hence measure zero. Our main theorem for the construction of field gadgets is the following. The theorem roughly asserts that we can construct field gadgets with arbitrarily close effective fields but substantially different magnetization gaps. For a rational $r=p/q$ with integers $p,q$ satisfying $\gcd(p,q)=1$, we let $\mathrm{bits}(r)$ denote the total number of bits needed to represent $p,q$. \begin{theorem}\label{thm:const1} Let $(\beta,\gamma,\lambda)$ be antiferromagnetic with $(\beta,\gamma,\lambda)\neq (\beta,\beta,1)$. There exist $\hat{R},\hat{M}, \Xi>0$ and an algorithm which on input an arbitrarily small rational $r\in (0,1/2)$ outputs in time $poly(\mathrm{bits}(r))$ a pair of field gadgets $\mathcal{T}_1,\mathcal{T}_2$, each of maximum degree 3 and size $O(|\log r|)$, such that \[|R_{\mathcal{T}_1} -\hat{R}|, |R_{\mathcal{T}_2}- \hat{R}|\leq r,\mbox{ but } |M_{\mathcal{T}_1}-M_{\mathcal{T}_2}|>\hat{M}.\] Moreover, the magnetization gaps $M_{\mathcal{T}_1}, M_{\mathcal{T}_2}$ are bounded in absolute value by the constant $\Xi$. \end{theorem} The proof of Theorem~\ref{thm:const1} is given in Section~\ref{sec:gadget}. In fact, we can bootstrap Theorem~\ref{thm:const1} to obtain pairs of trees with the same effective fields but different magnetization gaps for a dense set of (algebraic numbers) $\lambda$, and this gives a constant factor inapproximability result for the magnetization by applying Theorem~\ref{thm:vanilla}. \begin{theorem}\label{thm:const2} Let $(\beta,\gamma)$ be antiferromagnetic. There exists a set $S$ of algebraic numbers $\lambda$, dense in the interval $(0,\infty)$, such that for each $\lambda\in S$ the following holds. There is a pair of field gadgets $\mathcal{T}_1,\mathcal{T}_2$, each of maximum degree 3, such that $R_{\mathcal{T}_1}= R_{\mathcal{T}_2}$ but $M_1\neq M_2$. \end{theorem} In the following, we sketch the proof of Theorem~\ref{thm:vanilla} and in Section~\ref{sec:gadget} we will give a detailed outline of the proof of Theorems~\ref{thm:const1} and~\ref{thm:const2}. \subsection{The reduction: using field gadgets to obtain inapproximability} Fix $\Delta\geq 3$ and $\beta,\gamma,\lambda\in \ensuremath{\mathcal{U}}_{\Delta}$. Our results will be based on showing that approximating $\textsc{Max-Cut}$ on 3-regular graphs $H$ reduces to approximating the magnetization will be via a reduction from $\textsc{Max-Cut}$. The reduction uses two types of gadgets. The first type of gadget is a bipartite graph $G$ which is an almost $\Delta$-regular graph with $n$ vertices on its side and $\ell$ ``ports'' on each side of degree $\Delta-1$, which will be used to connect distinct copies of gadgets. These gadgets were used in previous inapproximability results for the partition function and analysing them was one of the key difficulties in those results. The main idea in these results is to replace each vertex of $H$ by a distinct copy of $G$ and make appropriate connections between ports to encode the edges of $H$; then due to the antiferromagnetic interaction the resulting graph settles in configurations which correspond to Max-Cut configurations of $H$ (the Max-Cut assignment can roughly be read off by looking at the ``phases'' of the gadgets $G$, i.e., which side has the most occupied vertices, see Section~\ref{sec:phase-gadget} for details). However, for our inapproximability results we would need to analyze the magnetization of such gadgets by taking into account the effect of conditioning the spins of the ports; this task seems even more challenging than in the previous settings since it seems to require very refined estimates. The field gadgets, which is the second type of gadgets, give a new reduction technique to bypass the need to perform this delicate, and likely difficult, task. In particular, by using a pair of field gadgets with the same effective fields and different magnetization gaps we will be able to observe the value of $\textsc{Max-Cut}(H)$ by taking the difference of the magnetizations when we append our field gadgets appropriately; crucially, the fact that the effective fields are the same implies that the underlying distribution does not change but that the difference of the magnetization gap of the two gadgets manifests itself in the magnetization. \subsection{The bipartite ``phase-gadget'' of Sly and Sun}\label{sec:phase-gadget} Fix an integer $\Delta\geq 3$. Let $\mathcal{G}^{\ell}_{n}$ be the set of $(2n)$-vertex bipartite graphs whose two sides are labelled with $\textup{\texttt{+}},\textup{\texttt{-}}$ and are obtained from a $\Delta$-regular $(2n)$-vertex bipartite graph by deleting a matching of size $\ell$. For a graph $G\in\mathcal{G}^{\ell}_{n}$, we denote its bipartition by $(U^\textup{\texttt{+}},U^\textup{\texttt{-}})$ where $U^\textup{\texttt{+}},U^\textup{\texttt{-}}$ are vertex sets with $|U^\textup{\texttt{+}}|=|U^\textup{\texttt{-}}|=n$, and we denote by $W^\textup{\texttt{+}},W^\textup{\texttt{-}}$ the sets of vertices with degree $\Delta-1$ on each side of the bipartition, i.e., the vertices incident to the edges of the matching, so that $|W^\textup{\texttt{+}}|=|W^\textup{\texttt{-}}|=\ell$. We will refer to set $W=W^+\cup W^-$ as the \textit{ports} of $G$. For $\sigma: U^\textup{\texttt{+}}\cup U^\textup{\texttt{-}}\rightarrow \{0,1\}$, we define the \emph{phase} $\mathcal{Y}(\sigma)$ of the configuration $\sigma$ as the side which has the most occupied vertices under $\sigma$, i.e., \[\mathcal{Y}(\sigma)=\begin{cases} \textup{\texttt{+}} & \mbox{ if } |\sigma_{U^\textup{\texttt{+}}}|\geq |\sigma_{U^\textup{\texttt{-}}}|,\\ \textup{\texttt{-}}& \mbox{otherwise}. \end{cases}\] Sly and Sun \cite{Sly10} (see also \cite{GSV:colorings}) establish that, whenever $\beta,\gamma,\lambda\in \ensuremath{\mathcal{U}}_{\Delta}$, for arbitrary $\epsilon>0$ and integer $\ell\geq 1$, there exist $n$ and $G\in \mathcal{G}^{\ell}_{n}$ such that, in the Gibbs distribution of the gadget graph $G$, each phase appears with probability close to 1/2$\pm \epsilon$, and that the spins of the ports of $G$, conditional on the phase, are roughly independent, with occupation probabilities that are asymmetric between the two sides. The detailed properties of the gadget can be found in Lemma~\ref{lem:SlySun} of Section~\ref{sec:SlySun}, though the exact details will not be important at this stage. \subsection{The reduction} Let $H$ be a 3-regular instance of the \textsc{Max-Cut} problem. Let $k$ be an arbitrary positive integer, and let $n$ and $G\in \mathcal{G}^{3k}_n$ be a bipartite gadget satisfying Lemma~\ref{lem:SlySun}. Let also $\mathcal{T}$ be a field gadget with effective field $R$ and magnetization gap $M$. Let $\widehat{H}^{k}_G$ be the graph with $m$ disconnected components obtained by replacing each vertex of $H$ with a distinct copy of $G$; for $v\in V_H$ we denote by $G_v$ the copy of $G$ in $\widehat{H}_G$ corresponding to the vertex $v$, and by $U^{\textup{\texttt{\textpm}}}_v, W^{\textup{\texttt{\textpm}}}_v$ the vertex sets and ports of $G_v$ in each side of the bipartition. Finally, we let $U_v=U^\textup{\texttt{+}}_v\cup U^\textup{\texttt{-}}_v$ and $W_v=W^\textup{\texttt{+}}_v\cup W^\textup{\texttt{-}}_v$. Let $H^{k}_{G,\mathcal{T}}$ be the graph obtained from $\widehat{H}^k_G$ as follows. For each edge $e=(u,v)\in E_H$, pick $k$ distinct ports from $W^{\textup{\texttt{\textpm}}}_u, W^{\textup{\texttt{\textpm}}}_v$ and connect them using a path with three edges, for a total of $2k$ edge-disjoint paths between the gadgets $G_u$ and $G_v$: $k$ paths between $\textup{\texttt{+}}/\textup{\texttt{+}}$ sides and $k$ paths between $\textup{\texttt{-}}/\textup{\texttt{-}}$ sides. Then, for each path $P$ append two distinct copies of the field gadget $\mathcal{T}$ by identifying the roots of the copies of $\mathcal{T}$, say $\rho_1,\rho_2$, with the internal vertices of $P$, say $t_1,t_2$. For a configuration $\sigma: V(H^{k}_{G,\mathcal{T}})\rightarrow \{0,1\}$, we let $\widehat{\mathcal{Y}}(\sigma): V(H)\rightarrow \{\textup{\texttt{+}},\textup{\texttt{-}}\}$ be the phases over the gadgets $G_v$ with $v\in V(H)$, i.e., $\widehat{\mathcal{Y}}(\sigma)=\big\{\mathcal{Y}(\sigma_{U_v})\big\}_{v\in V(H)}$. We define $\widehat{\mathcal{Y}}(\cdot)$ similarly for configurations on $\widehat{H}^k_G$, $H^k_G$. For a phase assignment $Y:V(H)\rightarrow \{\textup{\texttt{+}},\textup{\texttt{-}}\}$, we let $\mathrm{Cut}_H(Y)=\{(u,v)\in E(H)\mid Y_u\neq Y_v\}$ be the set of edges that are cut in $H$ by viewing the phase assignment $Y$ as a bipartition of $V(H)$ in the natural way. For $\mu=\mu_{H^{k}_{G,\mathcal{T}};\beta,\gamma,\lambda}$, let \[\textsc{Avg-Cut}_{\mu}(H):=\sum_{Y:V(H)\rightarrow \{\textup{\texttt{+}},\textup{\texttt{-}}\}}\mu\big(\widehat{\mathcal{Y}}(\sigma)=Y\big)|\mathrm{Cut}_H(Y)|\] be the size of the average cut in $H$ when phase assignments are weighted by $\mu$. The following lemma associates the magnetization on the graph $H^{k}_{G,\mathcal{T}}$ with the quantity $\textsc{Avg-Cut}_{\mu}(H)$ and, in turn, with $\textsc{Max-Cut}(H)$. The main idea is that the paths of length 3 between the ports cause antiferromagnetic interaction and the spin system on $H^{k}_{G,\mathcal{T}}$ prefers phase configurations $Y$ that have large $|\mathrm{Cut}_H(Y)|$ value. By choosing $k$ large enough we can further ensure that $\textsc{Avg-Cut}_{\mu}(H)$ arbitrarily close to $\textsc{Max-Cut}(H)$. \begin{lemma}\label{lem:maingadget} Let $\Delta\geq 3$ and $(\beta,\gamma,\lambda)\in \ensuremath{\mathcal{U}}_\Delta$. There are rational functions $A(R), B(R),C(R)$ defined for all $R\geq 0$, satisfying \begin{equation}\label{eq:vv6gvgg} \mbox{(i) $A(0)=1$, (ii) $A(R)>1$ for $R>0$, and (iii) $B(R)-C(R)=(\log A(R))'$ for $R>0$} \end{equation} so that the following holds for any field gadget $\mathcal{T}$ effective field $R>0$ and magnetization gap $M$. Let $A,B,C$ be the values of the functions at $\lambda R$ and define $\mathcal{A}':=\ensuremath{\mathbf{E}}_{\tau\sim \mu_{\mathcal{T};\beta,\gamma,\lambda}}[\,|\tau|\mid \tau(\rho)=0]$, where $\rho$ is the root of $\mathcal{T}$. Let $\epsilon\in (0,1/10)$, $k\geq 10/\log A$ be an integer, and $n$ and $G\in \mathcal{G}^{3k}_n$ satisfy Lemma~\ref{lem:SlySun} with $\ell=3k$ and the given $\epsilon$. Then, for every 3-regular graph $H$ with sufficiently large $|V(H)|$, for $\mu=\mu_{H^{k}_{G,\mathcal{T}};\beta,\gamma,\lambda}$, we have that the average magnetization of the graph $H^{k}_{G,\mathcal{T}}$ satisfies \begin{align*} \ensuremath{\mathcal{M}}_{\beta,\gamma,\lambda}(H^{k}_{G,\mathcal{T}})&=4k\mathcal{A}'|E(H)|+\ensuremath{\mathbf{E}}_{\sigma\sim \mu}\big[\big|\sigma_{V(\widehat{H}^{k}_{G})}\big|\big]+(1\pm 8\epsilon)kMQ \end{align*} with $Q:=(B-C)\textsc{Avg-Cut}_{\mu}(H)+C |E(H)|$, while $\textsc{Avg-Cut}_{\mu}(H)$ satisfies \[1/K\leq \frac{\textsc{Avg-Cut}_{\mu}(H)}{\textsc{Max-Cut}(H)}\leq 1 \mbox{\ \ for\ \ } K:=1+\frac{6}{k\log A}.\] \end{lemma} We defer the detailed proof of Lemma~\ref{lem:maingadget} to Section~\ref{sec:maingadget}. Note that the expression for the magnetization of $H^{k}_{G,\mathcal{T}}$ accounts for the contributions of the phase gadgets $G$ only implicitly. This is by design; when we append our pair of field gadgets $\mathcal{T}_1,\mathcal{T}_2$ which have the same effective fields, vertices in $V(\widehat{H}^{k}_{G})$ will have the same marginal distribution in both $\mu_{H^{k}_{G,\mathcal{T}_1}}$ and $\mu_{H^{k}_{G,\mathcal{T}_2}}$; on the other hand the magnetization gaps of $\mathcal{T}_1,\mathcal{T}_2$ are different. Therefore, when we take the difference of the magnetizations in $H^{k}_{G,\mathcal{T}_1}$ and $H^{k}_{G,\mathcal{T}_2}$, the contributions of the phase gadgets $G$ cancel and, in the left-over quantity, the major contribution comes from the value of $\textsc{Avg-Cut}_{\mu}(H)$. We are almost ready to prove Theorem~\ref{thm:vanilla}. Recall, the assumption therein is that we have a pair of field gadgets with the same effective fields and different magnetization gaps. We will need to bootstrap this slightly to obtain additional pairs of field gadgets, as stated in the following lemma. \begin{lemma}\label{lem:vanilla} Let $\Delta\geq 3$ be an integer and $(\beta,\gamma,\lambda)$ be antiferromagnetic with $(\beta,\gamma,\lambda)\neq (\beta,\beta,1)$. Suppose that there exists a pair of field gadgets $\mathcal{T}_1, \mathcal{T}_2$ with maximum degree $\Delta$ such that $R_{\mathcal{T}_1}=R_{\mathcal{T}_2}$ but $M_{\mathcal{T}_1}\neq M_{\mathcal{T}_2}$. Then, we can construct for $j=0,1,2,\hdots$ an infinite sequence of pairs of field gadgets $\mathcal{T}_{1,j},\mathcal{T}_{2,j}$ of maximum degree $\Delta$ with effective fields $R_{1,j}, R_{2,j}$ and magnetization gaps $M_{1,j},M_{2,j}$ such that $R_{1,j}=R_{2,j}$ but $M_{1,j}\neq M_{2,j}$; moreover the values of $R_{1,j}$, and hence of $R_{2,j}$ as well, are pairwise distinct. \end{lemma} The proof of Lemma~\ref{lem:vanilla} is given in Section~\ref{sec:vanilla}. With Lemmas~\ref{lem:vanilla} and~\ref{lem:SlySun} at hand, we can now give the proof of Theorem~\ref{thm:vanilla}. \begin{proof}[Proof of Theorem~\ref{thm:vanilla}] For $i\in\{1,2\}$, let $R_i:=R_{\mathcal{T}_i}$ be the effective field of $\mathcal{T}_i$ and $M_i:=M_{\mathcal{T}_i}$ be the magnetization gap of $\mathcal{T}_i$, so that $R_1=R_2$ but $M_1\neq M_2$. Let $A(R),B(R), C(R)$ be the functions in Lemma~\ref{lem:maingadget} and set $D(R)=B(R)-C(R)$. For convenience, we let $A,B,C,D$ denote the common values of $A(R_i),B(R_i),C(R_i),D(R_i)$, respectively, for $i\in \{0,1\}$. We will need to ensure in our argument that $D\neq 0$. The first observation is that \eqref{eq:vv6gvgg} implies that for all but finitely many values of $R$ we have that $D(R)\neq 0$.\footnote{\label{ft:4f343}If $B(R)$ and $C(R)$ agree on infinitely many values of $R$, then since both of them are rational functions of $R$, it must be the case that $B(R)=C(R)$ for all $R\geq 0$. Since for all $R\geq 0$, we have that $(\log A(R))'=B(R)-C(R)$, this would give that $A(R)$ is the constant function; contradiction, since \eqref{eq:vv6gvgg} asserts that $A(0)=1$ and $A(R)>1$ for all $R>0$.} The second observation is that, from Lemma~\ref{lem:vanilla}, using $\mathcal{T}_1,\mathcal{T}_2$ we can construct for $j=0,1,2,\hdots$ an infinite sequence of pairs of field gadgets $\mathcal{T}_{1,j},\mathcal{T}_{2,j}$ of maximum degree $\Delta$ with effective fields $R_{1,j}, R_{2,j}$ and magnetization gaps $M_{1,j},M_{2,j}$ such that $R_{1,j}=R_{2,j}$ but $M_{1,j}\neq M_{2,j}$; moreover the values of $R_{1,j}$ are pairwise distinct. From these two observations, it follows that we can assume without loss of generality that $D\neq 0$. Suppose for the sake of contradiction that, for arbitrarily small $\kappa>0$, there is a polynomial-time algorithm that, on input a graph $G$ of maximum degree $\Delta$, produces an $(1+\kappa)$-approximation of the magnetization $\ensuremath{\mathcal{M}}_{G;\beta,\gamma,\lambda}$. We will show that we can approximate $\textsc{Max-Cut}$ on 3-regular graphs within a constant factor arbitrarily close to 1, contradicting the inapproximability result of \cite{maxcut}. For $i\in \{0,1\}$, consider the graph $H^{k}_{G,\mathcal{T}_i}$ for some large integer $k>1+10/\log A$ and small $\epsilon>0$ to be specified later. Let $\mu_i$ denote the Gibbs distribution on $H^{k}_{G,\mathcal{T}_i}$ with parameters $\beta,\gamma,\lambda$. By Lemma~\ref{lem:maingadget}, the average magnetization of the graph $H^{k}_{G,\mathcal{T}_i}$ satisfies \begin{equation}\label{eq:magsia} \begin{aligned} \ensuremath{\mathcal{M}}_{\beta,\gamma,\lambda}(H^{k}_{G,\mathcal{T}_i})&=4k\mathcal{A}_i'|E(H)|+\ensuremath{\mathbf{E}}_{\sigma\sim \mu_i}\Big[\big|\sigma_{V(\widehat{H}^{k}_{G})}\big|\Big]+(1\pm 8\epsilon)kM_{i} Q_i. \end{aligned} \end{equation} where $Q_i=D\, \textsc{Avg-Cut}_{\mu_i}(H)+C |E(H)|$ and $\textsc{Avg-Cut}_{\mu_i}(H)$ satisfies \begin{equation}\label{eq:avgcutia} 1/K\leq \displaystyle \frac{\textsc{Avg-Cut}_{\mu_i}(H)}{\textsc{Max-Cut}(H)}\leq 1\mbox{ for }K_i:=1+\displaystyle\frac{6}{k\log A}. \end{equation} Note that since $R_1=R_2$ we have that \begin{equation}\label{eq:t5g4rv55} \ensuremath{\mathbf{E}}_{\sigma\sim \mu_0}\Big[\big|\sigma_{V(\widehat{H}^{k}_{G})}\big|\Big]=\ensuremath{\mathbf{E}}_{\sigma\sim \mu_1}\Big[\big|\sigma_{V(\widehat{H}^{k}_{G})}\big|\Big], \quad \mbox{ and } \textsc{Avg-Cut}_{\mu_1}(H)=\textsc{Avg-Cut}_{\mu_2}(H). \end{equation} Let $\ensuremath{\mathcal{D}}:=\ensuremath{\mathcal{M}}_{\beta,\gamma,\lambda}(H^{k}_{G,\mathcal{T}_1})- \ensuremath{\mathcal{M}}_{\beta,\gamma,\lambda}(H^{k}_{G,\mathcal{T}_2})$ and $Q:=Q_1-Q_2$, so that from \eqref{eq:magsia} and \eqref{eq:t5g4rv55} \[\ensuremath{\mathcal{D}}=4k(\mathcal{A}_1'-\mathcal{A}_2')|E(H)|+(1\pm 8\epsilon)k (M_1-M_2)Q.\] We have that $|\mathcal{A}_1'-\mathcal{A}_2'|\leq L$, where $L:=|V(\mathcal{T}_1)|+|V(\mathcal{T}_2)|$ is an absolute constant. Using the purported algorithm for the magnetizations on $H^{k}_{G,\mathcal{T}_i}$, and since the latter graph has at most $|V(H)|\, |V(G)|+4k|E(H)|\, |V(\mathcal{T}_i)|$ vertices for all sufficiently large $|V(H)|$, we can compute $\widehat{\ensuremath{\mathcal{D}}}$ which is an $(1+\kappa)$-approximation to $\ensuremath{\mathcal{D}}$, so that \[|\widehat{\ensuremath{\mathcal{D}}}-\ensuremath{\mathcal{D}}|\leq k(|V(G)|+4 L) |E(H)|\kappa\] for some small $\kappa$. Then, we have that $\widehat{\textsc{MC}}=\frac{\widehat{\ensuremath{\mathcal{D}}}-4k(A_1'-A_2')|E(H)|}{k(M_1-M_2)D_1}-\frac{C}{D}|E(H)|$ satisfies \begin{equation}\label{eq:4g566g6} |\widehat{\textsc{MC}}-\textsc{Avg-Cut}_{\mu}(H)|\leq \big(\tfrac{|V(G)|+4L}{|M_1-M_2|}\kappa+8\epsilon\big)|E(H)|, \end{equation} where $\textsc{Avg-Cut}_{\mu}(H)$ denotes the common value of $\textsc{Avg-Cut}_{\mu_1}(H),\textsc{Avg-Cut}_{\mu_2}(H)$. By choosing $k$ sufficiently large, we have from \eqref{eq:avgcuti} that $\textsc{Avg-Cut}_{\mu}(H)$ is within a factor arbitrarily close to 1 from $\textsc{Max-Cut}(H)$. This has the potential effect of increasing $G$, but by choosing $\epsilon, \kappa$ to be sufficiently small positive constants we can further ensure from \eqref{eq:4g566g6} that our approximation $\widehat{\textsc{MC}}$ is within a factor arbitrarily close to 1 from $\textsc{Avg-Cut}_{\mu_1}(H)$, and hence from $\textsc{Max-Cut}(H)$ as well. This finishes the contradiction argument and completes the proof of Theorem~\ref{thm:vanilla}. \end{proof} With Theorem~\ref{thm:vanilla}, we can easily conclude the inapproximability result for the average-size of an independent set. Theorems~\ref{thm:mainind3},~\ref{thm:mainIs3},~\ref{thm:maingen3} will follow analogously, once we give the field gadget constructions of Section~\ref{sec:f434}. The proofs of these Theorems are given in Section~\ref{sec:f4343c}. \begin{proof}[Proof of Theorem~\ref{thm:mainind1}] By Example~\ref{e4f334}, we have two trees $\mathcal{T}_1$ and $\mathcal{T}_2$ with the same effective fields and different magnetization gaps. Also, independent sets correspond to $\beta=1,\gamma=0,\lambda=1$ and it is well-known (see, e.g., \cite{Sly10}) that $(\beta,\gamma,\lambda)\in \ensuremath{\mathcal{U}}_{\Delta}^*$ iff $\Delta\geq 6$. Therefore, the desired inapproximability result follows by applying Theorem~\ref{thm:vanilla}. \end{proof} The proof of Theorems~\ref{thm:mainind2},~\ref{thm:mainIs2}, and~\ref{thm:maingen2} build on similar reduction ideas, but the details are slightly more technical because of the different type of gadgets that we use (cf. Theorem~\ref{thm:const1}). The details can be found in Section~\ref{sec:maingen2}. \section{Field Gadget construction}\label{sec:gadget} In this section, we give the proof of Theorem~\ref{thm:const1} by first outlining the key ideas of our field-gadget constructions. We start with the following lemma which describes the effective field and magnetization gap of field gadgets built out of smaller field gadgets. \begin{lemma}\label{lem1} Suppose we have trees $\mathcal{T}_1,\dots,\mathcal{T}_k$ with roots $\rho_1,\hdots,\rho_k$, effective fields $R_1,\dots,R_k$ and magnetization gaps $M_1,\dots,M_k$, respectively. Let $\mathcal{T}$ be the tree with root $\rho$, edge $\{\rho,u\}$ and the roots of $\mathcal{T}_1,\dots,\mathcal{T}_k$ identified with $u$. Let $R$ and $M$ be the effective field and magnetization gap for $\mathcal{T}$. Then \begin{equation*} R = \frac{1+\gamma\lambda\prod^{k}_{i=1} R_i}{\beta+\lambda \prod^{k}_{i=1}R_i}, \qquad M = 1 - \omega(R) \bigg( 1 + \sum_{i=1}^k (M_i-1)\bigg), \end{equation*} where $$ \omega(R) := \frac{1+\beta \gamma-\beta R-\gamma/R}{1-\beta \gamma}. $$ For antiferromagnetic $(\beta,\gamma)$ and any $\lambda>0$, it holds that $R\in (\gamma, 1/\beta)$ and $0<\omega(R)<1$. \end{lemma} The first step in the construction is to create a family of field gadgets with sufficiently dense effective fields in an interval and magnetization gaps that are in a small interval. To define the interval, consider $x^*$ and $\omega^*$ defined as follows \begin{equation}\label{ode} x^* = \frac{1+\gamma\lambda (x^*)^2}{\beta+\lambda (x^*) ^2},\quad \omega^* = \omega(x^*) = \frac{1+\beta \gamma-\beta x^*-\gamma/x^*}{1-\beta \gamma}, \end{equation} and note that $\omega^*\in(0,1)$ from Lemma~\ref{lem1}. \begin{lemma}\label{led} Fix $\lambda>0$. For any $\delta>0$ and any sufficiently small $\tau_1>0$ we can find $\tau\in (0,\tau_1)$ and construct a family of field gadgets $\mathcal{L}=\{{\cal T}_1,\dots,{\cal T}_k\}$ whose effective fields are in the interval $[x^* - \tau,x^*+\tau]$ and for any $x\in [x^* - \tau,x^*+\tau]$ there exist a field gadget in the family whose effective field is in the interval $[x-\tau\delta,x+\tau\delta]$. \end{lemma} The proof of Lemma~\ref{led} builds on techniques from~\cite{complex} and is given in Section~\ref{sec:led}. The second step of the construction is to use the field gadgets constructed in Lemma~\ref{led} as follows. We will maintain a rooted field gadget $\mathcal{T}$ with effective field $R$. In each step we merge our current field gadget with one field gadget from ${\cal T}$ using the operation from Lemma~\ref{lem1}. We are going to analyze what pairs (effective field, magnetization gap) we can achieve with this procedure. Let $R_i$ and $M_i$ be the effective field and magnetization gap for the field gadget $\mathcal{T}_i$ in our collection. Merging the field gadget $\mathcal{T}$ with $\mathcal{T}_i$ corresponds to the following pair of maps $(\phi_i,\psi_i)$: $$ \phi_i(R) = \frac{1+\gamma \lambda R R_i}{\beta +\lambda R R_i}\quad\mbox{and}\quad \psi_i(R,M)= 1 - \omega(\phi_i(R))( M + M_i - 1). $$ For a small constant $\tau>0$ to be specified later, let \begin{equation}\label{idef2} I' = \Big[x^* - 2 \tau \frac{|\omega^*|}{1-|\omega^*|}, x^* + 2 \tau \frac{|\omega^*|}{1-|\omega^*|}\Big] \end{equation} The choice of the interval $I'$ is such that the maps $\phi_i$ are uniformly contracting and map the interval $I'$ to itself. Namely, we show the following in Section~\ref{sec:contr}. \begin{lemma}\label{contr} There exists $0<C_{\mathrm{min}} < C_{\mathrm{max}}<1$ and $\tau_0>0$ such that for all $\tau\in(0,\tau_0)$ for all $R\in I'$ and all $R_i\in [x^* - \tau, x^* + \tau]$ it holds that \[C_{\mathrm{min}}\leq |\phi'_i(R)|\leq C_{\mathrm{max}}, \quad \omega(R)\leq C_{\mathrm{max}}, \quad \phi_i(R)\in I'\] \end{lemma} The second step of our construction will actuallly take place in the following smaller sub-interval of $I'$: \begin{equation}\label{idef} I = [x^* - |\omega|\tau/2, x^* + |\omega|\tau/2] \subseteq I', \end{equation} The choice of $I$ is to ensure the following ``well-covered'' property for the maps $\phi_i$ on $I$ which is obtained using the density of the effective fields from Lemma~\ref{led}, the proof is given in Section~\ref{sec:contr}. \begin{lemma}\label{lc} Suppose $\delta<|\omega|/100$. For every two points $x_1,x_2\in I$ such that $|x_1-x_2|\leq |\omega|\tau \delta/2$ there exists $i$ such that $x_1,x_2\in\phi_i(I)$. \end{lemma} Lemmas~\ref{contr} and~\ref{lc} ensure that for any $x\in I$ we can construct a sequence of field gadgets whose effective field approaches $x$. Consider the following process \verb!Build-gadget!$(x,t)$ where $x\in I$ and $t\geq 0$. If $t=0$ we return the degenerate tree. If $t\geq 1$ then we let $\phi_i$ be any map such that $x\in\phi_i(I)$. Let $y = \phi_i^{-1}(x)$, call \verb!Build-gadget!$(y,t-1)$ and apply the operation of Lemma~\ref{lem1} on the returned field gadget and ${\cal T}_i$. \begin{lemma}\label{yyyqw} There exists $C>0$ such that for any $x\in I$ and any $t\geq 0$ the effective field $R$ of the field gadget returned by \verb!Build-gadget!$(x,t)$ (for any choice of the $\phi_i$'s) satisfies $|R-x|\leq C C_{\mathrm{max}}^t$. \end{lemma} We will prove Lemma~\ref{yyyqw} in Section~\ref{sec:case2}. For the field gadgets we construct we will always maintain the effective field in the interval $I'$, cf. Lemma~\ref{contr}. Now we show that the magnetization gaps of the field gadgets constructed using our process also stay restricted to an interval $J$. Let \begin{equation}\label{TDEF} T = \frac{2+\max|M_i|}{1-C_{\mathrm{max}}} \mbox{ and let $J$ be the interval $[-T,T]$.} \end{equation} \begin{lemma}\label{eq:TDEF} Suppose $R\in I'$ and $M\in J$ then $\psi_i(R,M)\in J$. \end{lemma} \begin{proof} We have $\psi_i(R,M) = 1 - \omega(R)( M_i + M - 1)$. Hence $|\psi_i(R,M)|\leq 1 + C_{\mathrm{max}} ( T + \max |M_i| + 1) \leq T$, where the last inequality follows from~\eqref{TDEF}. \end{proof} For any $x\in I$ we are going to construct a sequence of families of pairs of maps ${\cal F}_{x,0},{\cal F}_{x,1},\dots$ as follows (in each pair the first map is from $\mathbb{R}$ to $\mathbb{R}$, the second map in the pair is from $\mathbb{R}^2$ to $\mathbb{R}$). Let ${\cal F}_{x,0}$ contain the pair of maps $(x \mapsto x,(x,y)\mapsto y)$. To construct ${\cal F}_{x,t+1}$ we take every $\phi_i$ such that that $x\in \phi_i(I)$ and every $(f,g)\in {\cal F}_{\phi_i^{-1}(x),t}$ and place into ${\cal F}_{x,t+1}$ the map \begin{equation}\label{eq:remark} (R,M)\mapsto \left( \phi_i(f(R)), \psi_i(f(R),g(R,M)) \right). \end{equation} Every $(f,g)\in {\cal F}_{x,t}$ corresponds to a rooted field gadget with one ``input vertex'' where another rooted field gadget can be hanged. If the field gadget hanged at the ``input vertex'' has effective field $R$ and magnetization gap $M$ then the final vertex will have effective field $f(R)$ and magnetization gap $g(R,M)$. Intuitively the field gadgets closer to the root have larger influence on the magnetization difference. The function pair $(f,g)$ allows us to keep track of this influence. In the end our construction of field gadgets will always use the \verb!Build-gadget! procedure; a particular map in ${\cal F}_{x,t}$ corresponds to a particular choice of the first $t$ steps of the construction with the benefit of understanding precisely where the magnetization gap will end up (once we have the value of magnetization gap and effective field of field gadgets constructed in later steps). We are going to distinguish two possible cases for the families ${\cal F}_{x,t}$. In the first case we will obtain the gadgets we need immediately using the \verb!Build-gadget! procedure. In the second case we will construct a continuous function from the families. Then we will argue that the function cannot satisfy a functional equation and this will yield the gadgets we require. \begin{lemma}[Case I]\label{case1} Suppose there exists $x\in I$ such that for some $t_1,t_2$ there exist $(f_1,g_1)\in {\cal F}_{x,t_1}$ and $(f_2,g_2)\in {\cal F}_{x,t_2}$ such that $g_1(I'\times J)$ and $g_2(I'\times J)$ are disjoint. Let $\hat{M}$ be the distance of $g_1(I'\times J)$ and $g_2(I'\times J)$. Then, there is an algorithm which, on input rational $r>0$, outputs in time $poly(\mathrm{bits}(r))$ a pair of field gadgets ${\cal T}_1$ and ${\cal T}_2$, each of maximum degree 3 and size $O(|\log r|)$, such that \[|R_{\mathcal{T}_1} - x|, |R_{\mathcal{T}_2} - x|\leq r, \mbox{ but } |M_{\mathcal{T}_1}-M_{\mathcal{T}_2}|\geq\hat{M}.\] \end{lemma} \begin{proof} Note that for a fixed $t$ the union $\bigcup_x {\cal F}_{x,t}$ contains finitely many functions (because there are only finitely many choices for $\phi_i$ in each step of the construction). If $t_1,t_2$ and $x$ assumed by the lemma exist then we can find them by examining finitely many functions. For each $(f_1,g_1)$ and $(f_2,g_2)$ we check whether $f_1(I)\cap f_2(I)\neq\emptyset$ and $g_1(I'\times J)\cap g_2 (I'\times J) = \emptyset$; if we find we such a pair we take $x\in f_1(I)\cap f_2(I)$. Note the running time for this process is a constant depending on $\beta,\gamma,\lambda$. (Note that $f(I)$ and $g(I'\times J)$ is always an interval that we can find inductively.) To construct ${\cal T}_i$, $i\in\{1,2\}$ we use the \verb!Build-gadget! procedure following the choices of $(f_i,g_i)$ in the first $t_i$ steps, cf. the discussion below \eqref{eq:remark}. Using Lemma~\ref{yyyqw}, we run the procedure for $O(|\log r|)$ steps achieving $|R_i - x|\leq r$, $i\in\{1,2\}$. We have $M_i\in g_i(I'\times J)$, $i\in\{1,2\}$ and hence $|M_1-M_2|\geq\hat{M}$. \end{proof} \begin{lemma}[Case II]\label{case2} Suppose that for every $x$, every $t_1,t_2$ and every two functions $(f_1,g_1)\in {\cal F}_{x,t_1}$ and $(f_2,g_2)\in {\cal F}_{x,t_2}$ we have that $f_2(I'\times J)$ and $g_2(I'\times J)$ intersect. Then there exists a continuous function $F:I\rightarrow J$ such that for every $x\in I$, every $\epsilon>0$ there exists $t_0$ such that for every $t\geq t_0$ and every $(f,g)\in {\cal F}_{x,t}$ and every $R\in I'$ and every $M\in J$ we have \begin{equation}\label{close} |g(R,M) - F(x)|\leq\epsilon. \end{equation} \end{lemma} The proof of Lemma~\ref{case2} is given in Section~\ref{sec:case2}. \begin{lemma}\label{viola} Suppose CASE II happens, that is, the assumption of Lemma~\ref{case2} is satisfied; let $F$ be the continuous function guaranteed by Lemma~\ref{case2}. Suppose that there exist $x_1,x_2\in I$ such that the following equation is violated. \begin{equation}\label{fun2} F\left(\frac{1+\gamma\lambda x_1 x_2}{\beta+\lambda x_1x_2}\right) = 1 - \frac{(1-\beta \gamma)\lambda x_1 x_2}{(1+\gamma\lambda x_1 x_2)(\beta+\lambda x_1 x_2)}(F(x_1) + F(x_2) - 1) \end{equation} Then, we can find in constant time (where the constant depends on $\beta,\gamma,\lambda,k$) rational numbers $x_1,x_2\in I$ such that \eqref{fun2} is violated and, moreover, for any integer $k\geq 1$, rationals $\hat{R}_1,\hdots,\hat{R}_k\in I$ such that the following holds. There is an algorithm which on input any rational $r\in (0,1/2)$ and any $i\in [k]$ outputs in time $poly(\mathrm{bits}(r))$ a pair of field gadgets ${\cal T}_1$ and ${\cal T}_2$, each of maximum degree 3 and size $O(|\log r|)$, such that $|R_{\mathcal{T}_1} - \hat{R}_i|\leq r$, $|R_{\mathcal{T}_2} - \hat{R}_i|\leq r$ and $|M_{\mathcal{T}_1}-M_{\mathcal{T}_2}|\geq\hat{M}$. \end{lemma} \begin{proof}[Proof of Lemma~\ref{viola}] Let $k\geq 1$ be an arbitrary integer and fix $x_1,x_2\in I$ that violate~\eqref{fun2}. Let $\delta>0$ be the absolute value of the difference between the two sides. From the continuity of $F$, more precisely equation~\eqref{equ2}, there exists $\epsilon>0$ such that for any $y_1,y_2\in I$ with $|y_1-x_1|\leq\epsilon$ and $|y_2-x_2|\leq\epsilon$ we have that $y_1,y_2$ violate~\eqref{fun2} with difference at least $\delta/2$ between the two sides. Let $\mathcal{C}$ be a finite set of pairs $(y_1,y_2)$ which form an $\tfrac{\epsilon}{20k}$-net for $I\times I$; by perturbing slightly the set of points in $\mathcal{C}$ we can obtain an $\tfrac{\epsilon}{10k}$-net for $I\times I$, say $\mathcal{C}'$, such that for any two pairs $(y_1,y_2)$ and $(y_1',y_2')$ it holds that $y_1y_2\neq y_1'y_2'$. Now, to check whether a pair $(y_1,y_2)$ in $\mathcal{C}'$ violates~\eqref{close}, we run \verb!Build-gadget! for $y_1,y_2$ and $y_3:=\frac{1+\gamma\lambda y_1 y_2}{\beta+\lambda y_1y_2}$ with the value of $t$ given by Lemma~\ref{case2} to achieve bound $\delta/100$ on the right-hand side of~\eqref{close}. Then, we will find at least $k$ different pairs $(y_{1,j},y_{2,j})$, $j=1,\hdots, k$ that violate~\eqref{fun2}. For $j\in [k]$, let $\hat{R}_j:=y_{3,j}=\frac{1+\gamma\lambda y_{1,j} y_{2,j}}{\beta+\lambda y_{1,j}y_{2,j}}$ and note that by the construction of $\mathcal{C}'$, the $\hat{R}_j$'s are pairwise distinct. Now, on input $j\in [k]$, we use the \verb!Build-gadget! procedure to construct $\hat{\cal T}_i$ for $y_{i,j}$, $i\in\{1,2,3\}$ for $t=O(|\log r |)$ steps, using Lemma~\ref{yyyqw},. The tree ${\cal T}_1$ is obtained by merging $\hat{\cal T}_1$ and $\hat{\cal T}_2$ and the tree ${\cal T}_2$ is $\hat{\cal T}_3$. \end{proof} Now assume that equation~\eqref{fun2} is satisfied for all $x_1,x_2\in I$. We are going to derive a contradiction, thereby showing that ~\eqref{fun2} must be violated. We will do this in two steps. First we use a special case of equation~\eqref{fun2} to obtain a functional equation that constraints the possible solutions of $F$. Second we show that none of these solutions satisfies~\eqref{fun2}. Suppose $x_1,x_2,x_3\in I$ are such that $x_1 x_2 = x_3 x^*$. Plugging into~\eqref{fun2} we obtain that $F$ has to satisfy the following equation \begin{equation}\label{fun} F(x_1) + F(x_2) = F(x_3) + F(x^*). \end{equation} \begin{lemma} Suppose $F$ is a continuous function on $I$. Suppose that for $x_1,x_2,x_3\in I$ such that $x_1 x_2 = x_3 x^*$ we have~\eqref{fun}. Then there exists $c$ such that for all $x\in I$ we have \begin{equation}\label{caus} F(x) = c\log(x/x^*) + F(x^*). \end{equation} \end{lemma} \begin{proof} We will use the following parametrization to turn~\eqref{fun} into Cauchy's functional equation. Let $x_1 = x^*\exp(y_1)$, $x_2 =2x^*\exp(y_2)$, and $x_3=x^*\exp(y_3)$. The condition $x_1 x_2 = x^* x_3$ is equivalent to $y_1+y_2=y_3$. Let \begin{equation}\label{gdef} G(y) = F(x^*\exp y) - F(x^*). \end{equation} Note that $G$ is defined on the interval $[\log(I_L/x^*),\log(I_R/x^*)]$ that contains $0$ (since $I_L<x^*<I_R$). Equation~\eqref{fun} becomes \begin{equation}\label{fun3} G(y_1)+G(y_2) = G(y_1+y_2). \end{equation} From continuity of $F$ we have continuity of $G$. Since~\eqref{fun3} is Cauchy's functional equation on an interval containing zero the only continuous solutions are $G(y)=cy$ for some constant $c$. Plugging in~\eqref{gdef} we obtain~\eqref{caus}. \end{proof} Finally we show that~\eqref{fun2} has to be violated. \begin{lemma}\label{final} A solution of form~\eqref{caus} cannot satisfy~\eqref{fun2}. \end{lemma} \begin{proof} We will plug-in~\eqref{caus} into~\eqref{fun2} with $x_1=x^*$ and $x_2=y$. We obtain \begin{equation}\label{zzz2} c \log \Big(\frac{1+\gamma\lambda x^* y}{\beta+\lambda x^* y}\Big) - c\log x^* + F(x^*) = 1- \frac{(1-\beta \gamma)\lambda x^* y}{(1+\gamma\lambda x^* y)(\beta+\lambda x^* y)}( c\log(y) - c\log(x^*)- 1 + 2 F(x^*)). \end{equation} Differentiating (w.r.t. $y$) we obtain \begin{align*} - c \frac{\lambda(1-\beta \gamma) x^*}{(\beta +\lambda x^* y)(1+\gamma\lambda x^* y)}& = \left(-\frac{(1-\beta \gamma)\lambda x^*(-\beta+\gamma \lambda^2 (x^*y)^2) }{(1+\gamma\lambda x^* y)^2(\beta+\lambda x^* y)^2} \right)( c\log(y) - c\log(x^*)- 1 + 2 F(x^*))\\&\hskip 2cm -\frac{(1-\beta \gamma)\lambda x^* y}{(1+\gamma\lambda x^* y)(\beta+\lambda x^* y)}\left( c\frac{1}{y} \right), \end{align*} which simplifies to \begin{equation}\label{zzz} 0 =\frac{(1-\beta \gamma)\lambda x^*(-\beta+\gamma \lambda^2 (x^*y)^2) }{(1+\gamma\lambda x^* y)^2(\beta+\lambda x^* y)^2}( c\log(y) - c\log(x^*)- 1 + 2 F(x^*)) \end{equation} The only solution for~\eqref{zzz} has to have $c=0$ and $F(x^*)=1/2$. Plugging $c=0$ and $F(x^*)=1/2$ into~\eqref{zzz2} we obtain 1/2 = 1 + 0, a contradiction. \end{proof} Finally, we combine the various pieces from the previous subsection to prove Theorem~\ref{thm:const1}. In fact, we will prove a slight strengthening of Theorem~\ref{thm:const1}, given below, which will be used in our reduction, analogously to Lemma~\ref{lem:vanilla}. \begin{theorem}\label{thm:occgadget} Let $(\beta,\gamma,\lambda)$ be antiferromagnetic and $\lambda>0$ be such that $\lambda \neq 1$ whenever $\beta=\gamma$. For every integer $k\geq 1$, there exist constants $\hat{M},\Xi>0$ and $k$ distinct numbers $\hat{R}_1,\hdots, \hat{R}_k>0$ such that the following holds. There is an algorithm, which, on input $i\in[k]$ and a rational $\delta_R>0$, outputs in time $poly(\mathrm{bits}(r))$ a pair of field gadgets $\mathcal{T}_1,\mathcal{T}_2$, each of maximum degree $3$ and size $O(|\log r|)$, such that \[|R_{\mathcal{T}_1} - \hat{R}_i|,\, |R_{\mathcal{T}_2} - \hat{R}_i|\leq r,\mbox{ but } |M_{\mathcal{T}_1}-M_{\mathcal{T}_2}|\geq \hat{M}.\] Moreover, the magnetization gaps $M_{\mathcal{T}_1}, M_{\mathcal{T}_2}$ are bounded in absolute value by the constant $\Xi$. \end{theorem} \begin{proof} There are two cases to consider: either Lemma~\ref{case1} or Lemma~\ref{case2}. In the latter case, we are clearly done using the conclusion of Lemma~\ref{case2}. In the former case, we are also done, modulo that Lemma~\ref{case1} only guarantees the existence of a single $\hat{R}$, namely the value $x$. Let $t_1,t_2$ be such that $(f_1,g_1)\in {\cal F}_{x,t_1}$ and $(f_2,g_2)\in {\cal F}_{x,t_2}$ satisfy $g_1(I'\times J)\cap g_2(I'\times J)=\emptyset$. The functions in $\mathcal{F}_{x,t}$ are continuous and defined on a closed interval, so we have that for sufficiently small $\epsilon>0$, for all $y$ such that $|y-x|\leq \epsilon$, we can find $(\tilde{f}_1,\tilde{g}_1)\in {\cal F}_{x,t_1}$ and $(\tilde{f}_2,\tilde{g}_2)\in {\cal F}_{x,t_2}$ which satisfy $\tilde{g}_1(I'\times J)\cap \tilde{g}_2(I'\times J)=\emptyset$. We pick $k$ such $y$'s for the values of the $\hat{R}_i$'s for $i=1,\hdots,k$ and produce the desired trees by running the \verb!Build-gadget! procedure for $O(\log |r|)$ steps. Finally note that the magnetizations all lie in the interval $J$, see \eqref{TDEF} and Lemma~\ref{eq:TDEF}, which is bounded by absolute constants, finishing the proof. \end{proof} Note that Theorem~\ref{thm:const1} corresponds to the case $k=1$ in Theorem~\ref{thm:occgadget}. \subsection{Proof of Theorem~\ref{thm:const2}} To prove Theorem~\ref{thm:const2}, we will just need an absolute bound on the second derivative of the effective-field constructions of the previous subsection, when viewed as functions of the parameter $\lambda$. The following lemma gives this bound. \begin{lemma}\label{lem:34f34vrr} Let $R_1(\lambda),\dots,R_k(\lambda)$ be a family of functions from a closed interval $I$ to $(\gamma,1/\beta)$. Consider the following family ${\cal F}$ of functions from $I$ to $(\gamma,1/\beta)$. Let $Q_0(\lambda)$ be a function from $I$ to $(\gamma,1/\beta)$. For every sequence $a_0,\dots,a_{m-1}$ of numbers in $[k]$ for $i\in [m-1]$ let $$ Q_{i+1}(\lambda) = \frac{1+\gamma\lambda R_{a_i}(\lambda) Q_{i}(\lambda)}{\beta + \lambda R_{a_i}(\lambda) Q_{i}(\lambda)}. $$ and place function $Q_m$ into ${\cal F}$. Suppose each $R_\ell(\lambda)$ and $Q_0(\lambda)$ is twice continuously differentiable on $I$. There exists bounded intervals $I_1,I_2$ such that for any $\lambda\in I$ and any $Q(\lambda)\in{\cal F}$ we have $Q_i'(\lambda)\in I_1$ and $Q_i''(\lambda)\in I_2$. \end{lemma} \begin{proof} Let $\ell=a_i$. We have \begin{equation}\label{azzz} Q_{i+1}'(\lambda) = \frac{(\gamma\lambda {R'}_\ell(\lambda) Q_i(\lambda)+\gamma\lambda R_\ell(\lambda) Q_i'(\lambda)) }{\beta + \lambda R_i(\lambda) Q_i(\lambda)} - \frac{(1+\gamma\lambda R_\ell(\lambda) Q_i(\lambda)) (\lambda {R'}_\ell(\lambda) R (\lambda)+\lambda R_\ell(\lambda) Q_i'(\lambda)) }{(\beta + \lambda R_\ell(\lambda) Q_i(\lambda))^2}. \end{equation} We can re-write~\eqref{azzz} as follows \begin{equation}\label{ind} \frac{Q_{i+1}'(\lambda)}{Q_{i+1}(\lambda)} = \frac{\lambda R_\ell(\lambda)Q_i(\lambda) (\beta\gamma-1)}{(1+\lambda\gamma R_\ell(\lambda)Q_i(\lambda))(\beta+\lambda R_\ell(\lambda)Q_i(\lambda))} + \frac{p_1(R_\ell(\lambda),Q_i(\lambda),R'_\ell(\lambda))}{(\beta + \lambda R_\ell(\lambda) Q_i(\lambda))}, \end{equation} where $p_1$ is a constant degree polynomial. Note that the coefficient of $Q_i'(\lambda)/Q_i(\lambda)$ in~\eqref{azzz} satisfies \begin{equation}\label{azzz2} \Big|\frac{\lambda R_\ell(\lambda)Q_i(\lambda) (\beta\gamma-1)}{(1+\lambda\gamma R_\ell(\lambda)Q_i(\lambda))(\beta+\lambda R_\ell(\lambda)Q_i(\lambda))}\Big| \leq C < 1, \end{equation} where $C=\frac{1-\sqrt{\beta\gamma}}{\sqrt{\beta\gamma}+1}$ if $\beta\gamma\neq 0$ (the case $\beta\gamma=0$ is discussed below). To see the bound in~\eqref{azzz2} let $W=\lambda R_\ell(\lambda)Q_i(\lambda)$. The coefficient becomes $\frac{W(\beta\gamma-1)}{(1+\gamma W)(\beta + W)}$, which achieves maximum for $W=\sqrt{\beta/\gamma}$ with value $\frac{\sqrt{\beta\gamma}-1}{\sqrt{\beta\gamma}+1}$. In the case $\beta=0$ the coefficient becomes $-1/(W\gamma+1)$, which since $W$ is uniformly bounded from below has absolute value uniformly bounded from $1$. In the case $\gamma=0$ the coefficient becomes $-W/(\beta+W)$ and since $W$ is uniformly bounded from above has absolute value uniformly bounded from $1$. Each $R'_\ell(\lambda)$ is bounded (since it is a continuous function on a closed interval. Hence there exists constant $M_1$ such that for any $x\in (\gamma,1/\beta)$ and any $\lambda\in I$ $$ \left| \frac{p_1(R_\ell(\lambda),x,R'_\ell(\lambda))}{(\beta + \lambda R_\ell(\lambda) x)^2} \right|\leq M_1. $$ From continuous differentiability of $Q_0$ we also have that there exists a constant $M_2$ such that for any $\lambda\in I$ we have $$ \Big|\frac{Q_0'(\lambda)}{Q_0(\lambda)}\Big|\leq M_2. $$ Now using~\eqref{ind} by induction $|\frac{Q_{i}'(\lambda)}{Q_{i}(\lambda)}|\leq (M_1+M_2)/(1-C)$. The argument for the second derivative is almost the same. We can write an expression for $Q''_{i+1}(\lambda)/Q_{i+1}(\lambda)$ as follows \begin{equation}\label{ind2} \frac{Q_{i+1}''(\lambda)}{Q_{i+1}(\lambda)} = \frac{\lambda R_\ell(\lambda)Q_i(\lambda) (\beta\gamma-1)}{(1+\lambda\gamma R_\ell(\lambda)Q_i(\lambda))(\beta+\lambda R_\ell(\lambda)Q_i(\lambda))} \frac{Q_{i}''(\lambda)}{Q_i(\lambda)} + \frac{p_2(R_\ell(\lambda),Q'_i(\lambda),Q_i(\lambda),R'_\ell(\lambda),R''_\ell(\lambda))}{(\beta + \lambda R_\ell(\lambda) Q_i(\lambda))^3}, \end{equation} where $p_2$ is a constant degree polynomial. Again all the parameters for $p_2$ are bounded (for $Q_i'(\lambda)$ we use the $(M_1+M_2)/(1-C) (1/\beta)$ bound) and hence there exists a constant $M_3$ such that for any $x\in (\gamma,1/\beta)$ and any $|y|\leq (M_1+M_2)/(1-C)$ we have $$ \Big|\frac{p_2(R_\ell(\lambda),y,x,R'_\ell(\lambda),R''_\ell(\lambda))}{(\beta + \lambda R_\ell(\lambda) x)^3}\Big|\leq M_3. $$ We also have that there exists a constant $M_4$ such that for any $\lambda\in I$ we have $$ \Big|\frac{Q_0''(\lambda)}{Q_0(\lambda)}\Big|\leq M_4. $$ Note that the coefficient of $Q_{i}''(\lambda)/Q_{i}(\lambda)$ in~\eqref{ind2} satisfies~\eqref{azzz2}. Now using~\eqref{ind2} by induction $|Q_{i}''(\lambda)/Q_i(\lambda)|\leq (M_3+M_4)/(1-C)$. \end{proof} We now give the proof of Theorem~\ref{thm:const2}. \begin{proof}[Proof of Theorem~\ref{thm:const2}] By Theorem~\ref{thm:const1}, for antiferromagnetic $(\beta,\gamma)$ and $\lambda>0$ with $(\beta,\gamma,\lambda)\neq (\beta,\beta,1)$, there exist $\hat{R},\hat{M}>0$ such that for any $r>0$, there exist a pair of field gadgets $\mathcal{T}_1,\mathcal{T}_2$, each of maximum degree 3 and size $O(|\log r|)$, such that \[|R_{\mathcal{T}_1} -\hat{R}|, |R_{\mathcal{T}_2}- \hat{R}|\leq r,\mbox{ but } |M_{\mathcal{T}_1}-M_{\mathcal{T}_2}|>\hat{M}.\] The effective fugacities of the gadgets $\mathcal{T}_1$, $\mathcal{T}_2$, viewed as functions of $\lambda$, are of the form given in Lemma~\ref{lem:34f34vrr} and hence their second derivatives are uniformly bounded. Note that the magnetization gap is the first derivative of the logarithm of the effective fugacity. So, the lower bound on the difference of $M_{\mathcal{T}_1},M_{\mathcal{T}_2}$ implies an absolute lower bound on the difference of the derivatives of $R_{\mathcal{T}_1},R_{\mathcal{T}_2}$. Since the second derivative is uniformly bounded (by Lemma~\ref{lem:34f34vrr}), we can find $\hat{\lambda}$ arbitrarily close to $\lambda$ such that $R_{\mathcal{T}_1}(\hat{\lambda}),R_{\mathcal{T}_2}(\hat{\lambda})$ are equal. Since $R_{\mathcal{T}_1},R_{\mathcal{T}_2}(\lambda)$ are rational functions of $\lambda$ (using that $\beta,\gamma$ are rational), we obtain that any such $\hat{\lambda}$ must in fact be algebraic, finishing the proof. \end{proof} \section{Field Gadgets: Remaining Proofs} In this section, we give the remaining proofs of Section~\ref{sec:gadget}. \subsection{Proof of Lemma~\ref{lem1}} \begin{proof}[Proof of Lemma~\ref{lem1}] Let $Z^{\mathsf{in}}_{\mathcal{T},\rho}$ be the weight of all configurations on $\mathcal{T}$ rooted at $\rho$ where $\rho$ is occupied (has state $1$). Similarly let $Z^{\mathsf{out}}_{\mathcal{T},r}$ be the weight of all configurations on $\mathcal{T}$ rooted at $\rho$ where $\rho$ is unoccupied (has state $1$). Define analogously $Z^{\mathsf{in}}_{\mathcal{T}_i,\rho_i}$ for $i=1,\hdots,k$. Then, we have \begin{align*} Z^{\mathsf{in}}_{\mathcal{T},\rho}&=\lambda \bigg(\prod^{k}_{i=1} Z^{\mathsf{out}}_{\mathcal{T}_i,\rho_i}+\gamma\lambda\prod^{k}_{i=1} \frac{Z^{\mathsf{in}}_{\mathcal{T}_i,\rho_i}}{\lambda}\bigg)\\ Z^{\mathsf{out}}_{\mathcal{T},\rho}&=\beta\prod^{k}_{i=1} Z^{\mathsf{out}}_{\mathcal{T}_i,\rho_i}+\lambda \prod^{k}_{i=1} \frac{Z^{\mathsf{in}}_{\mathcal{T}_i,\rho_i}}{\lambda} \end{align*} We therefore have that \[R=\frac{1}{\lambda}\frac{Z^{\mathsf{in}}_{\mathcal{T},\rho}}{Z^{\mathsf{out}}_{\mathcal{T},r}}=\frac{\prod^{k}_{i=1} Z^{\mathsf{out}}_{\mathcal{T}_i,r_i}+\gamma\lambda\prod^{k}_{i=1} \frac{Z^{\mathsf{in}}_{\mathcal{T}_i,\rho_i}}{\lambda}}{\beta\prod^{k}_{i=1} Z^{\mathsf{out}}_{\mathcal{T}_i,\rho_i}+\lambda \prod^{k}_{i=1} \frac{Z^{\mathsf{in}}_{\mathcal{T}_i,\rho_i}}{\lambda}}=\frac{1+\gamma\lambda\prod^{k}_{i=1} R_i}{\beta+\lambda \prod^{k}_{i=1}R_i}.\] For the magnetization gap, we view $Z^{\mathsf{in}}_{\mathcal{T},\rho}, Z^{\mathsf{out}}_{\mathcal{T},\rho},$ and $Z^{\mathsf{in}}_{\mathcal{T}_i,\rho_i}, Z^{\mathsf{out}}_{\mathcal{T}_i,\rho_i}$ as polynomials in $\lambda$, and therefore the $R_i$'s and $R$ as rational functions of $\lambda$. Then observe that \[M_i=\lambda \frac{\partial \log Z^{\mathsf{in}}_{\mathcal{T}_i,\rho_i}}{\partial \lambda}- \lambda \frac{\partial \log Z^{\mathsf{out}}_{\mathcal{T}_i,\rho_i}}{\partial \lambda}=\lambda \frac{\partial \log (\lambda R_i)}{\partial \lambda}=1+\frac{\lambda}{R_i} \frac{\partial R_i}{\partial \lambda},\] and similarly $M=1+\frac{\lambda}{R} \frac{\partial R}{\partial \lambda}$. It follows that \begin{align*} M&=1-\frac{(1-\beta \gamma)\lambda}{R(\beta+\lambda \prod^{k}_{i=1}R_i)^2}\frac{\partial (\lambda \prod^{k}_{i=1}R_i)}{\partial \lambda}=1-\frac{(1-\beta\gamma)\lambda}{(1+\gamma\lambda\prod^{k}_{i=1} R_i)(\beta+\lambda \prod^{k}_{i=1}R_i)}\frac{\partial (\lambda \prod^{k}_{i=1}R_i)}{\partial \lambda}\\ &=1-\frac{(1-\beta \gamma)\lambda \prod^{k}_{i=1}R_i}{(1+\gamma\lambda\prod^{k}_{i=1} R_i)(\beta+\lambda \prod^{k}_{i=1}R_i)}\bigg(1+\sum^{k}_{i=1}\frac{\lambda}{R_i}\frac{\partial R_i}{\partial \lambda}\bigg)=1 -\omega(R) \bigg( 1 + \sum_{i=1}^k (M_i-1)\bigg).\qedhere \end{align*} \end{proof} \subsection{Proof of Lemma~\ref{led}}\label{sec:led} In this section, we give the proof of Lemma~\ref{led}. We first create two field gadgets ${\cal T}_1$ and ${\cal T}_2$ with effective fields $R_1,R_2$ where $R_1$ is close to $x^*$ and $R_2$ is even closer to $x^*$. We generalize a ``bounding-tree'' construction from \cite{glauber}, which was used in the case of the hard-core model. To handle the special case $\lambda=\frac{1-\beta}{1-\gamma}$ for some $\beta,\gamma\in (0,1)$, cf. Definition~\ref{def:field} and the remark below, we will use the following field gadget whose effective field is different than $ 1$ and satisfies $R\in (\gamma,1/\beta)$. \begin{lemma}\label{lem:triangle} Let $(\beta,\gamma)$ be antiferromagnetic with $\beta,\gamma\in (0,1)$ and $\beta\neq \gamma$. Let $\lambda=\frac{1-\beta}{1-\gamma}$ and consider the field gadget $\mathcal{T}$ rooted at $\rho$, consisting of a triangle together with the extra vertex $\rho$ that is attached to one of the vertices of the triangle. Then, the effective field $R$ of $\mathcal{T}$ is different than 1 and satisfies $R\in (\gamma,1/\beta)$. \end{lemma} \begin{proof} A direct calculation gives that $R=\frac{1+\gamma \lambda r}{\beta+\lambda r}$ where $r=\frac{\beta + 2 \lambda \gamma + \lambda^2 \gamma^3}{\beta^3 + 2 \lambda \beta + \lambda^2 \gamma}$. Since $\lambda=\frac{1-\beta}{1-\gamma}$, we have that $R\neq 1$ iff $r\neq 1$. Using the value of $\lambda$ again we obtain that $r=1$ is equivalent to $(1-\beta)^2(\beta-\gamma)=0$, which cannot be the case when $\beta\neq \gamma$ and $\beta,\gamma\in(0,1)$. The fact that $R\in (\gamma,1/\beta)$ follows from $r\in (\gamma,1/\beta)$. \end{proof} \begin{lemma}\label{lem:rr44f} For every $\epsilon_1,\epsilon_2>0$ there exist field gadgets $\mathcal{T}_1$ and $\mathcal{T}_2$ such that \begin{equation} |R_1 - x^*| < \epsilon_1 \quad\mbox{and}\quad |R_2 - x^*| < \epsilon_2 |R_1 - x^*|. \end{equation} \end{lemma} \begin{proof} We will inductively construct two sequences of field gadgets ${\cal T}^L_1,{\cal T}^L_2,\dots$ and ${\cal T}^U_1,{\cal T}^U_2,\dots$ with effective fields $L_1,L_2,\dots$ and $U_1,U_2,\dots$. Throughout the construction we will maintain $1/\beta < L_i\leq x^*\leq U_i < \gamma$ and $L_i\neq U_i$. We will use the following inequalities \begin{equation}\label{eew} x<x^*\implies \frac{1+\gamma\lambda x^2}{\beta+\lambda x^2}>x^*\quad\mbox{and}\quad x>x^*\implies \frac{1+\gamma\lambda x^2}{\beta+\lambda x^2}<x^*; \end{equation} these follow from the fact that $\frac{1+\gamma\lambda x^2}{\beta+\lambda x^2}$ is decreasing and that $x^*$ is the fixpoint. If $1<x^*$ then we let ${\cal T}^L_1$ to be the degenerate tree (see Example~\ref{eee}) and ${\cal T}^U_1$ be the tree with one edge. Note that ${\cal T}^U_1$ is obtained from the degenerate tree using the operation of Lemma~\ref{lem1} and hence $L_1 = 1$ and $U_1 = (1+\gamma\lambda)/(\beta+\lambda)$ which by~\eqref{eew} is greater than $x^*$. In the case $x^*<1$ by the same argument we can take ${\cal T}^L_1$ the tree with one edge and ${\cal T}^U_1$ the degenerate tree and we again have $L_1 < x^* < U_1$. In the case where $x^*=1$ we must have that $\lambda=\frac{1-\beta}{1-\gamma}$ for some $\beta,\gamma\in (0,1)$ with $\beta\neq \gamma$; then, we can use the field gadget $\mathcal{T}$ of Lemma~\ref{lem:triangle}: if $R<1$ then we let ${\cal T}^L_1$ be $\mathcal{T}$ and we take ${\cal T}^U_1$ to be the single edge tree, and if $R>1$, vice versa. Now assume $L_i\leq x^* \leq U_i$ and $L_i\neq U_i$. Using~\eqref{eew} we have that \begin{equation}\label{iii} \frac{1+\gamma\lambda U_i^2}{\beta+\lambda U_i^2} \leq x^* \leq \frac{1+\gamma\lambda L_i^2}{\beta+\lambda L_i^2}. \end{equation} From the monotonicity of the map $x\mapsto (1+\gamma\lambda x)/(\beta+\lambda x)$ and~\eqref{iii} we have that there is $k\in\{0,1\}$ such that \begin{equation}\label{zzh} L_{i+1}:=\frac{1+\gamma\lambda U_i^k L_i^{2-k}}{\beta+\lambda U_i^k L_i^{2-k}} \leq x^* \leq \frac{1+\gamma\lambda U_i^{k+1}L_i^{1-k}}{\beta+\lambda U_i^{k+1} L_i^{1-k}}=:U_{i+1}. \end{equation} Equation~\eqref{zzh} corresponds to 1) creating ${\cal T}^L_{i+1}$ using $k$ copies of ${\cal T}^U_{i}$ and $2-k$ copies of ${\cal T}^L_{i}$ and 2) creating ${\cal T}^U_{i+1}$ using $k+1$ copies of ${\cal T}^U_{i}$ and $1-k$ copies of ${\cal T}^L_{i}$. Note that $U_i\neq L_i$ implies $U_{i+1}\neq L_{i+1}$. We will now argue that $\lim_{n\rightarrow\infty} L_n = \lim_{n\rightarrow\infty} U_n = x^*$. From~\eqref{zzh} we obtain \begin{equation}\label{dac2} \frac{U_i}{L_i} = \frac{(L_{i+1}\beta - 1)(\gamma-U_{i+1})}{(U_{i+1}\beta - 1)(\gamma-L_{i+1})}. \end{equation} We will now argue \begin{equation}\label{dac} \frac{(L_{i+1}\beta - 1)(\gamma-U_{i+1})}{(U_{i+1}\beta - 1)(\gamma-L_{i+1})} > \frac{U_{i+1}}{L_{i+1}}. \end{equation} We can rewrite~\eqref{dac} as follows $$ (U_{i+1}-L_{i+1})( \gamma(1-\beta L_{i+1}) + \beta L (U_{i+1} - \gamma) ) > 0, $$ which follows from $R\in (\gamma,1/\beta)$ (see Lemma~\ref{lem1}). Note that $U_i/L_i$ is a decreasing sequence, $U_i/L_i\geq 1$ and hence it has a limit. We are going to argue that the limit is $1$. Suppose the limit is $\alpha\geq 1$. Note that the values of $L_i$ are restricted to $(\gamma,1/\beta)$ and hence the set $\{L_i\,|\,i\geq 1\}$ has an accumulation point $x$. At the accumulation point we have \begin{equation}\label{eeeex} \alpha = \frac{(x\beta-1)(\gamma-\alpha x)}{(\alpha x \beta -1)(\gamma-x)}, \end{equation} since for every $\epsilon>0$ there exist $i$ such that $|L_{i+1}-x|\leq\epsilon$ and $|U_{i+1} - \alpha x|\leq \epsilon$ and $|U_{i}/L_{i}-\alpha|\leq\epsilon$ (which together with~\eqref{dac2} implies~\eqref{eeeex}). Equation~\eqref{eeeex} simplifies to \begin{equation}\label{eeeex2} (1-\alpha)( \alpha\beta\gamma x -\alpha\beta x^2 +\beta\gamma x - \gamma ) =0. \end{equation} We will show that for $x\in (\gamma,1/\beta)$ we have \begin{equation}\label{part} \alpha\beta\gamma x -\alpha\beta x^2 +\beta\gamma x - \gamma < 0. \end{equation} For $x=\gamma$ the left-hand side of~\eqref{part} simplifies to $(\beta\gamma-1)\gamma<1$. The derivative of the left-hand side of~\eqref{part} with respect to $x$ is \begin{equation}\label{part2} \beta (\alpha\gamma-2\alpha x + \gamma). \end{equation} We will show that for $x\in (\gamma,1/\beta)$ the expression~\eqref{part2} is negative; because of linearity we only need to argue at the endpoints of the interval. For $x=\gamma$ the value is $\gamma-\alpha\gamma<0$. For $x=1/\beta$ the value is $(1+\alpha)\beta \gamma - 2\alpha<0$. This proves~\eqref{part2} and hence~\eqref{eeeex2} implies $\alpha=1$, that is, the limit of $U_i/L_i$ goes to $1$ as $i\rightarrow\infty$. To construct ${\cal T}_1$ we iterate the process until $U_i/L_i\leq 1+\epsilon_1/x^*$; this implies $|U_i-x^*|\leq\epsilon_1$ and $|L_i-x^*|\leq\epsilon_1$. Since $U_i\neq L_i$ at least one of them is different from $x^*$; this will be the effective field of our field gadget ${\cal T}_1$. To construct ${\cal T}_2$ we iterate the process until $U_j/L_j\leq 1+\epsilon_2|R_1-x^*|/x^*$ and take either the field gadget for $L_j$ or $U_j$. \end{proof} \begin{proof}[Proof of Lemma~\ref{led}] We will use the Taylor approximation of the map of Lemma~\ref{lem1} for $R_1,R_2$ close to $x^*$. More precisely, there exists $C>0$ and $\tau_0>0$ such that for any $\tau\in(0,\tau_0)$, $|y_1|\leq\tau$, and $|y_2|\leq\tau$ for $R_1=x^*+y_1$ and $R_2=x^*+y_2$ we have \begin{equation}\label{oooz} \Big|\frac{1+\gamma \lambda R_1 R_2}{\beta +\lambda R_1 R_2} - R\Big|\leq C \tau^2, \end{equation} where $R=x^* - \omega^*(y_1 + y_2)$ (see equation~\eqref{bou1}). For $i\in\{0,\dots,Q\}$ (where $Q=\lceil 2\log_2(1/\delta) + 2\log_2(1/\omega^*)\rceil$) we will construct a sequence of field gadgets ${\cal T}_{i,0}, \dots, {\cal T}_{i,2^i}$ with effective fields $R_{i,0},\dots,R_{i,2^i}$ that are close to an arithmetic sequence. More precisely for each $i\in\{0,\dots,Q\}$ there will be a value $\alpha_i$ and $\xi_i>0$ such that for all $j\in\{0,\dots,2^i\}$ we have \begin{equation}\label{suho} |R_{i,j} - (x^* + j\alpha_i)|\leq\xi_i |\alpha_i|. \end{equation} We will aim to have $\xi_i$ small; the exact bound will be established inductively. To simplify the notation we assume $C\geq 1$ (increasing $C$ preserves~\eqref{oooz}) and $\tau_0<1/100$ (decreasing $\tau_0$ preserves~\eqref{oooz}). We start with ${\cal T}_{0,0}={\cal T}_2$ and ${\cal T}_{0,1}={\cal T}_1$ where ${\cal T}_1,{\cal T}_2$ are the field gadgets guaranteed by Lemma~\ref{lem:rr44f} with parameters $\epsilon_2=\tau_0(\omega^*)^{2Q}/(C^2 9^Q)$, $\epsilon_1=\epsilon_2^2$. Note that we satisfy~\eqref{suho} with $\alpha_0=R_{0,1}$ and $\xi_0 = \epsilon_2$. Suppose we constructed ${\cal T}_{i,0}, \dots, {\cal T}_{i,2^i}$ and $\xi_i\leq 3^i\xi_0<1/100$. For $j\in\{0,\dots,2^{i+1}\}$ we let ${\cal T}_{i+1,j}$ be obtained from ${\cal T}_{i,k}$ and ${\cal T}_{i,\ell}$ where $k+\ell=j$ (any choice of $k$ and $\ell$ is fine). We let $\alpha_{i+1}=-\omega^*\alpha_i$. From~\eqref{oooz} we have $$ \big| R_{i+1,j} - \big(x^* - \omega^*\big( (R_{i,k}-x^*) + (R_{i,\ell}-x^*) \big)\big) \big| \leq C (2^{i+1} |\alpha_i|) ^2, $$ which combined with~\eqref{suho} for $R_{i,k}$ and $R_{i,\ell}$ implies \begin{equation}\label{suho2} |R_{i+1,j} - (x^* + j\alpha_{i+1})|\leq C 2^{2i+2} |\alpha_i| \xi_0 \xi_i + 2 \xi_i \omega^* |\alpha_i| \leq 3 \xi_i |\alpha_{i+1}|, \end{equation} where in the first inequality we used $|\alpha_i|\leq |\alpha_0|\leq\epsilon_1 = (\xi_0)^2\leq \xi_0 \xi_i$. Hence we have ${\cal T}_{i+1,0}, \dots, {\cal T}_{i+1,2^{i+1}}$ that satisfy~\eqref{suho} with $\xi_{i+1}\leq 3^{i+1}\xi_0<1/100$. Our final family of field gadgets is ${\cal T}_{Q,i},i\in\{0,\dots,2^Q\}$ and ${\cal T}_{Q-1,i}, i\in\{0,\dots,2^{Q-1}\}$ (the reason we take field gadgets for two values of the first index is to cover both sides of $x^*$; note that $\alpha_i$'s alternate sign). We take $\tau = 2^{Q-1}\omega^*|\alpha_{Q}|$. Let $x\in [x^*-\tau,x^*+\tau]$. If the sign of $x-x^*$ agrees with the sign of $\alpha_Q$ we let $k = \lfloor (x-x^*)/\alpha_Q\rfloor$ (note $0\leq k\leq 2^{Q-1}$) and take the tree ${\cal T}_{Q,k}$. We have \begin{equation}\label{uuuup} | R_{Q,k} - (x^* + \alpha_Q k) | \leq (1/100) |\alpha_Q| \end{equation} and hence \begin{equation}\label{uuuuq} | R_{Q,k} - x | \leq 2 |\alpha_Q| \leq 2^{-Q+2} \tau \leq\delta\tau. \end{equation} If the sign of $x-x^*$ agrees with the sign of $\alpha_{Q-1}$ we let $k = \lfloor (x-x^*)/\alpha_{Q-1}\rfloor$ (note $0\leq k\leq 2^{Q-1}$) and take the tree ${\cal T}_{Q-1,k}$. The argument is analogous to~\eqref{uuuup} and~\eqref{uuuuq}. \end{proof} \subsection{Proof of Lemmas~\ref{contr} and~\ref{lc}}\label{sec:contr} \begin{proof}[Proof of Lemma~\ref{contr}] We will consider the functions $\phi_i$ for $R$ and $R_i$ close to $x^*$. The gradient of $\phi_i(R)$ (viewed as a function of $R$ and $R_i$) is \begin{equation}\label{deri} \left(\frac{\lambda R_i (\beta\gamma-1)}{(\beta +\lambda R R_i)^2}, \frac{\lambda R (\beta\gamma-1)}{(\beta +\lambda R R_i)^2}\right), \end{equation} so we let $R_i=R=x^*$ in~\eqref{deri} then we obtain that the gradient of $\phi_i$ at $(x^*,x^*)$ is $(\omega^*,\omega^*)$, since \begin{equation*} \frac{\lambda x^* (\beta\gamma-1)}{(\beta +\lambda (x^*)^2)^2} = \omega^*. \end{equation*} We therefore obtain the following linear approximation (using Taylor's theorem) of $\phi_i$ around $x^*$. There exists $C$ such that for any sufficiently small $\tau>0$ the following is true. Suppose $R_i = x^*+y_i$ and $R = x^* + y$ where $|y_i|\leq\tau$ and $|y|\leq \tau$. Then \begin{equation}\label{bou1} | \phi_i(R) - (x^* + \omega^*(y_i + y) )| \leq C \tau^2 \end{equation} and \begin{equation}\label{bou2} | \phi_i'(R) - \omega^* | \leq C |\tau|. \end{equation} We will choose $\tau>0$ small enough so that \begin{equation}\label{tab} \tau < \frac{|\omega^*|(1-|\omega^*|)}{100 C}. \end{equation} Recall that $|\omega^*|<1$ and hence~\eqref{bou2} implies that for every $\tau>0$ small enough we have that for $R_i\in [x^*-\tau,x^*+\tau]$ we have that the map $\phi_i$ on the interval \begin{equation}\tag{\ref{idef2}} I' = \Big[x^* - 2 \tau \frac{|\omega^*|}{1-|\omega^*|}, x^* + 2 \tau \frac{|\omega^*|}{1-|\omega^*|}\Big] \end{equation} is uniformly contracting, using also Lemma~\ref{lem1}. The bound on $\omega(R)$ follows from $\omega(x^*)<1$ (see Lemma~\ref{lem1}). This proves the first two inequalities in the lemma. For the third inequality, consider $R_i\in [x^*-\tau,x^*+\tau]$ and let $R_i = x^* + y_i$, so that $|y_i|\leq\tau$. Let also $R= x^* + y$; then, since $R\in I'$, we have $|y|\leq 2 \tau \frac{|\omega^*|}{1-|\omega^*|}$. From~\eqref{bou1} we have $$ |\phi_i(R) - x^*| \leq C \tau^2 + \left(\tau + 2 \tau \frac{|\omega^*|}{1-|\omega^*|}\right)|\omega^*|. $$ To prove the lemma it is enough to show \begin{equation}\label{mapr} C \tau^2 + \left(\tau + 2 \tau \frac{|\omega^*|}{1-|\omega^*|}\right)|\omega^*| \leq 2 \tau \frac{|\omega^*|}{1-|\omega^*|}. \end{equation} Equation~\eqref{mapr} is equivalent to $C\tau^2 \leq 2\tau |\omega^*|$, which follows from our choice of $\tau$ in~\eqref{tab}. \end{proof} \begin{proof}[Proof of Lemma~\ref{lc}] Let $x=(x_1+x_2)/(2\omega)$. Note that $x\in [x^*-\tau,x^*+\tau]$. Let $R_i$ be the effective field of the field gadget guaranteed by Lemma~\ref{led}, that is, $|R_i - x|\leq \tau\delta$. We will show \begin{equation}\label{eop} \phi_i( x^* + |\omega|\tau/2) < x_1 \quad\mbox{and}\quad x_2 < \phi_i( x^* - |\omega|\tau/2). \end{equation} Using~\eqref{bou1} we have \begin{align} \phi_i (x^* + |\omega|\tau/2) - x_1 \leq x^* + \omega( (R_i-x^*) + |\omega|\tau/2 ) - x_1 + C|\tau|^2 \leq \\ x^* + |\omega| \tau\delta + \omega( (x-x^*) + |\omega|\tau/2 ) - x_1 + C|\tau|^2 \leq 2 |\omega| \tau\delta + \omega |\omega|\tau/2 + C|\tau|^2 <0, \end{align} the last inequality is true for $\tau$ satisfying~\eqref{tab} and $\delta<|\omega|/100$ (the negative middle term ``overwhelms'' the remaining positive terms). The second inequality in~\eqref{eop} follows the same argument yielding \[\phi_i (x^* - |\omega|\tau/2) - x_2 \geq - 2 |\omega| \tau\delta - \omega |\omega|\tau/2 - C|\tau|^2 > 0.\qedhere\] \end{proof} \subsection{Proof of Lemma~\ref{case2}}\label{sec:case2} In this section, we consider Case 2 and prove Lemma~\ref{case2}. We first argue that the maps ${\cal F}_{x,t}$ are getting ``flat'' as $t$ goes to infinity. \begin{lemma}\label{shrink} There exist constants $C<1,D<1$ and $C'>0,D'>0$ such that for any $x\in I$ any $t\geq 0$ and any $(f,g)\in{\cal F}_{x,t}$ we have \begin{equation}\label{ee1} \max_{R,R'\in I'} | f(R) - f(R') | \leq C' C^t. \end{equation} and \begin{equation}\label{ee2} \max_{R,R'\in I', M,M'\in J} | g(R,M) - g(R',M') |\leq D' D^t. \end{equation} \end{lemma} \begin{proof} We will prove the lemma by induction on $t$. Consider $(f,g)\in {\cal F}_{x,t}$. Let $i$ be such that $x\in\phi_i^{-1}(I)$ and $(\hat{f},\hat{g})\in {\cal F}_{\phi_i^{-1}(x),t-1}$ be such that $$f(R) = \phi_i(\hat{f}(R))\quad\mbox{and}\quad g(R,M)=\psi_i(\hat{f}(R),\hat{g}(R,M)).$$ Note that $\hat{f}(R)\in I'$ and $\hat{f}(R')$ (see Lemma~\ref{contr}). Recall that~$\phi_i$ is contracting on $I'$ (see Lemma~\ref{contr}), hence \begin{equation}\label{ttty} | f(R) - f(R') | = |\phi_i(\hat{f}(R)) - \phi_i(\hat{f}(R'))| \leq C | \hat{f}(R) - \hat{f}(R') | \leq C' C^{t}. \end{equation} We have $$ g(R,M) = 1-\omega(f(R))\Big( \hat{g}(f(R),M) + M_i - 1\Big)\quad\mbox{and}\quad g(R',M') = 1-\omega(f(R'))\Big( \hat{g}(f(R'),M') + M_i - 1\Big). $$ Hence \begin{equation}\label{uuu7} \begin{aligned} g(R,M)- g(R',M') &= \big(\omega(f(R'))-\omega(f(R))\big)\big(M_i-1 + \hat{g}(f(R'),M')\big)\\ &\hskip 3.5cm + \omega(f(R)) \Big(\hat{g}(f(R'),M')-\hat{g}(f(R),M)\Big). \end{aligned} \end{equation} We will use~\eqref{ttty} to bound the first term in the final expression of~\eqref{uuu7}; the second term will be bounded by induction. Note that the function $\omega(x)$ on $I'$ has a bounded derivative. Further note that $M_i$ and $\hat{g}(f(R'),M')$ are in $J'$. Hence there exists a constant $K$ such that \begin{equation}\label{ooooq} \|(\omega(f(R'))-\omega(f(R)))(M_i-1 + \hat{g}(f(R'),M'))\| \leq K |f(R')-f(R) \leq K C' C^t. \end{equation} We can now take $D>\max\{C,C_{\mathrm{max}}\}$ and $D' = K C' D/(D-C_{\mathrm{max}})$. Then we have \[| g(R,M)- g(R',M') | \leq K C' C^t + Q D' D^{t-1} \leq D' D^t.\qedhere\] \end{proof} We can now prove Lemma~\ref{yyyqw}. \begin{proof}[Proof of Lemma~\ref{yyyqw}] The lemma follows from~\eqref{ee1} and the fact that $x\in f(I)$. \end{proof} \begin{proof}[Proof of Lemma~\ref{case2}] Let $L_x$ be the intersection of $g(I'\times J)$ for all $(f,g)\in {\cal F}_{x,t}$ for all $t\geq 0$. By Helly's theorem $L_x$ is non-empty. By Lemma~\ref{shrink} we have that $L$ consists of a single point $\ell$. Let $F(x)=\ell$. Lemma~\ref{shrink} also implies~\eqref{close} for every $R\in I'$ and every $M\in J$ and $t$ large enough. We have the following observation about the function $F$. If $\phi_i(y)=x$ and $x,y\in I$ then \begin{equation}\label{eq4} F(x) = 1 - \omega(x) ( F(y) + M_i - 1). \end{equation} To prove~\eqref{eq4} note that if we take $(f,g)\in{\cal F}_{y,t}$ then we have $(f_1,g_1)\in{\cal F}_{x,t+1}$ where $$g_1(R,M) = \psi_i(f(R), g(R,M)) = 1 - \omega(\phi_i(f(R)))(g(R,M) + M_i - 1).$$ Note that as $t$ goes to infinity we have that $f(R)$ goes to $y$, $\phi_i(f(R))$ goes to $x$, $g(R,M)$ goes to $F(y)$ and $g_1(R,M)$ goes to $F(x)$ (for any $R\in I'$ and $M\in J$) and hence~\eqref{eq4} holds. Now we argue continuity of $F$. We will show that for $x_1,x_2\in I$ we have for some $c\in (0,1)$ \begin{equation}\label{equ2} |F(x_1) - F(x_2)|\leq C |x_1 - x_2|^{c}. \end{equation} We will prove~\eqref{equ2} by induction on $\lfloor\log_{C_{\mathrm{max}}} |x_1-x_2| \rfloor$, where $C_{\mathrm{max}}$ is the constant from Lemma~\ref{contr}. The base case is when $|x_1-x_2|\geq |\omega|\tau\delta/2$. Since $F(x_1),F(x_2)\in J$ we have $$|F(x_1)-F(x_2)|\leq 2 T \leq C |\omega|\tau\delta/2 \leq C (|\omega|\tau\delta/2)^c \leq C |x_1-x_2|^c,$$ where we choose $C\geq 4T/(|\omega|\tau\delta)$. Now we proceed to the induction step. Let $x_1,x_2$ be such that $|x_1-x_2|\leq |\omega|\tau\delta/2$. By Lemma~\ref{lc} there exists $\phi_i$ such that both $x_1,x_2$ are in $\phi_i(I)$. Let $y_1=\phi_i^{-1}(x_1)$ and $y_2=\phi_i^{-1}(x_2)$. By Lemma~\ref{contr} we have $$(1/C_{\mathrm{max}})|x_1 - x_2| \leq |y_1-y_2|\leq (1/C_{\mathrm{min}})|x_1 - x_2|.$$ Note that $$\lfloor\log_{C_{\mathrm{max}}} |y_1-y_2| \rfloor < \lfloor\log_{C_{\mathrm{max}}} |x_1-x_2| \rfloor.$$ From equation~\eqref{eq4} we have \begin{equation}\label{eq6} F(x_1) - F(x_2) = (F(y_1) + M_i - 1 ) (\omega(x_2)-\omega(x_1)) - \omega(x_2) (F(y_1) - F(y_2)). \end{equation} Note that the function $\omega(x)$ on $I'$ has a bounded derivative. Further note that $M_i$ and $F(y_1)$ are in $J'$. Hence there exists a constant $K$ such that \begin{equation}\label{eq7} | (F(y_1) + M_i - 1 ) (\omega(x_2)-\omega(x_1)) | \leq K |x_2 - x_1|. \end{equation} Hence \begin{equation}\label{ttyyy} |F(x_1) - F(x_2)|\leq K |x_2 - x_1| + C_{\mathrm{max}} C |y_2 - y_1|^c \leq \left( K + C \frac{C_{\mathrm{max}}}{C_{\mathrm{min}}^c}\right) |x_2 - x_1|^c. \end{equation} We will choose $c\in (0,1)$ such that $C_{\mathrm{min}}^c > C_{\mathrm{max}}$ (such $c\in (0,1)$ exists since $C_{\mathrm{min}}, C_{\mathrm{max}} \in (0,1)$. We then choose $C$ such that $C (\frac{C_{\mathrm{max}}}{C_{\mathrm{min}}^c}-1) + K \leq 0$. For our choice of $c\in (0,1)$ and $C$ we can bound~\eqref{ttyyy} by $C |x_2 - x_1|^c$ completing the induction step. \end{proof} \subsection{Obtaining an infinite sequence of pairs of field gadgets}\label{sec:vanilla} In this section, we prove Lemma~\ref{lem:vanilla}. \begin{proof}[Proof of Lemma~\ref{lem:vanilla}] For $j=0$, we set $\mathcal{T}_{1,0}=\mathcal{T}_1,\mathcal{T}_{2,0}=\mathcal{T}_2$. For $j\geq 1$, we proceed inductively. For $i\in \{1,2\}$, we construct $\mathcal{T}_{i,j+1}$ by just combining $\mathcal{T}_{i,j}$ with the degenerate tree of Example~\ref{eee} according to Lemma~\ref{lem1}; we then have that \[R_{i,{j+1}}=\frac{1+\gamma\lambda R_{i,j}}{\beta+\lambda R_{i,j}}, \qquad M_{i,j+1} = 1 - \omega(R_{i,j}) M_{i,j}.\] Since $R_{1,j}=R_{2,j}$ and $M_{1,j}\neq M_{2,j}$, we therefore have that $R_{1,{j+1}}=R_{2,{j+1}}$ and $M_{1,j+1}\neq M_{2,j+1}$ as well. The function $f(x)=\frac{1+\gamma\lambda x}{\beta+\lambda x}$ has a unique fixpoint $x^*$ in the interval $(\beta,1/\gamma)$ and for any starting point $x_0\in (\beta,1/\gamma)$ with $x_0\neq x^*$, repeated application of $f$ produces $x_i$'s that are getting strictly closer to $x^*$. It follows that the sequence $\{R_{1,j}\}$ constructed above, and hence $\{R_{2,j}\}$ as well, has pairwise distinct elements except for the case that $R_{1}=R_{2}=x^*$. In this case, we let $\mathcal{T}_{i,0}$ to be the field gadget obtained by combining two copies of $\mathcal{T}_i$ according to Lemma~\ref{lem1} and proceed as before. Note that whenever $x^*\neq 1$, we also have that $R_{i,0}\neq x^*$ as needed since \[R_{i,0} =\frac{1+\gamma\lambda (x^*)^2}{\beta+\lambda (x^*)^2 }\neq f(x^*)=x^*,\] where the disequality holds because $x^*\neq 1$. We also have that $R_{1,0}=R_{2,0}$ and $M_{1,0}\neq M_{2,0}$ since, for $i\in \{1,2\}$, $M_{i,0}=1-\omega(R_{i,0})(2M_{i}-1)$ and $M_1\neq M_2$. Finally, in the case that $x^*=1$, which corresponds to $\lambda=\frac{1-\beta}{1-\gamma}$ for $\beta,\gamma\in(0,1)$ and $\beta\neq \gamma$, we let $\mathcal{T}_{i,0}$ to be the field gadget obtained by combining, according to Lemma~\ref{lem1}, $\mathcal{T}_i$ and the field gadget $\mathcal{T}$ of Lemma~\ref{lem:triangle}. Then, we have that $R_{i,0}\neq x^*$ as needed since \[R_{i,0} =\frac{1+\gamma\lambda R}{\beta+\lambda R }\neq 1,\] since the effective field $R$ of $\mathcal{T}$ satisfies $R\neq 1$ by Lemma~\ref{lem:triangle}. We also have that $R_{1,0}=R_{2,0}$ and $M_{1,0}\neq M_{2,0}$ since, for $i\in \{1,2\}$, $M_{i,0}=1-\omega(R_{i,0})(M_{i}+M-1)$ and $M_1\neq M_2$, where $M$ is the magnetization gap of $\mathcal{T}$. This finishes the proof of Lemma~\ref{lem:vanilla}. \end{proof} \section{Proofs of the remaining inapproximability results} With all the field-gadget constructions in place, we now give/finish the proofs of the remaining inapproximability results. \subsection{The bipartite ``phase-gadget'' of Sly and Sun}\label{sec:SlySun} Here, we state more precisely the properties of the bipartite phase-gadgets that we described in Section~\ref{sec:phase-gadget}. Recall that a graph $G\in \mathcal{G}^{\ell}_{n}$ is an almost-$\Delta$-regular bipartite graph with $n$ vertices on its side and $\ell$ ``ports'' of degree $\Delta-1$, which will be used to connect distinct copies of gadgets. Recall also that for $\sigma: U^\textup{\texttt{+}}\cup U^\textup{\texttt{-}}\rightarrow \{0,1\}$, we define the \emph{phase} $\mathcal{Y}(\sigma)$ of the configuration $\sigma$ as the side which has the most occupied vertices under $\sigma$, i.e., \[\mathcal{Y}(\sigma)=\begin{cases} \textup{\texttt{+}} & \mbox{ if } |\sigma_{U^\textup{\texttt{+}}}|\geq |\sigma_{U^\textup{\texttt{-}}}|,\\ \textup{\texttt{-}}& \mbox{otherwise}. \end{cases}\] \begin{lemma}[{\cite[Section 4.1]{SlySun}}]\label{lem:SlySun} Let $\Delta\geq 3$ and $(\beta,\gamma,\lambda)\in \ensuremath{\mathcal{U}}_{\Delta}$. There exist real numbers $q^\textup{\texttt{+}}, q^\textup{\texttt{-}}\in (0,1)$ with $q^\textup{\texttt{-}}<q^\textup{\texttt{+}}$ such that the following hold for every integer $\ell\geq 0$, real $\epsilon>0$, and all sufficiently large integers $n$. There exists a graph $G\in \mathcal{G}^{\ell}_{n}$ such that the Gibbs distribution $\mu=\mu_{G;\beta,\gamma, \lambda}$ satisfies the following: \begin{enumerate} \item \label{it:balancedphases} $\tfrac{1-\epsilon}{2}\leq\mu(\mathcal{Y}(\sigma)=\textup{\texttt{\textpm}})\leq \tfrac{1+\epsilon}{2}$. \item \label{it:approxindep}for every $\tau: W\rightarrow \{0,1\}$, we have that $(1-\epsilon)Q_W^{\textup{\texttt{\textpm}}}(\tau)\leq \mu(\sigma_W=\tau\mid \mathcal{Y}(\sigma)=\textup{\texttt{\textpm}})\leq (1+ \epsilon)Q_W^{\textup{\texttt{\textpm}}}(\tau)$, where $Q^\textup{\texttt{+}}_W(\cdot), Q^\textup{\texttt{-}}_W(\cdot)$ are product distributiond defined by \begin{equation}\label{eq:product} Q^\textup{\texttt{\textpm}}_W(\tau)= (q^\textup{\texttt{\textpm}})^{|\tau^{-1}(1) \cap W^\textup{\texttt{+}}|}(1-q^\textup{\texttt{\textpm}})^{|\tau^{-1}(0) \cap W^\textup{\texttt{+}}|}(q^\mip)^{|\tau^{-1}(1) \cap W^\textup{\texttt{-}}|}(1-q^\mip)^{|\tau^{-1}(0) \cap W^\textup{\texttt{-}}|}. \end{equation} \end{enumerate} \end{lemma} \begin{remark}\label{rem:gadgetcompute} We remark that for any fixed $\epsilon>0$ and $\ell\geq 1$, we can find $n$ and $G\in \mathcal{G}^{\ell}_{n}$ satisfying Items~\ref{it:balancedphases} and~\ref{it:approxindep} by brute force in constant time. Namely, the values of $q^\textup{\texttt{+}},q^\textup{\texttt{-}}$ can be obtained by solving the system of equations $x=\lambda\left(\frac{ \beta y+1}{y+\gamma}\right)^{\Delta-1},y=\lambda\left(\frac{ \beta x+1}{x+\gamma}\right)^{\Delta-1}$ for $x,y\in (0,1)$; it can be shown that for $(\beta,\gamma,\lambda)\in \ensuremath{\mathcal{U}}_{\Delta}$ this system has a unique solution with $x<y$ (see, e.g., \cite[Lemma 7]{GSVIsing}, or \cite[Section 6.2]{MSW07}). Using these values, for any constant $n$ and any graph $G\in \mathcal{G}^{r}_{n}$ we can check whether Items~\ref{it:balancedphases} and~\ref{it:approxindep} hold in constant time, and therefore find $G$ satisfying Lemma~\ref{lem:SlySun}. \end{remark} \subsection{Preliminaries} Let $G=(V,E)$ be a graph and $(\beta,\gamma)$ be antiferromagnetic. It will sometimes be convenient to consider models where instead of a uniform field $\lambda$ over vertices of $G$, we allow vertices to have their ``own'' field. More precisely, for a field vector $\ensuremath{\boldsymbol{\lambda}}=\{\lambda_v\}_{v\in V}$, we define \begin{equation}\label{eq:multi} \mu_{G;\beta,\gamma,\ensuremath{\boldsymbol{\lambda}}}(\sigma)=\frac{w_{G;\beta,\gamma,\ensuremath{\boldsymbol{\lambda}}}(\sigma)}{Z_{G;\beta,\gamma,\ensuremath{\boldsymbol{\lambda}}}}, \mbox{ where \ \ }w_{G;\beta,\gamma,\ensuremath{\boldsymbol{\lambda}}}(\sigma):=\lambda^{|\sigma|}\beta^{m_{0}(\sigma)}\gamma^{m_{1}(\sigma)}\prod_{v\in V;\, \sigma(v)=1} \lambda_v. \end{equation} \begin{lemma}\label{lem:perturb} Let $(\beta,\gamma)$ be antiferromagnetic and $\lambda,\lambda_1,\lambda_2>0$. Let $G=(V,E)$ be a graph and $S\subseteq V$. For $i\in \{1,2\}$, let $\ensuremath{\boldsymbol{\lambda}}_i$ be the field vector on $V$, where every $v\in S$ has field $\lambda_i$, whereas every $v\in V\backslash S$ has field $\lambda$. Let $\mu_i$ be the Gibbs distributions on $G$, respectively, with parameters $\beta,\gamma, \ensuremath{\boldsymbol{\lambda}}_i$. Then, for every $v\in V$, it holds that \[\big|\ensuremath{\mathbf{E}}_{\sigma\sim \mu_2}[\sigma(v)]-\ensuremath{\mathbf{E}}_{\sigma\sim \mu_1}[\sigma(v)]\big|\leq 2|S|\, \Big|\frac{\lambda_2}{\lambda_1}-1\Big|.\] \end{lemma} \begin{proof} Assume first that $\lambda_1\geq \lambda_2$. For $v\in V$, let \[Z^{\mathsf{in}}_{F,v}(\ensuremath{\boldsymbol{\lambda}}_i):= \sum_{\sigma:V\rightarrow \{0,1\}; \, \sigma(v)=1} w_{G;\beta,\gamma,\ensuremath{\boldsymbol{\lambda}}_i}(\sigma),\quad Z^{\mathsf{in}}_{G}(\ensuremath{\boldsymbol{\lambda}}_i):= Z^{\mathsf{in}}_{G;\beta,\gamma,\ensuremath{\boldsymbol{\lambda}}_i},\] so that $\ensuremath{\mathbf{E}}_{\sigma\sim \mu_i}[\sigma(v)]=\frac{Z^{\mathsf{in}}_{G,v}(\ensuremath{\boldsymbol{\lambda}}_i)}{Z_{G}(\ensuremath{\boldsymbol{\lambda}}_i)}$. Therefore, \begin{align}\label{eq:4tg4ggteewe} \ensuremath{\mathbf{E}}_{\sigma\sim \mu_1}[\sigma(v)]-\ensuremath{\mathbf{E}}_{\sigma\sim \mu_2}[\sigma(v)]=\frac{Z^{\mathsf{in}}_{G,v}(\ensuremath{\boldsymbol{\lambda}}_1)-Z^{\mathsf{in}}_{G,v}(\ensuremath{\boldsymbol{\lambda}}_2)}{Z_{G}(\ensuremath{\boldsymbol{\lambda}}_1)}+\frac{Z^{\mathsf{in}}_{G,v}(\ensuremath{\boldsymbol{\lambda}}_2)}{Z_{G}(\ensuremath{\boldsymbol{\lambda}}_2)}\frac{Z_G(\ensuremath{\boldsymbol{\lambda}}_2)-Z_{G}(\ensuremath{\boldsymbol{\lambda}}_1)}{Z_{G}(\ensuremath{\boldsymbol{\lambda}}_1)} \end{align} For arbitrary $\sigma: V\rightarrow \{0,1\}$, we have that \[\frac{w_{G;\beta,\gamma,\ensuremath{\boldsymbol{\lambda}}_1}(\sigma)-w_{G;\beta,\gamma,\ensuremath{\boldsymbol{\lambda}}_2}(\sigma)}{w_{G;\beta,\gamma,\ensuremath{\boldsymbol{\lambda}}_1}(\sigma)}=\frac{\lambda_1^{|\sigma_S|}- \lambda_2^{|\sigma_S|}}{\lambda_1^{|\sigma_S|}}\leq |S|\Big(1-\frac{\lambda_2}{\lambda_1}\Big).\] From this, it follows that \[\Big|\frac{Z^{\mathsf{in}}_{G,v}(\ensuremath{\boldsymbol{\lambda}}_1)-Z^{\mathsf{in}}_{G,v}(\ensuremath{\boldsymbol{\lambda}}_2)}{Z_{G}(\ensuremath{\boldsymbol{\lambda}}_1)}\Big|\leq |S|\Big(1-\frac{\lambda_2}{\lambda_1}\Big), \quad \Big|\frac{Z_G(\ensuremath{\boldsymbol{\lambda}}_2)-Z_{G}(\ensuremath{\boldsymbol{\lambda}}_1)}{Z_{G}(\ensuremath{\boldsymbol{\lambda}}_1)}\Big|\leq |S|\Big(1-\frac{\lambda_2}{\lambda_1}\Big).\] Hence, by taking absolute values in \eqref{eq:4tg4ggteewe} and using $\frac{Z^{\mathsf{in}}_{G,v}(\ensuremath{\boldsymbol{\lambda}}_2)}{Z_{G}(\ensuremath{\boldsymbol{\lambda}}_2)}\leq 1$ and the triangle inequality, we obtain \[\big|\ensuremath{\mathbf{E}}_{\sigma\sim \mu_1}[\sigma(v)]-\ensuremath{\mathbf{E}}_{\sigma\sim \mu_2}[\sigma(v)]\big|\leq 2|S| \Big(1-\frac{\lambda_2}{\lambda_1}\Big),\] finishing the proof for $\lambda_1\geq \lambda_2$. The case $\lambda_1<\lambda_2$ follows from the previous case since \[\big|\ensuremath{\mathbf{E}}_{\sigma\sim \mu_1}[\sigma(v)]-\ensuremath{\mathbf{E}}_{\sigma\sim \mu_2}[\sigma(v)]\big|\leq 2|S| \Big(1-\frac{\lambda_1}{\lambda_2}\Big)\leq 2|S| \Big(\frac{\lambda_2}{\lambda_1}-1\Big).\qedhere\] \end{proof} \subsection{Proof of Lemma~\ref{lem:maingadget}}\label{sec:maingadget} We start with the proof of Lemma~\ref{lem:maingadget}. \begin{proof}[Proof of Lemma~\ref{lem:maingadget}] We first prove the bounds on $\ensuremath{\mathcal{M}}_{\beta,\gamma,\lambda}(H^{k}_{G,\mathcal{T}})$. For an edge $e=(u,v)\in E_H$ and $i\in [k]$, let $P^{i,\textup{\texttt{+}}}_{e},P^{i,\textup{\texttt{-}}}_{e}$ be the $i$-th paths connecting the $\textup{\texttt{+}}/\textup{\texttt{+}}$ and $\textup{\texttt{-}}/\textup{\texttt{-}}$ sides of the gadgets $G_u,G_v$, respectively. Let the (two) internal vertices of the path $P^{i,\textup{\texttt{\textpm}}}_{e}$ be $t^{i,\textup{\texttt{\textpm}}}_{e,1}$ and $t^{i,\textup{\texttt{\textpm}}}_{e,2}$. For $j=1,2$ denote by $\mathcal{T}^{i,\textup{\texttt{\textpm}}}_{e,j}$ the copy of $\mathcal{T}$ that was appended to $t^{i,\textup{\texttt{\textpm}}}_{e,j}$. Note that the vertex set of $H^{k}_{G,\mathcal{T}}$ is the disjoint union of $V(\widehat{H}^{k}_{G})$ and $V(\mathcal{T}^{i,s}_{e,j})$ for $e\in E(H), s\in\{\textup{\texttt{+}},\textup{\texttt{-}}\}, i\in [k], j\in \{1,2\}$, so we have \begin{equation}\label{eq:MHkGT} \ensuremath{\mathcal{M}}_{\beta,\gamma,\lambda}(H^{k}_{G,\mathcal{T}})=\ensuremath{\mathbf{E}}_{\sigma\sim \mu}\big[\big|\sigma_{V(\widehat{H}^{k}_{G})}\big|\big]+\sum_{e\in E(H)}\sum_{s\in\{\textup{\texttt{+}},\textup{\texttt{-}}\}}\sum_{i\in [k]}\sum_{j\in \{1,2\}}\ensuremath{\mathbf{E}}_{\sigma\sim \mu}\Big[\big|\sigma_{V(\mathcal{T}^{i,s}_{e,j})}\big|\Big]. \end{equation} Fix arbitrary $e\in E(H), s\in\{\textup{\texttt{+}},\textup{\texttt{-}}\}, i\in [k], j\in \{1,2\}$, and for convenience let $\mu^{i,s}_{e,j}$ denote the Gibbs distribution on $\mathcal{T}^{i,s}_{e,j}$ with parameters $\beta,\gamma,\lambda$. Note that conditioned on the spin of $t^{i,s}_{e,j}$, the distribution $\mu$ factorizes; more precisely, for $\tau: V(\mathcal{T}^{i,s}_{e,j})\rightarrow \{0,1\}$ and $w\in \{0,1\}$, we have \[\mu\Big(\sigma_{V(\mathcal{T}^{i,s}_{e,j})}=\tau\mid \sigma(t^{i,s}_{e,j})=w\Big)=\mu^{i,s}_{e,j}(\tau\mid \tau(t^{i,s}_{e,j})=w).\] It follows that \begin{align*} \ensuremath{\mathbf{E}}_{\sigma\sim \mu}\Big[\big|\sigma_{V(\mathcal{T}^{i,s}_{e,j})}\big|\Big]&=\sum_{w\in\{0,1\}}\mu\big(\sigma(t^{i,s}_{e,j}\big)=1)\, \ensuremath{\mathbf{E}}_{\tau\sim \mu^{i,s}_{e,j}}\big[\,|\tau|\mid \tau\big(t^{i,s}_{e,j}\big)=w\big]\\ &=M\,\ensuremath{\mathbf{E}}_{\sigma\sim \mu}[\sigma(t^{i,s}_{e,j})]+\mathcal{A}', \end{align*} where the last equality follows by writing $\mu\big(\sigma(t^{i,s}_{e,j})=0\big)=1-\mu\big(\sigma(t^{i,s}_{e,j})=1\big)=1-\ensuremath{\mathbf{E}}_{\sigma\sim \mu}[\sigma(t^{i,s}_{e,j})]$. Plugging into \eqref{eq:MHkGT}, we obtain \begin{equation}\label{eq:4g4t4g56yttere5} \ensuremath{\mathcal{M}}_{\beta,\gamma,\lambda}(H^{k}_{G,\mathcal{T}})=4k\mathcal{A}'|E(H)|+\ensuremath{\mathbf{E}}_{\sigma\sim \mu}\big[\big|\sigma_{V(\widehat{H}^{k}_{G})}\big|\big]+M \sum_{e\in E(H)}\sum_{s\in\{\textup{\texttt{+}},\textup{\texttt{-}}\}}\sum_{i\in [k]}M^{i,s}_{e}, \end{equation} where, for $e\in E(H)$, $i\in [k]$ and $s\in \{\textup{\texttt{+}},\textup{\texttt{-}}\}$, \[M^{i,s}_{e}:=\ensuremath{\mathbf{E}}_{\sigma\sim \mu}[\sigma(t^{i,s}_{e,1})+\sigma(t^{i,s}_{e,2})].\] We can expand $M^{i,s}_{e}$ accoding to the configuration on the ports $W^{i,s}_e:= \{w^{i,s}_{u},w^{i,s}_{v}\}$, i.e, \begin{equation}\label{eq:4tg5tb5yhyhnh} M^{i,s}_{e}=\sum_{\tau: W^{i,s}_e\rightarrow \{0,1\}} \mu\big(\sigma_{W^{i,s}_e}=\tau\big) \ensuremath{\mathbf{E}}_{\sigma\sim \mu}[\sigma(t^{i,s}_{e,1})+\sigma(t^{i,s}_{e,2})\mid \sigma_{W^{i,s}_e}=\tau]. \end{equation} For convenience, let $\overline{W}^{i,s}_e$ be the set $(W_u\cup W_v)\backslash W^{i,s}_e$, i.e., the set of all ports in the gadgets $G_u,G_v$ other than those in $W^{i,s}_e$. We have \begin{equation}\label{eq:rtb5b5hh5} \mu\big(\sigma_{W^{i,s}_e}=\tau\big)=\sum_{\substack{Y: V(H)\rightarrow \{\textup{\texttt{+}},\textup{\texttt{-}}\};\\\eta:\overline{W}^{i,s}_e\rightarrow \{0,1\}}}\mu\big(\sigma_{W^{i,s}_e}=\tau\mid \widehat{\mathcal{Y}}(\sigma)=Y,\sigma_{\overline{W}^{i,s}_e}=\eta\big)\mu\big(\widehat{\mathcal{Y}}(\sigma)=Y,\sigma_{\overline{W}^{i,s}_e}=\eta\big). \end{equation} Now, observe that $\overline{W}^{i,s}_e$ disconnects the vertices in $U_u\cup U_v$ from the rest of the graph $H^{k}_{G,\mathcal{T}}$, so, conditioned on $\eta:\overline{W}^{i,s}_e\rightarrow \{0,1\}$, the configuration on $W^{i,s}_e$ is distributed according to $\mu_e$, where $\mu_e$ is the Gibbs distribution with parameters $(\beta,\gamma,\lambda)$ on the subgraph of $H^{k}_{G,\mathcal{T}}$ induced by $U_u\cup U_v$. Therefore, for any $Y: V(H)\rightarrow \{\textup{\texttt{+}},\textup{\texttt{-}}\}$ and $\eta:\overline{W}^{i,s}_e\rightarrow \{0,1\}$, we have that \begin{equation}\label{eq:6N6J8R} \mu\big(\sigma_{W^{i,s}_e}=\tau\mid \widehat{\mathcal{Y}}(\sigma)=Y,\sigma_{\overline{W}^{i,s}_e}=\eta\big)=\mu_e\big(\sigma_{W^{i,s}_e}=\tau\mid \mathcal{Y}(\sigma_{U_u})=Y_u, \mathcal{Y}(\sigma_{U_v})=Y_v,\sigma_{\overline{W}^{i,s}_e}=\eta). \end{equation} Since $G_u,G_v$ are copies of $G$, and $G$ satisfies Lemma~\ref{lem:SlySun}, by Item~\ref{it:approxindep} we obtain that $\mu_e\big(\sigma_{W^{i,\textup{\texttt{\textpm}}}_e}=\tau\mid \mathcal{Y}(\sigma_{U_u})=Y_u, \mathcal{Y}(\sigma_{U_v})=Y_v,\sigma_{S_e}=\eta)$ is approximately independent of $\eta$ and within a factor of $(1\pm 8\epsilon)$ from the Gibbs distribution on $P^{i,\textup{\texttt{\textpm}}}_e$ with field vector $\ensuremath{\boldsymbol{\lambda}}_{\textup{\texttt{\textpm}}}(Y_u,Y_v)$ given by \[\lambda_{w^{i,\textup{\texttt{\textpm}}}_u}=\tfrac{q^{\textup{\texttt{\textpm}} Y_u}}{1-q^{\textup{\texttt{\textpm}} Y_u}},\quad \lambda_{t^{i,\textup{\texttt{\textpm}}}_{e,1}}=\lambda_{t^{i,\textup{\texttt{\textpm}}}_{e,2}}=\lambda R,\quad \lambda_{w^{i,\textup{\texttt{\textpm}}}_u}=\tfrac{q^{\textup{\texttt{\textpm}} Y_v}}{1-q^{\textup{\texttt{\textpm}} Y_v}}.\] More precisely, we have \begin{equation}\label{eq:tb5b5h5646} \mu_e\big(\sigma_{W^{i,s}_e}=\tau\mid \mathcal{Y}(\sigma_{U_u})=Y_u, \mathcal{Y}(\sigma_{U_v})=Y_v,\sigma_{\overline{W}^{i,s}_e}=\eta)=(1\pm 8\epsilon)\mu_{P^{i,s}_e; \beta,\gamma,\ensuremath{\boldsymbol{\lambda}}_{s}(Y_u,Y_v)}(\sigma_{W^{i,\textup{\texttt{\textpm}}}_e}=\tau). \end{equation} Combining \eqref{eq:6N6J8R} and \eqref{eq:tb5b5h5646}, and plugging back into \eqref{eq:rtb5b5hh5}, we obtain \[\mu\big(\sigma_{W^{i,s}_e}=\tau\big)=(1\pm 8\epsilon)\sum_{Y: V(H)\rightarrow \{\textup{\texttt{+}},\textup{\texttt{-}}\}}\mu\big(\widehat{\mathcal{Y}}(\sigma)=Y\big)\, \mu_{P^{i,s}_e; \beta,\gamma,\ensuremath{\boldsymbol{\lambda}}_{s}(Y_u,Y_v)}(\sigma_{W^{i,s}_e}=\tau)\] In turn, plugging this back into \eqref{eq:4tg5tb5yhyhnh} yields that \begin{equation}\label{eq:45g54trexxa} M^{i,s}_{e}=(1\pm 8\epsilon)\sum_{Y: V(H)\rightarrow \{\textup{\texttt{+}},\textup{\texttt{-}}\}}\mu\big(\widehat{\mathcal{Y}}(\sigma)=Y\big)\ensuremath{\mathbf{E}}_{\sigma\sim \mu_{P^{i,s}_e; \beta,\gamma,\ensuremath{\boldsymbol{\lambda}}_{s}(Y_u,Y_v)}}[\sigma(t^{i,s}_{e,1})+\sigma(t^{i,s}_{e,2})]. \end{equation} For $s_1,s_2,s_3\in\{\textup{\texttt{+}},\textup{\texttt{-}}\}$, let \[A^{s_1}_{s_2s_3}:=\ensuremath{\mathbf{E}}_{\sigma\sim \mu_{P^{i,s_1}_e; \beta,\gamma,\ensuremath{\boldsymbol{\lambda}}_{s}(s_2,s_3)}}[\sigma(t^{i,s_1}_{e,1})+\sigma(t^{i,s_1}_{e,2})].\] To give expressions for $A^{s_1}_{s_2s_3}$, it will be convenient to consider the following vectors/matrices: \begin{equation}\label{eq:4t4vt4ggyh} \mathbf{q}^{\textup{\texttt{\textpm}}}:=\Big[\begin{smallmatrix} 1-q^\textup{\texttt{\textpm}}\\ q^\textup{\texttt{\textpm}} \end{smallmatrix}\Big], \quad \mathbf{L}(x):=\Big[\begin{smallmatrix} \beta^3+2\beta x+\gamma x^2 & \beta^2 + x(1 + \beta \gamma) + \gamma^2 x^2 \\ \beta^2 + x(1 + \beta \gamma) + \gamma^2 x^2 & \beta + 2\gamma x+ \gamma^2 x^3 \end{smallmatrix}\Big], \quad \begin{array}{c} f_{\textup{\texttt{\textpm}} \textup{\texttt{\textpm}}}(x):=(\mathbf{q}^{\textup{\texttt{\textpm}}})^{\ensuremath{\intercal}}\, \mathbf{L}(x) \mathbf{q}^{\textup{\texttt{\textpm}}}\\ f_{\textup{\texttt{\textpm}} \mip}(x):=(\mathbf{q}^{\textup{\texttt{\textpm}}})^{\ensuremath{\intercal}}\, \mathbf{L}(x) \mathbf{q}^{\mip}\end{array}. \end{equation} where $q^{\textup{\texttt{+}}},q^{\textup{\texttt{-}}}$ are the constants in Lemma~\ref{lem:SlySun}, and recall that $q^{\textup{\texttt{+}}}\neq q^{\textup{\texttt{-}}}$. Roughly, the matrix $\mathbf{L}(x)$ corresponds to the interaction matrix between the endpoints of a path of length 4, whose vertices have vertex fields $1,x,x,1$ respectively. Then, the functions $f_{\textup{\texttt{\textpm}} \textup{\texttt{\textpm}}}(x)$ capture the total weight of configurations on the path, when the endpoints are occupied with probabilities $q^{\textup{\texttt{\textpm}}},q^{\textup{\texttt{\textpm}}}$, respectively; similarly for the functions $f_{\textup{\texttt{\textpm}} \mip}(x)$. \[A^{\textup{\texttt{+}}}_{\textup{\texttt{+}}\pl}=A^{\textup{\texttt{-}}}_{\textup{\texttt{-}}\mi}=\frac{f_{\textup{\texttt{+}} \textup{\texttt{+}}}'(\lambda R)}{f_{\textup{\texttt{+}} \textup{\texttt{+}}}(\lambda R)},\quad A^{\textup{\texttt{-}}}_{\textup{\texttt{+}}\pl}=A^{\textup{\texttt{+}}}_{\textup{\texttt{-}}\mi}=\frac{f_{\textup{\texttt{-}} \textup{\texttt{-}}}'(\lambda R)}{f_{\textup{\texttt{-}} \textup{\texttt{-}}}(\lambda R)}, \quad A^{\textup{\texttt{+}}}_{\textup{\texttt{+}}\textup{\texttt{-}}}=A^{\textup{\texttt{+}}}_{\textup{\texttt{-}}\textup{\texttt{+}}}=A^{\textup{\texttt{-}}}_{\textup{\texttt{-}}\textup{\texttt{+}}}= A^{\textup{\texttt{-}}}_{\textup{\texttt{+}}\textup{\texttt{-}}}=\tfrac{f_{\textup{\texttt{+}} \textup{\texttt{-}}}'(\lambda R)}{f_{\textup{\texttt{+}} \textup{\texttt{-}}}(\lambda R)}=\tfrac{f_{\textup{\texttt{-}} \textup{\texttt{+}}}'(\lambda R)}{f_{\textup{\texttt{-}}\textup{\texttt{+}}}(\lambda R)}.\] Now, let's fix a phase vector $Y:V(H)\rightarrow \{\textup{\texttt{+}},\textup{\texttt{-}}\}$, and compute \begin{equation}\label{eq:34f5646y} \sum_{e=(u,v)\in E(H)}\sum_{s\in\{\textup{\texttt{+}},\textup{\texttt{-}}\}}\sum_{i\in [k]}\ensuremath{\mathbf{E}}_{\sigma\sim \mu_{P^{i,s}_e; \beta,\gamma,\ensuremath{\boldsymbol{\lambda}}_{s}(Y_u,Y_v)}}[\sigma(t^{i,s}_{e,1})+\sigma(t^{i,s}_{e,2})]. \end{equation} where the functions $f_{\textup{\texttt{\textpm}}\plm},f_{\textup{\texttt{\textpm}} \mip}$ are as in \eqref{eq:4t4vt4ggyh}. We have that the contribution from an edge $e=(u,v)$ with $Y_u\neq Y_v$ is $kB$, while the contribution from an edge $e=(u,v)$ with $Y_u= Y_v$ is $kC$, where \[B=A^{\textup{\texttt{+}}}_{\textup{\texttt{+}}\textup{\texttt{-}}}+A^{\textup{\texttt{-}}}_{\textup{\texttt{+}}\textup{\texttt{-}}}=A^{\textup{\texttt{+}}}_{\textup{\texttt{-}}\textup{\texttt{+}}}+A^{\textup{\texttt{-}}}_{\textup{\texttt{-}}\textup{\texttt{+}}}=\tfrac{f_{\textup{\texttt{+}} \textup{\texttt{-}}}'(\lambda R)}{f_{\textup{\texttt{+}} \textup{\texttt{-}}}(\lambda R)}+\tfrac{f_{\textup{\texttt{-}} \textup{\texttt{+}}}'(\lambda R)}{f_{\textup{\texttt{-}}\textup{\texttt{+}}}(\lambda R)}, \quad C=A^{\textup{\texttt{+}}}_{\textup{\texttt{+}}\pl}+A^{\textup{\texttt{-}}}_{\textup{\texttt{+}}\pl}=A^{\textup{\texttt{-}}}_{\textup{\texttt{-}}\mi}+A^{\textup{\texttt{+}}}_{\textup{\texttt{-}}\mi}=\tfrac{f_{\textup{\texttt{+}} \textup{\texttt{+}}}'(\lambda R)}{f_{\textup{\texttt{+}} \textup{\texttt{+}}}(\lambda R)}+\tfrac{f_{\textup{\texttt{-}} \textup{\texttt{-}}}'(\lambda R)}{f_{\textup{\texttt{-}} \textup{\texttt{-}}}(\lambda R)}.\] It follows that the value of the sum in \eqref{eq:34f5646y} is \begin{equation}\label{eq:4tt6gtgrrerrv} k B\, \mathrm{Cut}_H(Y)+k C\big(|E(H)|- \mathrm{Cut}_H(Y)\big)=k (B-C)\mathrm{Cut}_H(Y)+kC |E(H)|. \end{equation} Combining \eqref{eq:45g54trexxa} with \eqref{eq:4g4t4g56yttere5} and using the value of the sum in \eqref{eq:34f5646y} as obtained in \eqref{eq:4tt6gtgrrerrv}, finishes the proof of the bounds on $\ensuremath{\mathcal{M}}_{\beta,\gamma,\lambda}(H^{k}_{G,\mathcal{T}})$. We next prove the bounds on $\textsc{Avg-Cut}_{\mu}(H)$. The upper bound is trivial, so we focus on the lower bound, which is along the same lines as in \cite[Lemma 4.2]{SlySun}. Let $\hat{\mu}$ be the Gibbs distibution on $\widehat{H}^k_G$ and note that this is a product distribution over the gadgets. For convenience, let $\mathbf{L}=\{L_{ij}\}_{i,j\in\{0,1\}}$ denote the (entries of the) matrix $\mathbf{L}(\lambda R)$. For phase configurations $Y:V(H)\rightarrow \{\textup{\texttt{+}},\textup{\texttt{-}}\}$, we have that \[\mu(\hat{\mathcal{Y}}(\sigma)=Y)\propto \hat{\mu}(\hat{\mathcal{Y}}(\sigma)=Y)\sum_{\tau:W\rightarrow \{0,1\}}\hat{\mu}(\sigma_W=\tau\mid \hat{\mathcal{Y}}(\sigma)=Y)\prod_{e=(u,v)\in E(H)}\prod_{s\in \{\textup{\texttt{+}}, \textup{\texttt{-}}\}}\prod_{i\in [k]}L_{\tau(w^{i,s}_u),\tau(w^{i,s}_v)}\] By Items~\ref{it:balancedphases} and~\ref{it:approxindep} of Lemma~\ref{lem:SlySun}, for all $Y:V(H)\rightarrow \{\textup{\texttt{+}},\textup{\texttt{-}}\}$ and $\tau:W\rightarrow \{0,1\}$, it holds that \[\hat{\mu}\big(\hat{\mathcal{Y}}(\sigma)=Y\big)=\Big(\frac{1\pm \epsilon}{2}\Big)^{|V(H)|}, \quad \hat{\mu}(\sigma_W=\tau\mid \hat{\mathcal{Y}}(\sigma)=Y)=(1\pm \epsilon)^{|V(H)|} \prod_{v\in V}Q^{Y_v}_{W_v}(\tau_{W_v}),\] where, for $v\in V(H)$, $Q^{\textup{\texttt{\textpm}}}_{W_v}$ is the product distribution defined in \eqref{eq:product} for the gadget $G_v$. Using that \[\mu(\hat{\mathcal{Y}}(\sigma)=Y)\propto \big(\tfrac{1}{2}\pm\epsilon\big)^{|V(H)|}\prod_{e=(u,v)\in E(H)}\prod_{s\in \{\textup{\texttt{+}},\textup{\texttt{-}}\}}\prod_{i\in [k]}\sum_{\tau:W^{i,s}_{e}\rightarrow \{0,1\}}Q^{Y_u}(\tau(w^{i,s}_u))L_{\tau(w^{i,s}_u),\tau(w^{i,s}_v)}Q^{Y_v}_{W_v}(\tau(w^{i,s}_v)).\] Observe now that $\sum_{\tau:W^{i,s}_e\rightarrow \{0,1\}}Q^{Y_u}_{W_v}(\tau(w^{i,s}_u))L_{\tau(w^{i,s}_u),\tau(w^{i,s}_v)}Q^{Y_v}(\tau(w^{i,s}_v))=(\mathbf{q}^{Y_u})^{\ensuremath{\intercal}} \mathbf{L}\, \mathbf{q}^{Y_v}$, so \[\mu(\hat{\mathcal{Y}}(\sigma)=Y)\propto \big(\tfrac{1}{2}\pm\epsilon\big)^{|V(H)|}\prod_{(u,v)\in E(H); Y_u\neq Y_v}\big(f_{\textup{\texttt{+}} \textup{\texttt{-}}}(\lambda R)f_{\textup{\texttt{-}} \textup{\texttt{+}}}(\lambda R)\big)^{k}\prod_{(u,v)\in E(H); Y_u=Y_v}\big(f_{\textup{\texttt{+}} \textup{\texttt{+}}}(\lambda R)f_{\textup{\texttt{-}} \textup{\texttt{-}}}(\lambda R)\big)^{k}.\] It follows that for \[A:=A(R)=\frac{f_{\textup{\texttt{+}} \textup{\texttt{-}}}(\lambda R)\cdot f_{\textup{\texttt{-}} \textup{\texttt{+}}}(\lambda R)}{f_{\textup{\texttt{-}} \textup{\texttt{-}}}(\lambda R)\cdot f_{\textup{\texttt{+}} \textup{\texttt{+}}}(\lambda R)}, \] we have that \[\mu(\hat{\mathcal{Y}}(\sigma)=Y)\propto \big(\tfrac{1}{2}\pm\epsilon\big)^{|V(H)|}A^{k\mathrm{Cut}_H(Y)}.\] Now note that for $R>0$, we have $A>1$ since $q^{\textup{\texttt{+}}}\neq q^{\textup{\texttt{-}}}$ and for all $x$ we have that \[f_{\textup{\texttt{+}} \textup{\texttt{-}}}(x)\cdot f_{\textup{\texttt{-}} \textup{\texttt{+}}}(x)-f_{\textup{\texttt{+}} \textup{\texttt{+}}}(x)\cdot f_{\textup{\texttt{-}} \textup{\texttt{-}}}(x)=(1-\beta \gamma)^3x^2 (q^{\textup{\texttt{+}}}-q^{\textup{\texttt{-}}})^2.\] Note also that $A(0)=1$, while $B(R)-C(R)=(\log A(R))'$ thus proving that $A(R),B(R),C(R)$ are rational functions of $R$ satisfying \eqref{eq:vv6gvgg}. Let $\hat{K}>1$ be such that $1-\frac{1}{\hat{K}}\leq \frac{4}{k\log A}$. From the estimates above, we have \begin{equation}\label{eq:45gg4fcfr} \mu\Big(\frac{\mathrm{Cut}_H\big(\hat{\mathcal{Y}}(\sigma)\big)}{\textsc{Max-Cut}(H)}\leq \frac{1}{\hat{K}}\Big)\leq \frac{\big(\tfrac{1}{2}+\epsilon\big)^{|V(H)|} 2^{|V(H)|} A^{ \frac{k}{\hat{K}}\textsc{Max-Cut}(H)}}{\big(\tfrac{1}{2}-\epsilon\big)^{|V(H)|}A^{k \textsc{Max-Cut}(H)}}\leq \Big(\frac{1}{2}\Big)^{|V(H)|}, \end{equation} where in the last inequality we used that \[A,\hat{K}>1,\quad \textsc{Max-Cut}(H)\geq \tfrac{1}{2}|E(H)|=\tfrac{3}{4}|V(H)|,\mbox{ and } 2\big(\tfrac{1}{2}+\epsilon\big)/\big(\tfrac{1}{2}-\epsilon\big)\leq 4.\] Since $\textsc{Avg-Cut}_{\mu}(H):=\sum_{Y:V(H)\rightarrow \{\textup{\texttt{+}},\textup{\texttt{-}}\}}\mu\big(\widehat{\mathcal{Y}}(\sigma)=Y\big)|\mathrm{Cut}_H(Y)|$, from \eqref{eq:45gg4fcfr}, and using that $k\geq 10/\log A$, for $|V(H)|\geq 2kA$, we obtain \[\textsc{Avg-Cut}_\mu(H)\geq \big(1-(1/2)^{|V(H)|}\big)\frac{\textsc{Max-Cut}(H)}{\hat{K}}\geq \frac{\textsc{Max-Cut}(H)}{K},\] where $K=1+\frac{6}{k\log A}$ is as in the statement of the lemma, as wanted. This finishes the proof of Lemma~\ref{lem:maingadget}. \end{proof} \subsection{Constant-factor inapproximability --- Proof of Theorems~\ref{thm:mainind3},~\ref{thm:mainIs3},~\ref{thm:maingen3}}\label{sec:f4343c} We now give the relatively straightforward proofs of Theorems~\ref{thm:mainind3},~\ref{thm:mainIs3},~\ref{thm:maingen3}. \begin{proof}[Proof of Theorems~\ref{thm:mainind3},~\ref{thm:mainIs3},~\ref{thm:maingen3}] Analogously to the proof of Theorem~\ref{thm:mainind1}, these theorems can be obtained as immediate corollaries of Theorem~\ref{thm:maingen3} using the field-gadget constructions of Theorem~\ref{thm:const2}. The only extra fact that we need to note is that in the case of the hard-core model ($\beta=1,\gamma=0$), we have that $(\beta,\gamma,\lambda)\in \ensuremath{\mathcal{U}}^*_\Delta$ iff $\lambda>\lambda_c(\Delta)$, for all $\Delta\geq 3$. Similarly in the case of the antiferromagnetic Ising model ($0<\beta=\gamma<1$), we have that $(\beta,\gamma,\lambda)\in \ensuremath{\mathcal{U}}^*_\Delta$ iff $\lambda\in (\tfrac{1}{\lambda_c},\lambda_c)$, where $\lambda_c=\lambda^{\mathsf{Ising}}_c(\Delta,\beta)$, for all $\Delta\geq 3$. \end{proof} \subsection{Proof of Theorems~\ref{thm:mainind2},~\ref{thm:mainIs2}, and~\ref{thm:maingen2}}\label{sec:maingen2} We next give the proof of Theorem~\ref{thm:maingen2}, using Theorem~\ref{thm:occgadget}. \begin{proof}[Proof of Theorem~\ref{thm:maingen2}] Suppose for the sake of contradiction that, for arbitrarily small $\kappa>0$, there is a polynomial-time algorithm that, on input a graph $G$ of maximum degree $\Delta$, produces an $(1+\frac{\kappa}{\log |V(G)|})$-approximation of the magnetization $\ensuremath{\mathcal{M}}_{G;\beta,\gamma,\lambda}$. We will show that we can approximate $\textsc{Max-Cut}$ on 3-regular graphs within a constant factor arbitrarily close to 1, contradicting the inapproximability result of \cite{maxcut}. Let $A(R),B(R), C(R)$ be the rational functions in Lemma~\ref{lem:maingadget} and set $D(R)=B(R)-C(R)$. From Footnote~\ref{ft:4f343}, we have that for all but finitely many values of $R$ we have that $D(R)\neq 0$. Using Theorem~\ref{thm:occgadget}, we therefore conclude that there are constants $R^*,M, \Xi, L>0$ such that $D(R^*)\neq 0$ and an algorithm, which, on input a rational $r\in (0,1/2)$, outputs in time $poly(\mathrm{bits}(r))$ a pair of field gadgets $\mathcal{T}_1,\mathcal{T}_2$, each of maximum degree $3$ and size $\leq L|\log r|$, such that \begin{equation}\label{eq:fieldgadgets} |R_1 - R^*|,|R_2 - R^*|\leq r, \quad |M_1|,|M_2|\leq \Xi, \quad |M_1-M_2|\geq \hat{M}. \end{equation} where, for $i\in\{1,2\}$, $R_i:=R_{\mathcal{T}_i}$ is the effective field of $\mathcal{T}_i$ and $M_i:=M_{\mathcal{T}_i}$ is the magnetization gap of $\mathcal{T}_i$. Let $H$ be a 3-regular graph, an instance of the $\textsc{Max-Cut}$ problem. Let $r=\min\{\tfrac{1}{|V(H)|^2 |V(G)|},r_0\}$ where $r_0$ is a small constant to be picked shortly. Consider field gadgets $\mathcal{T}_1,\mathcal{T}_2$ that satisfy \eqref{eq:fieldgadgets}. For convenience, for $i\in\{1,2\}$ we let $A_i',A_i,B_i,C_i,D_i$ denote $A_{\mathcal{T}_i}',A(R_i),B(R_i),C(R_i), D(R_i)$, respectively. Since the functions $A,B,C,D$ are continuously differentiable with respect to $R$ and $D(R^*)\neq 0$, there are constants $r_0,\eta>0$ so that \begin{equation}\label{eq:conti123} D_1,D_2\neq 0,\quad \Big|\frac{R_1}{R_2}-1\Big|\leq \eta r, \quad |C_1-C_2|\leq \eta r, \quad |D_1-D_2|\leq \eta r. \end{equation} For $i\in \{0,1\}$, consider the graph $H^{k}_{G,\mathcal{T}_i}$ for some large integer $k>1+10/\log A_1$ and small $\epsilon>0$ to be specified later. Let $\mu_i$ denote the Gibbs distribution on $H^{k}_{G,\mathcal{T}_i}$ with parameters $\beta,\gamma,\lambda$. By Lemma~\ref{lem:maingadget}, the average magnetization of the graph $H^{k}_{G,\mathcal{T}_i}$ satisfies \begin{equation}\label{eq:magsi} \begin{aligned} \ensuremath{\mathcal{M}}_{\beta,\gamma,\lambda}(H^{k}_{G,\mathcal{T}_i})&=4k\mathcal{A}_i'|E(H)|+\ensuremath{\mathbf{E}}_{\sigma\sim \mu_i}\Big[\big|\sigma_{V(\widehat{H}^{k}_{G})}\big|\Big]+(1\pm 8\epsilon)kM_{i} Q_i. \end{aligned} \end{equation} where $Q_i=D_i\textsc{Avg-Cut}_{\mu_i}(H)+C_i |E(H)|$ and $\textsc{Avg-Cut}_{\mu_i}(H)$ satisfies \begin{equation}\label{eq:avgcuti} 1/K_i\leq \displaystyle \frac{\textsc{Avg-Cut}_{\mu_i}(H)}{\textsc{Max-Cut}(H)}\leq 1\mbox{ for }K_i:=1+\displaystyle\frac{6}{k\log A_i}. \end{equation} Let \begin{gather*} \ensuremath{\mathcal{D}}:=\ensuremath{\mathcal{M}}_{\beta,\gamma,\lambda}(H^{k}_{G,\mathcal{T}_1})- \ensuremath{\mathcal{M}}_{\beta,\gamma,\lambda}(H^{k}_{G,\mathcal{T}_2}),\quad \ensuremath{\mathcal{D}}':=\ensuremath{\mathbf{E}}_{\sigma\sim \mu_1}\big[\big|\sigma_{V(\widehat{H}^{k}_{G})}\big|\big]-\ensuremath{\mathbf{E}}_{\sigma\sim \mu_2}\big[\big|\sigma_{V(\widehat{H}^{k}_{G})}\big|\big], \end{gather*} so that from \eqref{eq:magsi} \[\ensuremath{\mathcal{D}}=4k(A_1'-A_2')|E(H)|+\ensuremath{\mathcal{D}}'+(1\pm 8\epsilon)k \big((M_1-M_2)Q_1+M_{2} (Q_1-Q_2)).\] Observe that \[|A_1'-A_2'|\leq 4L\log |V(H)|,\quad \ensuremath{\mathcal{D}}'\leq 4\eta k |V(H)|^2 |V(G)| r\leq 4k\eta ,\quad |M_2(Q_1-Q_2)|\leq 2\eta \Xi|E(H)|r \] The first inequality follows from the bounds on the sizes of $\mathcal{T}_1,\mathcal{T}_2$, the second inequality follows from applying Lemma~\ref{lem:perturb}, and the third inequality follows from \eqref{eq:conti123}, the fact that $|M_2|$ is bounded by $\Xi$ and the trivial bound $\textsc{Avg-Cut}_{\mu_i}(H)\leq |E(H)$|. Using the purported algorithm for the magnetizations on $H^{k}_{G,\mathcal{T}_i}$, and since the latter graph has at most $|V(H)|\, |V(G)|+2k|E(H)|\, |V(\mathcal{T}_i)|\leq |V(H)|^{2}$ vertices for all sufficiently large $|V(H)|$, we can compute $\widehat{\ensuremath{\mathcal{D}}}$ which is an $(1+\frac{\kappa}{2\log |V(H)|})$-approximation to $\ensuremath{\mathcal{D}}$, so that \[|\widehat{\ensuremath{\mathcal{D}}}-\ensuremath{\mathcal{D}}|\leq 10 k L |E(H)|\kappa\] for some small $\hat{\kappa}$. Then, we have that $\widehat{\textsc{MC}}=\frac{\widehat{\ensuremath{\mathcal{D}}}-4k(A_1'-A_2')|E(H)|}{k(M_1-M_2)D_1}-\frac{C_1}{D_1} |E(H)|$ satisfies \begin{equation}\label{eq:4g566g6b} |\widehat{\textsc{MC}}-\textsc{Avg-Cut}_{\mu_1}(H)|\leq \big(\tfrac{10 L}{|M_1-M_2| |D_1|}\kappa +8\epsilon+ \tfrac{2\eta \Xi}{|M_1-M_2| |D_1|} r\big)|E(H)|\leq 10\big(\tfrac{L}{\hat{M}} \kappa+\epsilon\big)|E(H)|. \end{equation} By choosing $k$ sufficiently large, we have from \eqref{eq:avgcuti} that $\textsc{Avg-Cut}_{\mu_1}(H)$ is within a factor arbitrarily close to 1 from $\textsc{Max-Cut}(H)$. By choosing $\epsilon, \kappa$ to be sufficiently small positive constants we can further ensure from \eqref{eq:4g566g6b} that our approximation $\widehat{\textsc{MC}}$ is within a factor arbitrarily close to 1 from $\textsc{Avg-Cut}_{\mu_1}(H)$, and hence from $\textsc{Max-Cut}(H)$ as well. This finishes the contradiction argument and completes the proof of Theorem~\ref{thm:maingen2}. \end{proof} \begin{proof}[Proof of Theorems~\ref{thm:mainind2} and~\ref{thm:mainIs2}] The theorems can be obtained as immediate corollaries of Theorem~\ref{thm:maingen2} using the field-gadget constructions of Theorem~\ref{thm:const1}. As in Section~\ref{sec:f4343c}, we again note that in the case of the hard-core model ($\beta=1,\gamma=0$), we have that $(\beta,\gamma,\lambda)\in \ensuremath{\mathcal{U}}^*_\Delta$ iff $\lambda>\lambda_c(\Delta)$, for all $\Delta\geq 3$. Similarly in the case of the antiferromagnetic Ising model ($0<\beta=\gamma<1$), we have that $(\beta,\gamma,\lambda)\in \ensuremath{\mathcal{U}}^*_\Delta$ iff $\lambda\in (\tfrac{1}{\lambda_c},\lambda_c)$, where $\lambda_c=\lambda^{\mathsf{Ising}}_c(\Delta,\beta)$, for all $\Delta\geq 3$. \end{proof} \bibliographystyle{plain}
{'timestamp': '2020-04-21T02:26:23', 'yymm': '2004', 'arxiv_id': '2004.09238', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09238'}
arxiv
\section{Introduction} Deep neural networks (DNNs) are the state-of-the-art method to solve a wide variety of complex tasks from computer vision to speech recognition. In general, the weights of those networks are optimized exploiting a vast amount of data. However, collecting and especially labeling data, which is necessary for supervised learning, is time-consuming and labour-intensive. Consequently, current research investigates the integration of prior knowledge to DNNs in order to improve the data efficiency of the learning process, thus improving the performance when training data is limited or scarce \cite{Coors2018ECCV}. One promising approach is to exploit prior knowledge by enforcing in- or equivariance properties to symmetric geometrical transformations such as rotation and scaling. This can be achieved by replacing the randomly initialized weights of convolutional layers with predefined or restricted filters \cite{HarmonicNetworks, DeepHybridNetworks, LearnableScatter}. Alternatively, the \textit{standard convolution}, which is equivariant to translations, can be substituted by a more general form called \textit{group convolution} \cite{GroupEquivariantCNNs}, which guarantees equivariance with respect to more sophisticated transformation groups. Weiler et al. combine both approaches by restricting the convolution weights to linear combinations of steerable filters and applying the group convolution to the activations \cite{LearningSteerable}. The aforementioned methods build invariant feature spaces by pooling from equivariant feature spaces. In practice however, those feature spaces are affected by sampling effects and are thus not completely invariant. To avoid this, one could replace the simple pooling operation with an advanced operation geared towards enforcing invariance properties. We propose to use invariant integration (II) for this purpose. II is a method for constructing a complete feature space that is invariant to a transformation group \cite{SM_Existence,SM_Algos}. It has successfully been applied to object detection from grayscale images \cite{SM_Gray}, automatic speech recognition \cite{Muller3} and event detection from image sequences \cite{Condurache}. However, all of these approaches use II to create a feature space used by conventional classifiers, such as a \textit{Support Vector Machine}. We propose a novel DNN layer based on II embedded into a convolutional neural network (CNN) architecture. The II layer (IIL) builds upon an equivariant feature layer to foster an invariant feature representation (see Figure \ref{fig:Architecture}). We demonstrate that the backpropagation algorithm is applicable with respect to the IIL's parameters and input. Hence, its parameters as well as preceding layers can be optimized en bloc. We test our method on the Rotated-MNIST dataset \cite{RotMNIST} and demonstrate state-of-the-art performance. The largest performance gains are achieved when only few labeled training samples are available. \section{A DNN architecture based on Invariant Integration} Group theory lays the foundation of II. A group $G$ is a mathematical abstraction consisting of a set of elements acted upon by an operation under the axioms of closure, associativity, identity and invertibility. A function $f$ is said to be equivariant with respect to a group $G$ of transformations, if we can determine an exact relationship between transformations $g \in G$ of the function's input $x$ and a corresponding transformation $g^\prime \in G$ of the function's output: \begin{equation*} f(gx) = g^\prime f(x) \; \forall \; x \in X \text{.} \end{equation*} Invariance is a special case of equivariance, where the induced transformation in the output space $g^\prime$ is the identity. An example of an equivariant function is the convolutional layer, which is equivariant to translations. In practice, we are also interested to enforce invariance to other transformation groups than translations, e.g. rotations. However, this is more difficult to achieve in an explicit manner. \setlength{\belowcaptionskip}{-15pt} \begin{figure} \centering \includegraphics[width=0.8\textwidth]{img/inkscape/architecture.eps} \caption{We apply invariant integration in a learned equivariant feature space to form a feature space invariant to rotations and translations and use fully connected layers for classification.}\label{fig:Architecture} \end{figure} II is an algorithm to construct a complete feature space with respect to a symmetric transformation first proposed by Schulz-Mirbach \cite{SM_Existence, SM_Algos}. A feature space is defined as complete, if all patterns which are equivalent with respect to a transformation group $G$ are mapped to the same point in the feature domain, while all distinct patterns are mapped to different points. This means that a complete feature space is invariant to transformations $g\in G$ of the input signal. In \cite{SM_Algos}, Schulz-Mirbach proposes a general algorithm to construct a complete feature space relying on the group average $A$, which is defined by integrating an invariant function $f$ over transformations $g \in G$ acting on the input space $\mathbf{x}$: \begin{equation*}\label{eq:groupAverage} A[f](\mathbf{x}) := \int_{g \in G} f(g\mathbf{x}) \,dg \text{.} \end{equation*} In the case of a discrete group, this integral reduces to a sum over all transformations $g \in G$ of the input. For the invariant function $f$, the set of all possible monomials $m(\mathbf{x})$ represents a good choice for creating a complete feature space. These are defined as: \begin{equation*} m(\mathbf{x}) = \prod_{i=1}^{K} x_i^{b_i} \quad \text{with} \quad \sum_i b_i \le |G| \text{,} \end{equation*} where $K$ is the size of the input feature and $b_i$ are the monomial's exponents. The upper bound for the number of all possible monomials is $\binom{K + |G|}{K}$. \subsection{Rotation-Invariant Integration in Image Space} We apply II using monomials over the group of rotations and translations in image space \cite{SM_Gray}. Thus, our input is defined as $\mathbf{x} \in \mathbb{R}^{H \times W \times C}$, where $H$, $W$ and $C$ are the image's width, height and number of channels. We apply the group average independently to each channel $c = 1,\hdots,C$ and reformulate: \begin{align*} A[f](\mathbf{x}) &= \sum\limits_{u}\sum\limits_{v}\int_\phi m(\mathbf{x}(u, v; \phi))\,d\phi \\ &= {\sum\limits_{u}\sum\limits_{v}}\int_\phi\prod\limits_{i=1}^{K}\mathbf{x}(u + d_{u,i}\sin(\phi), v + d_{v,i}\cos(\phi))^{b_i}\,d\phi \text{,} \end{align*} with the monomial distances $d_{u,i}$ and $d_{v,i}$, the pixel offsets $u$ and $v$ and the integration angle $\phi$. The output is of dimension $\mathbb{R}^{C \times M}$, where $M$ is the number of monomials. Contrarily to previous work, we choose to apply rotation-invariant integration directly in convolutional feature space. \subsection{Monomial Selection} Since including all possible monomials is computationally expensive, the question arises, how to choose a meaningful subset. While the exponents $b_i$ can be optimized using backpropagation (see Chapter \ref{sec:backprob}), choosing the monomial orders $K$ and their distances is non-trivial. We use an iterative approach for feature selection called \textit{Feature Finding Neural Network} (FFNN) proposed by Gramss \cite{Gramss91}. It has successfully been used to select the monomials for II in automatic speech recognition by Mueller and Mertins \cite{Muller3} and is based on iteratively ranking monomial combinations according to the \textit{least square error} (LSE) of a linear classifier. While using a linear classifier facilitates good generalization ability, the LSE can be computed in closed-form, which enables an efficient calculation. We adapt this method by utilizing the closed-form solution of a linear classifier to rank the feature combinations according to the classifiers' validation accuracies instead of the LSE. The iterative selection is stopped, if the validation accuracy has not improved within the past ten iterations. \subsection{Architecture and Training Process} The architecture for a classification network using the proposed IIL is shown in Figure \ref{fig:Architecture}. The IIL is used to construct an invariant feature space with respect to transformations of the convolutional feature space it acts on. To ensure that the whole DNN is invariant, the convolutional feature space must be equivariant with respect to transformations of the DNN's input. Thus, we use an equivariant backbone built out of equivariant convolutional layers and apply the IIL to build an complete invariant feature space (see Figure \ref{fig:Architecture}). Finally, we use fully connected layers to obtain the classification scores. In comparison, the networks proposed in \cite{HarmonicNetworks, LearningSteerable} use max- or sum-pooling to create an invariant feature space from their equivariant convolutional feature space. During training, we first train the baseline network without the IIL. Thereafter, we apply II on the features of the last convolutional layer and select $M$ monomials using our iterative sampling approach. Finally, we re-train the entire network including the IIL and the preceding equivariant convolutional layers. \subsection{Backpropagation for Invariant Integration Layers}\label{sec:backprob} To enable using II for the construction of a complete feature space in combination with DNNs it is inevitable that the proposed feature transformation is differentiable with respect to both its parameters and inputs. The gradients of a monomial with respect to a single input $x_j$ and to the learnable exponents $b_j$ are respectively defined as: \begin{equation*} \frac{\delta m(\mathbf{x})}{\delta x_j} = b_j x_j^{b_j - 1} \prod_{i=1, i\neq j}^{K}x_i^{b_i} \text{,} \quad \frac{\delta m(\mathbf{x})}{\delta b_j} = \log(x_j) x_j ^{b_j} \prod_{i=1, i\neq j}^{K}x_i^{b_i} \text{.} \end{equation*} Investigating these formulas, it is evident that we need to enforce $x_i \neq 0 \; \forall i$, because $\lim\limits_{x_i \rightarrow 0} \frac{\delta m(\mathbf{x})}{\delta x_j} = 0$ and $\lim\limits_{x_i \rightarrow 0} \frac{\delta m(\mathbf{x})}{\delta b_j} = 0$, would lead to vanishing gradients backpropagated to earlier layers and to the exponents of the IIL, respectively. We further restrict the input values to $\mathbb{R}^{+}$ because multiplying by a negative number alters the sign of the output, hence leading to great shifts in output space. Finally, we note that the identity element of a multiplication is 1, while a multiplication with values close to 0 would eradicate the result. Following the aforementioned insights, we choose to shift our input features: ${\mathbf{\tilde{x}} = \max(\epsilon, \mathbf{x} - x_{min} + 1)} \text{,}$ with $0 < \epsilon \ll 1$. In our implementation, we shift the input per channel, while $x_{min}$ is the minimal value that occurred within that channel when processing the training data. Lastly, we apply the $\max$-function to ensure that there are no values smaller than $\epsilon$ during testing. \section{Experiments and Discussion} \setlength{\belowcaptionskip}{-15pt} \begin{figure} \begin{multicols}{2} \includegraphics[width=\linewidth]{img/limited/te_limited_unaug.eps} \par \includegraphics[width=\linewidth]{img/limited/te_limited_aug.eps}\par \end{multicols} \centering \vspace*{-10pt} \caption{Mean test error using limited training data without (\textit{left}) and with (\textit{right}) augmented data. The transparent corridors represent the results' standard deviation.} \label{fig:MNIST_limited} \end{figure} We use our approach to enforce rotation invariance for the recognition of randomly rotated hand-written digits on the Rotated MNIST dataset \cite{RotMNIST}. It contains $10{,}000$ training, $2{,}000$ validation and $50{,}000$ test images. We optimize the hyper-parameters on the validation set. Thereafter, we retrain on the training and validation sets to report the final results on the test set (cf. \cite{HarmonicNetworks, LearningSteerable}). \setlength\intextsep{0pt} \setlength{\belowcaptionskip}{0pt} \begin{wraptable}{R}{4.8cm} \small \centering \begin{tabular}{|l|c|c|} \hline \multirow{2}{*}{Method} & \multicolumn{2}{c|}{Augmentation} \\ & $\times$ & $\checkmark$ \\ \hline CNN \cite{HarmonicNetworks,GroupEquivariantCNNs} & $5.130$ & $3.772$\\ HCNN \cite{HarmonicNetworks} & $1.730$ & $1.606$ \\ \textbf{II-HCNN}& $1.548$ & $1.377$ \\ SFCNN \cite{LearningSteerable} & $0.880$ & $\mathbf{0.714}$ \\ \textbf{II-SFCNN} & $\mathbf{0.799}$ & $0.722$ \\ \hline \end{tabular} \caption{Mean test error [$\%$].} \label{tab:results} \end{wraptable} For the equivariant backbone, we use two different approaches that are equivariant to rotations in image space. First, we apply harmonic convolutions (HCNN) proposed by Worrall et. al \cite{HarmonicNetworks}. We use the modulus of the final complex convolutional layer as the input to our IIL. Secondly, we use the Steerable Filter CNN (SFCNN) proposed by Weiler et. al \cite{LearningSteerable}. We max-pool along the angle dimension of the final convolutional layer and apply channel-wise II. We empirically choose to use $M=5$ monomials and to integrate over 8 angles using bilinear interpolation to obtain a good trade-off between performance and computational complexity. We compare the different approaches by means of the mean test error over ten independent training runs. In Table \ref{tab:results}, we show results obtained when training on the entire training and validation set both with and without data augmentation. We evaluate a standard CNN as well as the HCNN and the SFCNN without and with the IIL. The data was augmented by randomly rotating the input during training. When combining II with the HCNN, we achieve a relative improvement of $10.52 \, \%$ without and $14.26\, \%$ with data augmentation. The II-SFCNN improves the baseline by $9.2 \, \%$. However, when training with augmented data, the SFCNN achieves the best performance, but only by a small margin. Figure \ref{fig:MNIST_limited} shows the mean test error and the standard deviation when training with limited data. When using only a subset of the available training data, we achieve significant improvements over the state-of-the-art baseline algorithms. It seems that enforcing the sought invariances on top of an equivariant feature space by using II instead of the simpler pooling operation is particularly beneficial when only limited data is available. We believe this is related to the fact that a small training set typically does not include the variability needed to properly capture the sought invariances without explicitly enforcing them. Additionally, we observe that the performance boost is bigger when applying the IIL to the SFCNN because its feature representation is equivariant to sampled rotations, while the HCNN guarantees equivariance to continuous rotations. Enforcing the invariance with the IIL seems to mitigate those sampling effects. \section{Conclusion and Future Work} We proposed a novel layer based on II which allows us to incorporate prior knowledge expressed as the need to obtain features invariant to certain geometrical transformations of the input, e.g. rotations. We apply it to enforce rotation invariance in a CNN architecture. We show competitive performance when training on the full dataset and state-of-the-art results in the low data regime. This indicates that our approach enables a better transition from equivariant to invariant features than pooling when the learned feature representation is not exactly equivariant, e.g. due to sampling effects. Our method is especially helpful, when training with fewer training samples. In the future, II can be expanded towards other transformation groups, e.g. scale. Additionally, the IIL can be applied in more complex neural network architectures. We will investigate, if hand-designing the monomials is possible, thus allowing to incorporate additional prior knowledge and avoiding the pre-training of the baseline network necessary to enable selecting appropriate monomials. \begin{footnotesize} \bibliographystyle{unsrt}
{'timestamp': '2020-04-21T02:24:11', 'yymm': '2004', 'arxiv_id': '2004.09166', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09166'}
arxiv
\section{Introduction} Bitcoin is the first publicly-issued cryptocurrency, introduced in 2008 by Satoshi Nakamoto with a paper \cite{satoshi} that discloses not only the nuts and bolts of the underlying technology, the blockchain, but also the expected dynamics of the complex system created by the adoption of this new form of electronic money. These dynamics are crucial because they are what make the bitcoin and other cryptocurrencies robust, scalable, and secure. This paper aims to shed some light on one of these dynamics, which is at the core of bitcoin’s security: the mining of blocks. By applying a modeling technique known as system dynamics \cite{forrester, sterman}, the evolution of the network hash rate is shown to be explainable, to a large extent, with a simple efficient-market hypothesis, where bitcoin miners mine because of the expected profit they make from mining, net of the cost of electricity. On the one hand, this result is unimpressive and reassuring, in that it resonates well with common sense. On the other hand, it may have significant implications on the future evolution of the network hash rate. In particular, if the profit from mining becomes negative as a consequence of a price crash or of a dramatic fall in the reward, the network hash rate might drop significantly, because hashing power would be diverted to the mining of more profitable alternative coins. This might be the case, for instance, in the aftermath of the forthcoming halving of May, 2020, when the network could have reached the ‘peak hash’. Possible consequences include higher volatility of the bitcoin network hash rate, as well as security issues. \section{The Bitcoin and System Dynamics} System dynamics (SD) is an approach to the modeling of systems in terms of stocks, flows, and feedback loops, introduced in the 60s by MIT’s Prof. Jay Forrester \cite{forrester}. It became very popular in the 70s thanks to the publication of The Limits to Growth [3], a book that used an SD model to expose the futility of the idea of infinite growth on a finite planet. Today, the most comprehensive reference about system dynamics is the book Business Dynamics by MIT’s Prof. John Sterman \cite{sterman}. System dynamics can model both the technical and social aspects of the complex systems established with the adoption of the bitcoin and other cryptocurrencies. Therefore, it is a perfect approach to study the economic dynamics of these new forms of money thanks to its ability to explain emergent systemic phenomena in terms of interactions between factors related to both human behavior and (technical) system architecture. Surprisingly, little attention has been paid so far to the bitcoin and other cryptocurrencies by researchers in system dynamics. Only two studies so far applied quantitative SD models to cryptocurrencies, presenting an Accounting System Dynamics macroeconomic perspective on peer-to-peer monetary systems \cite{yamaguchi1, yamaguchi2}. Neither of these studies, however, explicitly models or builds upon the unique features of the bitcoin cryptocurrency system architecture. This paper intends to show how SD can be both a powerful and accessible tool to model the architecture of the blockchain and related market behaviors, that is the technical and social aspects of the bitcoin as a complex system. The power of SD in this context lies in the capability to integrate these aspects in one model, and its accessibility in the visual representation of the model, in terms of stocks, flows, and feedback loops, which make SD models intelligible to a large audience. \newpage \section{The Hypothesis} The model of this paper addresses: what does drive the growth of bitcoin mining power (i.e., the network hash rate)? The hypothesis is that miners mine blocks because they profit. In other words, because \[ \textrm{Mining Revenues} \ge \textrm{Mining Cost} \] where \[ \textrm{Mining Revenues} = (\textrm{Subsidy} + \textrm{Transaction Fees}) \cdot \textrm{BTC Price} \] Note that both sides of the first equation are in U.S. Dollars (USD) and refer to the reward and cost of mining in monetary terms at the exchange rate between Bitcoin (BTC) and USD at the time the block is mined. For reference, the historical evolution of bitcoin price and transaction fees from the beginning of the bitcoin to the date of writing is given (Fig. \ref{fig:image1}). \begin{figure}[h] \begin{subfigure}{0.5\textwidth} \includegraphics[width=0.9\linewidth]{price.png} \caption{Bitcoin price (in USD/BTC)} \label{fig:subim3} \end{subfigure} \begin{subfigure}{0.5\textwidth} \includegraphics[width=0.9\linewidth]{transaction-fees.png} \caption{Transaction fees (in BTC)} \label{fig:subim4} \end{subfigure} \caption{Historical time series used as exogenous variable in the model. Source of data and images: blockchain.com} \label{fig:image1} \end{figure} In the simplified model of this paper, the operational cost of mining (OPEX) is approximated just with the cost of the energy used in the mining process, whereas other operational costs, as well as the original investment to purchase and setup the mining hardware (CAPEX), are neglected. Finally, it is assumed that energy is traded in a legal tender currency, USD, and therefore miners have to sell bitcoin to pay the electricity bill. This dynamic hypothesis further assumes an efficient market with perfect information. As long as the mining profit is positive, more hashing power is added to the network until the marginal cost of adding more hashing power exceeds its expected return. Conversely, when the mining profit becomes negative, hash rate is subtracted from the network. The increase and decrease of hash rate happens with a certain time constant, represented with a delay factor (i.e., the adjustment is not instantaneous). In a first approximation, this delay is assumed to be the same for both the increase and decrease of hashing rate, although the latter is likely to be smaller than the former. This hypothesis is a coarse simplification of reality, and therefore can only provide a partial answer to the question of what drives the bitcoin network hash rate. Specifically, it assumes that all miners work for the immediate profit of mining, and it does not consider that some (most?) miners may be willing to invest even when the current revenues of mining are negative in the expectation of the future returns from rising BTC price. Nevertheless, it is plausible that the perspective of a present-time gain, at any time, is the dominant mechanism underlying the decision of a miner whether or not to invest in additional mining hardware, or mine bitcoin instead of another more rewarding cryptocurrency. Furthermore, the same hypothesis is applied throughout the entire life of the bitcoin, from the early days (January 2009) till now (April 2020). It is obvious that the dynamics driving the mining of the bitcoin in the early days were not the same of today. At the beginning, a true market barely existed, and mining was performed by enthusiastic individuals with modest investment in hardware infrastructure. Today, there is a market with ‘perfect information’ that is dominated by corporations with a stake in mining infrastructure worth any million of USD. Hence, the model is expected to correlated with historic data better in the late years than in the early years. \section{The Model} The model of this paper has been created with Vensim (Ventana Systems, Inc.), and it is available at: github.com/davidelasi/bitcoin. The model is organized in two views: Coin Creation and Hash Rate Adjustment. Certain variables of the system are treated as exogenous variables, meaning that neither their value is determined by the state of other variables of the system, nor they take part in feedback loops. The following historical time series are exogenous (inputs) to the model: \begin{itemize} \item Bitcoin price [in USD/BTC] \item Revenues from transaction fees [in BTC/Day] \item Energy efficiency of state of the art mining hardware [in GH/J] \end{itemize} The latter is based on our synthesis of a multitude of internet sources that are too many to be mentioned here (from Wikipedia to old pages of other websites and forums about the energy efficiency of mining hardware). The model correlation is performed by comparing selected model outputs with the historical time series: \begin{itemize} \item Height of the Blockchain [in blocks] \item BTC in circulation [in BTC] \item Hash Rate [in GH/s] \end{itemize} The first two are used only as a model sanity check, whereas the last one is used for model correlation. The correlation of the model has been performed both manually and using the optimization capabilities of Vensim DSS. The model structure is discussed in detail in the following sections. The following conventions are used: variable names are capitalized, and constant names are all capital. Exogenous variables are highlighted in gray in the figures. Bitcoin is abbreviated as BTC. \subsection{Coins Creation} The creation of bitcoins is modelled as shown in Fig. \ref{fig:coin_creation}. This diagram represents the mechanism of controlled supply devised by Satoshi Nakamoto. There is a finite stock of 21,000,000 Total BTC, whose content flows into a second stock of BTC in Circulation with a certain creation rate. This creation rate is given by the product of two factors: how many blocks are mined per day, and how much subsidy (in BTC) is granted for each mined block. The former is assumed to correspond to the Target Block Creation Rate of 1 block every 10 min (144 blocks / day), and the latter is a geometric series following the process that is hard-coded in the bitcoin software: an initial subsidy of 50 BTC per mined block, that is halved every 210,00 blocks until the value of the subsidy reaches the minimum bitcoin-transaction unit of 0.00000001 BTC, commonly known as ‘1 Satoshi’. This part of the model does not include any dynamic loop. No feedback is present, and with respect of the dynamic hypothesis current under investigation, the only connections to the higher layer of the model are through the variables BTC Subsidy per Mined Block and Target Block Creation Rate, which are used to compute the Revenues from Subsidy. \begin{figure} [h] \centering \includegraphics[width=4in]{coin-creation.png} \caption{Coin Creation model view.} \label{fig:coin_creation} \end{figure} \newpage \subsection{Hash Rate Adjustment} The addition of hash rate to the bitcoin network is modeled as shown in Fig. \ref{fig:hash_rate_adjustment}. The negative feedback loop is the manifestation of the effect of the efficient-market hypothesis set forth earlier. \begin{figure} [h] \centering \includegraphics[width=5in]{hash-rate-adjustment.png} \caption{Hash Rate Adjustment model view. Exogenous variables in gray.} \label{fig:hash_rate_adjustment} \end{figure} The network Hash Rate (GH/s) is a stock with a Net Inflow of Hash Rate representing the amount of computational power that is daily added or subtracted from the network. The Hash Rate at time zero is set to 0.007 GH/s, according to some estimation of the original computational power available to Satoshi Nakamoto in the early days of bitcoin \cite{satoshi-hash}. From the Hash Rate, the number of Daily Hashes (GH/day) computed by the network is calculated. The Mining Cost is determined by the Hashing Cost, expressed in \$/GH and given by the quotient between the Price of Energy (\$/J) and the Energy Efficiency of State of the Art Mining Hardware (GH/J). The Price of Energy is assumed to be constant over the studied time period at 0.05 \$/kWh. This is a simplification that may not be fully representative of the average price of energy used by miners in the early days, although it seems to be aligned with the present (according to \cite{coinshare-research}, ~0.04 \$/kWh). The Energy Efficiency of State of the Art Mining Hardware is modeled as a constant level in different epochs of mining. Seven periods are identified, from the times of the CPU to the most-recent ASIC technology (Table \ref{table:1} and Fig. \ref{fig:miners_technology}). At the end of each period, the variable assumes the value of the next period, as if the whole network would immediately switch to the new technology at once. This is not realistic and creates discontinuities in the time series, as the difference of this variable between consecutive period is often of the order of 10x. The model could be easily improved by adding further elements to model the typical S-shaped (logistic function) pattern of new technology's diffusion. \begin{table}[h!] \begin{center} \begin{tabular}{ |c|c|c|c| } \hline Technology & From (date) & Period (days) & Energy efficiency (MH/J) \\ \hline CPU & Mar 2009 & 0–600 & 0.1 \\ GPU & Oct 2010 & 600–1,000 & 1 \\ FPGA & Dec 2011 & 1,000–1,400 & 10 \\ ASIC (110 nm) & Jan 2013 & 1,400–1,550 & 100 \\ ASIC (55 nm) & Jun 2013 & 1,550–1,900 & 500 \\ ASIC (28 nm) & Jun 2014 & 1,900–2,450 & 1,000 \\ ASIC (16 nm) & Dec 2015 & 2,450–Now & 10,000 \\ \hline \end{tabular} \caption{Evolution of state-of-the-art mining hardware} \label{table:1} \end{center} \end{table} \begin{figure} [h] \centering \includegraphics[width=3in]{miners-technology.png} \caption{Energy efficiency evolution of state-of-the-art mining hardware.} \label{fig:miners_technology} \end{figure} The Mining Revenues are calculated by summing the Revenues from Subsidy and from transaction fees, and converting them into \$. This calculation uses a mix of endogenous and exogenous factors: the subsidy is calculated based on the variables modelled in the ‘Coins Creation’ view described in the previous section, whereas the transaction fees and the BTC price are extracted from historic data series mentioned earlier. Subtracting the cost from the revenues of mining, the Mining Profit is calculated. This determines the amount of Hash Rate Shortfall, that is how much hashing power could be added before the marginal cost of adding more will exceed the benefit (a situation of zero-profit that is the goal of the negative feedback loop): \[\textrm{Hash Rate Shortfall} = \frac{\textrm{Mining Profit}}{\textrm{Cost of Energy} \cdot \textrm{Energy Efficiency of Mining Hardware}} \] \newpage In other words, the profit that the network makes every day (\$/day, expressed in \$/s) is converted into an amount of energy (J/s) that the network could afford to add before reaching a zero-profit situation. This amount of energy, in turn, corresponds to a certain amount of hashing power (GH/s) calculated through the Energy Efficiency of State of the Art Mining Hardware that is available at any given time (GH/J). At last, the key factor involved in this loop is introduced: the Hash Rate Adjustment Time. This accounts for the fact that the system does not react instantaneously to a shortfall in hash rate, for instance, because the supply chain of mining hardware is (notoriously) limited in its throughput. This parameter is the only one that is acted upon for the correlation of the model results by comparing the calculated hash rate with the historical time series. \section{Results and Discussion} The results and discussion are divided into three sections about model correlation, insights about the past, and speculations about the future. Table \ref{table:2} maps the number of days of the simulation to calendar dates and relevant events, to help with the interpretation of the results. \begin{table}[h!] \begin{center} \begin{tabular}{ |c|c|c| } \hline Time (day) & Date & Comment \\ \hline 0 & 3 Jan 2009 & Mining of the genesis block \\ 500 & May 2010 & Introduction of GPU miners \\ 1,000 & Sep 2011 & Introduction of FPGA miners \\ 1,500 & Feb 2013 & Introduction of 1st gen. ASIC \\ 2,500 & Nov 2015 & Introduction of 4th gen. ASIC \\ 3,300 & Dec 2017 & Bitcoin grazes the 20,000 \$/BTC price mark \\ 3,700 & Feb 2019 & – \\ 4,100 & Mar 2020 & Latest update of this model \\ \hline \end{tabular} \caption{Evolution of state-of-the-art mining hardware} \label{table:2} \end{center} \end{table} \subsection{Model Sanity Check and Correlation} A sanity check of the model is performed by comparing the height of the blockchain calculated by the model with the actual historical time series (Fig. \ref{fig:blockchain-height}). The comparison is satisfactory, showing that the Coin Creation part of the model works as expected. \begin{figure} [h] \centering \includegraphics[width=2.1in]{blockchain-height.png} \caption{Evolution of the height of the blockchain over time (model vs reality).} \label{fig:blockchain-height} \end{figure} The correlation of the model with historical data series has been performed by tuning the value of the Hash Rate Adjustment Time manually, and through the automated optimization routines, until reaching a satisfactory matching between the calculated and the historical time series of the hash rate. By using a single value for the Hash Rate Adjustment Time throughout the whole time series, an optimal result can be found at 1112 days, but a poor correlation is obtained, particularly in the last three years (Fig. \ref{fig:hash-rate-correlation}a). The situation can be significantly improved by allowing for the possibility that the delay time of the feedback loop changes at some point (i.e., IF time < value THEN use delay time 1 ELSE use delay time 2). The optimal fit occurs for a delay time of 1482 days from time 0 to 3,777 and only 264 days from time 3,777 to 4,100 (Fig. \ref{fig:hash-rate-correlation}b). The rest of the results in this paper are relative to this second scenario. \begin{figure}[h] \begin{subfigure}{0.5\textheight} \includegraphics[width=12cm]{hash-rate_1time.png} \caption{Correlation with one delay value.} \label{fig:subim1} \end{subfigure} \begin{subfigure}{0.5\textheight} \includegraphics[width=12cm]{hash-rate_2times.png} \caption{Correlation with two delay values.} \label{fig:subim2} \end{subfigure} \caption{Model correlation with Hash Rate Adjustment Time: top row 1112 days; bottom row, 1482 days (time 0 – 3,777) and 264 days (time 3,777 – 4,100).} \label{fig:hash-rate-correlation} \end{figure} \newpage In general, the correlation can be considered good enough to gain some insights from this model, especially considering its simplicity, with the following provisos: \begin{itemize} \item The Hashing Rate Adjustment Loop does not capture well the dynamics of the system in the early days (0-1,500 days) dominated by CPU, GPU, and FGPA miners. Model improvements are needed to use it for this period. For example, the diffusion of new technologies could be modeled to allow for a gradual implementation of the newer generation of mining hardware, particularly in the early days, rather than as a step function. This could reduce the tendency of the model to overestimate the hash rate in the early days, and it would also avoid discontinuities in the hash rate as for time 2,450 in Fig. \ref{fig:hash-rate-correlation}. Also, a better estimate of the Price of Energy of the miners in the early days, which as certainly higher on average than 0.05\$/kWh, would help. \item The model reasonably captures the main dynamics of the system from time 1,500 on, which is in the epoch of ASIC miners; however, some dynamics are not represented by the model (e.g., the peak in Hash Rate around time ~3,600). To capture these ‘modes’, one would need to envisage and implement additional feedback loops working together with the Hashing Rate Adjustment Loop. \item Using two different adjustment times with an IF THEN condition is a ‘quick and dirty’ trick, which is generally considered ‘bad practice’ in a system dynamics model. The need to use such a ‘trick’ is symptomatic of the fact that the Hash Rate Adjustment Time might be, itself, part of other feedback loops that are currently not modeled, which would justify the change of this variable with time. For example, the delay’s decrease could be due to the reinvestment of mining profits in new technology or the enhancement of the supply chain of existing technologies. \end{itemize} In summary, there are several opportunities to extend and improve this model by identifying and implementing these additional loops. Yet, this simple model is sufficiently complex to gain relevant insights about the system while avoiding the risk of over-fitting the data. \newpage \subsection{Insights About The Past} Having established a reasonable correlation between the model and the reality, the analysis of the simulation results gives further insights on the past evolution of bitcoin mining and the related market dynamics: \begin{itemize} \item The long delay time of the feedback loop until ~ ten years (day 3,777) from the genesis block, means that there was much more potential demand than supply of mining hardware. In other words, even if mining was a great deal financially speaking, procuring as much hashing power as it would financially make sense from a pure present-day profit consideration, was never possible. The long delay time of hash rate addition is also in line with the lived experience that mining hardware has always been a (relatively) scarce resource, and further invalidates some efficient-market hypothesis models which would overestimate hash rate growth. \item The jump to a much lower delay time of the feedback loop that occurred around mid-2019, from 1,482 to 264 days, is also aligned with some factual evidence. In particular, in 2019, new mining hardware with ~5x the hashing power per unit sold compared to the previous state-of-the-art hardware became available \cite{coinshare-research}. This ratio matches quite well with the ratio between the two delays time, which is 5.6, and it would be compatible with the same supply chain delivering approximately the same ‘flow’ of miners (in units) but a ~5x bigger flow of mining power (in hash rate). \item Until late 2019, there was always a positive shortfall of hashing power in the network, with the biggest spike matching the time of highest bitcoin price and transaction fees. Compare Fig. \ref{fig:mining-past} with Fig. \ref{fig:image1}. The profit from mining, expressed in the simplistic terms of this paper as same-day revenues minus operational costs accounting for the cost of energy, was always positive, until the last few months. The current price of ~7,000 \$/BTC is likely to be close to the marginal cost of production of a bitcoin in the present conditions. The latter point, in particular, calls for some thinking about the future and the reaction of the system to the forthcoming halving event, in about a month from the time of writing. \end{itemize} \begin{figure} [h] \centering \includegraphics[width=3in]{mining-past.png} \caption{The Hash Rate shortfall that drives the negative feedback loop, and the mining economy in terms of revenues, cost, and profit (results for past time).} \label{fig:mining-past} \end{figure} \newpage \subsection{Speculations About The Future} Using a model correlated with past data to attempt to predict the future is always a tricky endeavor. This is true for this model as well for two reasons. First, because it is a simple model with only one feedback loop it may not capture all the dynamics of the system. Second, because the model correlation is performed with past data that were almost always relative to a growing network hash rate, and there is no guarantee that the same dynamics work when the market would turn in a different direction. In fact, the limited ability of the model to represent the ‘mode’ of the peak at 3,600 days (to the right in Fig. \ref{fig:hash-rate-correlation}) signals that different dynamics might apply to a decrease of the network hash rate. With this necessary premise, the temptation to apply the model to a hypothetical future is irresistible. Therefore, we have exercised the model after a hypothetical future scenario where the price of bitcoin and the revenues from transaction fees remain at an average level close to the recent time’s. This scenario is interesting because the current profit from mining, net of the cost of energy, is nearly zero (Fig. 8), meaning that the hashing power may have reached a status of equilibrium at the present level of revenues from the subsidy and the transaction fees. Therefore, it is interesting to see that this equilibrium might be perturbed by the forthcoming halving of the subsidy. Specifically, we have extended the model operation from day 4,100 to 7,500 with the following assumption: \begin{itemize} \item The Future BTC Price fluctuates around an average level of 7,300 \$/BTC. This is represented with a pink-noise time series (std deviation 500 \$/BTC and correlation time of 28 days). \item The Future Revenues from Transaction Fees fluctuate around an average level of 30 BTC/day. This is also represented with a pink-noise time series (std deviation 5 BTC/day and correlation time of 28 days). \end{itemize} All these assumptions are of course arbitrary, and one could play with any different set of assumption. The Energy Efficiency of State of the Art Mining Hardware is kept constant at today’s value, which is probably not too far off from reality in the short term, considering that orders of magnitude improvements of the present ASIC technology are unlikely to happen (although in the long-term quantum computing might be a game changer). While bitcoin mining spurs further technological advancement along the lines of Moore’s law, we don’t expect massive technological changes to affect this system dynamics model. To put it another way, the constraint of reduction of coinbase reward is expected to dominate over technological leaps in hashing efficiency. Fig. \ref{fig:mining-future} shows the projected future evolution of the revenues, costs, and profits from mining, and the evolution of the Hash Rate Shortfall determines the operation of the negative feedback loop of the model. The results show a quick switch to negative-profit for block mining at the next two halving events, and particularly at the next one, when the mining subsidy will be cut in half for the third time, from 12.5 to 6.25 BTC per block. Correspondingly, the Hash Rate Shortfall becomes negative, to indicate that the network has an excess of hash rate, which makes the cost of mining higher than the revenues that it generates. In other words, should the (dollar) revenues from mining remain at today’s level, mining will suddenly start to become unprofitable an unprofitable business until the difficulty goes down because of a reduction of the network hash rate. \begin{figure} [h] \centering \includegraphics[width=3in]{mining-future.png} \caption{The Hash Rate shortfall that drives the negative feedback loop, and the mining economy in terms of revenues, cost, and profit (future projection, see the text for details about the assumed revenues from subsidy and transactions).} \label{fig:mining-future} \end{figure} The feedback loop of the model, based on the efficient-market hypothesis set forth at the beginning of the paper, operates by reducing the hash power of the network until the net profit from mining will tend again to zero. The difference from the past is that, for the first time, the hash rate would tend to its equilibrium state from the bottom instead of the top. In the current model, the adjustment time of the net inflow hash rate is the same, regardless of the sign (i.e., addition or removal of hash rate). However, it is likely that the removal of hash rate will take place with a much shorter adjustment time, because it is much easier to switch off a mining hardware or use it for another purpose (e.g., switch to another cryptocurrency) than to procure and set it up. This could be implemented by considering different inflow and outflow of hash rate from the Hash Rate stock (currently modeled as a single net flow, see Fig. \ref{fig:hash_rate_adjustment}). This effect is not considered in the model, but it can be added in the future if the network hash rate will indeed start to drop. Hence there will be data to correlate this ‘mode’ of the system (in fact, there may already be some data to try to do so using the peak of hash rate at 3,600 days, to the right in Fig. \ref{fig:hash-rate-correlation}). This brings us to the last final question of this work: has the bitcoin reached the ‘peak hash’? That is, has the bitcoin reached the situation where the cost of mining is higher than the revenues from mining? Possibly, as the projection of the future evolution of the hash rate in Fig. \ref{fig:peak-hash} shows. Under the future (halved) value of the subsidy, the equilibrium hash rate of the system might be closer to ~60B GH/s than to the current ~110 GH/s. \begin{figure} [h] \centering \includegraphics[width=3.5in]{peak-hash.png} \caption{Peak hash (present time = 4100).} \label{fig:peak-hash} \end{figure} If that will be the case, a most interesting question will be: where will all that excess hashing power be invested, and how this might change the landscape of the bitcoin and other cryptocurrencies? Could the bitcoin and other networks’ hash rate experience higher volatility of hash rate after the next halving event? May such a staggeringly large amount of hashing power that could potentially flee from the bitcoin network in the long-term be a threat to the security of the network (or other SHA256 secured coins such as BCH and BSV), if ever it would suddenly come back? Of course, a number of events may allow for a smooth transition between the current and the next reward era, such as significant improvements in the energy efficiency of the mining hardware, access to yet cheaper energy, or substantial inflation of bitcoin price and transaction fees. Some of these changes (e.g., increase in block size) and trends (e.g., increase in transaction fees) have been already happening in the past. But one thing seems true: the effect of the forthcoming halving might be different and have deeper consequences than the previous, so it is worth making sure that the bitcoin, as a dynamical system, is prepared for this transition. Finally, it is worth considering what could be an alternative model of coin supply that would not have incurred this (hypothetical) peak of hash rate. In 2014, for instance, a cryptocurrency based on a continuous logarithmic coin release mechanism was released: the Woodcoin [10], which replaces bitcoin’s geometric series reduction of coinbase rewards with a harmonic series. Such a mechanism, among others, ensures a slower overall rate of coinbase reduction, changing the system dynamics especially in the longer term. While the “halving” system of a geometric series reduction of coinbase chosen by Satoshi has been popular among other public currencies (e.g. XMR, LTC), a System Dynamics model could tell us more about how other choices of currency issuance will affect the hash rate and future security of the system. \newpage \section{Conclusions} We have shown that aspects of bitcoin mining can be modeled as a dynamical system using system dynamics. Starting with a dynamical hypothesis based on an efficient-markets hypothesis applied to the mining of blocks, we have shown how the recent evolution of the bitcoin network has rate can be explained by a negative feedback dynamic loop that zeroes on mining profit with a delay time. By extending the simulation into the future to cover the next two reward eras, under the assumption of constant bitcoin price and revenues from transaction fees approximately at the level of April 2020, we have shown how there is a possibility that the next halving event lead to a transition to an unprofitable mining regime with an excess of network hash rate. This may imply that we might be at the ‘peak hash’, and experience a continuous decline of the hash rate (and difficulty) in the coming years. Finally, this model shows that system dynamics methods and tools can be effective to model the bitcoin and could be applied to other existing or new proposed cryptocurrencies as well to understand the behavior of the complex sociotechnical systems that are created from the application of blockchain technology to electronic money and other applications enabled by shared ledger. It is worth noting the relative success that the model enjoys with historical data, especially considering that there is no way to verify how many people are mining nor what hardware is available to them. \subsection*{Future Work} Despite a decade of practice, the theory behind public proof-of-work ledgers remains in its infancy. There are many additional tweaks possible to the system dynamics we have presented here, including more complex models of mining efficiencies, other currency release curves (other coins), and modeling the effect of market shocks. The initial applicability of the model leaves us expecting much more from future work using system dynamics to understand the evolution of the public proof-of-work consensus network. \subsection*{Acknowledgments} One of the authors, Davide Lasi, is extremely grateful to Prof. Jim Lyneis, lecturer of system dynamics in the MIT \textit{System Design \& Management (SDM)} program. His teachings of system dynamics and his generous dedication of time to brainstorm about system dynamics and the bitcoin were instrumental for laying the ground for this work in the summer of 2017, when this model was conceived. Prof. Lyneis has not reviewed the final implementation of this model; therefore, any mistake is only attributable to the authors. \newpage
{'timestamp': '2020-04-21T02:25:24', 'yymm': '2004', 'arxiv_id': '2004.09212', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09212'}
arxiv
\section{Introduction} \label{sec:introduction} The COVID-19 pandemic has engulfed the world with a large portion of the population infected. These staggering numbers highlight various opportunities in existing technologies and infrastructure to contain the spread of this highly contagious virus. The impact of Coronavirus is both global and unpredictable. Also, the supply chain shock it is causing will most definitely and substantially cut into the worldwide manufacturing revenue of US \$15 trillion currently forecasts for 2020 by global tech market advisory firms~\cite{ABI_research}. The lack of an approved medicine to cure this disease presses the need for prevention and mitigation mechanisms to minimize the spread. \textit{Social distancing} measures, including country wide lock-downs, travel prohibition, quarantining hot-spots, and limiting customers at essential businesses, are slowly restricting the spread of the virus. It is paramount, in such critical situations, to implement swift mechanisms, and various agencies work in coordination to limit the spread of the disease. It is expected that broad range of situational intelligence and automated targeted response is needed throughout the community to ensure the safety of people and assets, with an aim to lower the fatalities and minimize impact on the economy. However, even in the cities where strict social distancing guidelines were issued to limited movement, it has been noticed the technology can play a role in enforcing such restrictions. In the United States~\cite{smartcitiesdive}, New York, San Francisco, New Orleans, and Philadelphia ranked as the most vulnerable specifically in terms of health risks. These large cities are vulnerable due to high population density and higher use of public transportation, according to the report. Also, about 61\% percent of New York City residents commute using public transportation compared to less than 0.1\% of residents from Amarillo, TX, which ranked as one of the least vulnerable cities in the United States. It is clearly evident, with the surge in the number of cases for COVID-19, that our cities are not prepared for fending off such pandemics and outbreaks, assisting in tracking the suspects, limiting movement of people to vulnerable neighborhoods, directing and monitoring traffic, or even pushing alerts to commuters. There are some initiatives worldwide which were deployed on ad-hoc basis to fight this pandemic. Countries and cities deployed drones with loudspeakers to communicate rules and government mandated precautions with residents. Wearable devices \cite{sphcc} have been mandated for the population to enforce quarantine measures, whereas telecommunication data has been used to monitor the large gathering of people. Corporations are developing applications for contact tracing \cite{contact-tracing,singapore-contact} which can effectively be enabled to trigger an alert if someone gets in contact with newly diagnosed COVID-19 patients. Currently many countries around the world are approaching the idea of deploying ``smart'' cities, including USA, Netherlands, China, and Japan, to say the least. For instance, Amsterdam's latest model of \textit{SmartCity 3.0}~\cite{ams-smartcity} motivates active participation of citizens and private organizations along with the government in creating and expanding smart city solutions. This initiative includes research, projects and data sharing in areas such as infrastructure and technology, smart energy and water, and Intelligent Transportation System (ITS). Another prime example is Smart America~\cite{smartamerica}, a White House Presidential Innovation Fellow project with the goal to research smart city related topics such as ITS, Smart Manufacturing, Healthcare, Smart Energy, and Disaster Response. Although many cities are taking the initiative of turning into smart cities, there are many challenges that need to be addressed. To be effectively prepared for future outbreaks and enforce protocols, it is expected that smart cities and ITS technology will host a range of data driven services together with deployed sensors to not only help in enforcing community wide social distancing measure but also assist in early detection of such outbreaks. This article focuses on proposing a novel architecture along with several use-cases which can be developed to create a smart city and ITS inspired data driven system which can help to enable and enforce community distancing measures during pandemics and high impact low frequency (HILF) events. We also highlight challenges and future opportunities to empower future smart cities and ITS to cater such circumstances. \iffalse \textbf{Current status of smart city and ITS around the world:} Currently many countries around the world are approaching the idea of deploying “smart” cities, including USA, Netherlands, China, and Japan, to say the least. For instance, Amsterdam is one of the first and leading cities to start the process of becoming a smart city. Its latest model of Smart City 3.0 motivates the active participation of citizens and private organizations along with the government in creating and expanding smart city solutions. This initiative includes research, projects and data sharing in areas such as Infrastructure and technology, Smart energy and water, and ITS. Another prime example is SmartAmerica[], a White House Presidential Innovation Fellow project with the goal to research smart city related topics such as ITS, Smart Manufacturing, Healthcare, Smart Energy, and Disaster Response. Although many cities are taking the initiative of turning into smart cities, there are many challenges that need to be addressed. \fi \section{Architecture} Figure 1 shows a holistic overview of the smart city and ITS architecture. The proposed conceptual model specifically caters to the requirements and support applications which are envisioned to enforce social distancing and community measures in pandemics and high impact low frequency (HILF) events like COVID-19. In simple terms, this architecture provides the common basis for planners and engineers to conceive, design and implement system together with concerns relevant to large number of stakeholders to offer services, alerts and data driven applications. This service oriented architecture is scalable to offer applications in wide geographic location offering quality of service (QoS). Overall, the architecture consists of physical devices, including road-side sensors, smart traffic lights and connected cars, having the ability to record real time data and exchange messages with nearby entities and upload relevant information to central cloud facilities for processing. At the same time, such smart physical devices can also replicate edge computes to offer the capability for real time low latency communication supported by ITS such as vehicle-to-vehicle (V2V), vehicle-to-infrastructure (V2I) or vehicle-to-everything (V2X). The flexibility of the architecture to adapt to various use-case requirements can be achieved by having a hybrid edge cloud supported model which enable dynamic real time needs, and at the same time offer infinite computation on data captured using central cloud infrastructures. Basic Safety Messages (BSMs) can also be used to enable V2X communication with information pertaining to an event, location or even severity. It is also viable to create \textit{digital twins} for various smart devices to offer a virtual counterpart for each physical object. These twins, based on the data collected in the real environment, can provide insights to improve the operations, increase efficiency and discover issues. The participating entities including vehicles, law enforcement, drones, parking sensors or other roadside units (RSUs) must enroll with a central authority to receive certificates and ensure trustworthiness of messages exchanged among entities. The communication technologies which can enable the messages exchange can include cellular LTE, WiFi, 5G or Dedicated Short Range Communication (DSRC). In addition, Message Queuing Telemetry Transport (MQTT) messaging protocol has been widely used to support physical entity to cloud service providers like Amazon Web Services (AWS) or Microsoft Azure. This architecture will need multiple technologies and communication protocols to cater different use cases. As shown in the figure, the communication (with dashed lines) can happen among different physical entities, using cloud supported services, edge assisted messaging or even peer to peer model. Such infrastructures and supported technologies will need long term investment and partnership among public and private entities to enable hundreds of smart devices interaction with each other. The architecture further focuses on offering data sharing platform across interested parties which can help speed up reaction times and also enforce community measures in critical situations. By real time data sharing with law enforcement, city authorities or other stakeholders, it is expected that more efficient and automated response mechanisms can be implemented. For example, in order to ensure social distancing and limiting community gatherings, drones can be used to collect information about the number of individuals and messages can be sent to the near by traffic signals to divert traffic to other location. At the same time, automatic disinfectant and fogging can be deployed in certain locations based number of existing cases, vulnerability or large gatherings. Parking availability can be shared in real time with the cloud services and registered individuals can be allotted a time to ensure minimal human interface. These applications (as more discussed in the next section) allow cities to gain insights and identity problems with low response time, and at the same time enable efficient resource planning in times with high resource demand in most affected areas. With continuous monitoring, data capturing and real time communication, an efficient and more productive safer environment can be created. \begin{figure}[t] \centering \includegraphics[scale=0.45]{Architecture-v1.png} \caption{Smart City and ITS Architecture} \label{fig-arch} \end{figure} \section{Usecases} In this section, we will discuss some important usecases that describe how smart city infrastructure and various Intelligent Transportation systems technologies can be used to enforce and enable social distancing measures in a swift and timely manner, together with data driven AI applications. \subsection{Monitoring Large Gatherings Monitoring large gatherings during pandemics is essential to regular social distancing. ITS and Smart cities infrastructures can play an important role in such a scenario. During the COVID-19 outbreak, multiple countries have started utilizing drones and other AI assisted technologies to enforce social distancing rules (including lock down rules). For example, state police in Western Australia, Derbyshire police in England, the local police in Italy, and local police in New Jersey~\cite{us-drones} plan to utilize drones to enforce social distancing. The drones can be used to monitor areas like, recreational parks, beaches, and public transits, ensuring people comply with the most recent forged gathering rules. Based on the severity of infection in a particular place, more or less stringent rules can be used. This can be done by using body heat temperature sensors to detect the number of people present at one particular place. Upon detecting a higher than the allowed number, drones can instruct the people to evacuate the place due to a higher chance of getting infected. It can also be used to detect proximity of people to enforce distancing rules. If a particular area is known to be a hot infectious spot, a complete lock down can be enforced. Drones can also help in informing people about the newest enforced rules. By taking advantage of ITS and smart cities infrastructures, different rules can be enforced in different locations. However, ongoing change of social distancing rules can be hard to keep up with, especially during an outbreak in which people are in a state of stress. Using drones with attached loud speakers to inform the people at a particular location can be very useful. This will help ensure that people are aware of the recent enforcement rules to prevent unintended break of rules. These drones can also communicate with automated disinfectant spray vehicles to remotely monitor there effectiveness and direct to needed communities. As such having a systematic way of incorporating drones as part of ITS infrastructure, in particular, and smart cities infrastructure, in general, can be very useful. \subsection{Smart Parking Smart parking~\cite{khanna2016iot} can play an important role in enforcing social distancing. In smart parking, sensors and other AI based techniques are used to determine whether a particular spot on the street or in a parking garage is occupied or vacant. Using such information, different restrictions can be added on the number of vehicles parked at a particular location. For example, a parking space at a grocery store might allow more cars to be parked at one particular time than a senior home which is more critical due to the occupancy of elderly people who are more prone to COVID-19. Changing the parking rules at different locations, each with its own parking rules to alleviate gathering, can be challenging. Specially, since such rules can be updated everyday and informing law enforcement agents of these updates can be a daunting task. Smart parking can automatically enforce these rules while informing the vehicles through relayed messages. \subsection{Re-Routing Traffic to Reduce Footprint ITS and smart city infrastructures can be useful in creating on the fly designated, high speed routes to critical and vulnerable locations like hospitals to supply resources like ventilators, Personal Protective Equipment (PPEs), etc. With the shortage of such supplies due to high volume of patients infected, many states are pooling all the surgical resources available in state hospitals and assigning them on per need basis. In such a scenario, real time count of the supplies can be maintained in hospitals, that can automatically initiate a message to the central pool location. Once initiated, designated enforcement vehicles can be loaded with emergency supplies and fastest routes can be created on the fly with smart traffic lights, and roadside units to provide free passage. At the same time V2V and V2I messaging can be used among vehicles and infrastructures to ensure fastest delivery. It is also possible to create AI assisted systems that direct vehicles to drive through COVID-19 testing locations based on an area and waiting time at different locations. This can be enforced with automated waiting count at various testing areas and sending such data to a central cloud, which will then forward messages to vehicles directing them to different available locations. Such enforcement can also limit movement of visitors in old-age homes or localities with greater density of senior citizen population. More stringent policies can be implemented in states and counties with high rates of health conditions like, obesity, diabetes, hypertension, heart, and kidney disease. Such architecture can also enable the number of delivery drivers from restaurants and grocery stores to allow a certain number of people at a time in any location. \textit{E-Passes} can be generated using Radio-frequency identification (RFID) tags that can be placed on a vehicle, to keep track on who is on the road. This enforcement can also help in limiting the number of vehicles on the road at one time. For example, it should be enforced that no one from one household is allowed to visit grocery store more than once in 10 days. If the vehicle registered for a household is detected on road, it can be confiscated, and an automatic ticket/fine can be issued. It is also possible to assign a designated time and date for a particular vehicle belonging to a household. If another vehicle from the same household is detected by roadside sensors without an approved RFID, law enforcement can take policy based actions. Such RFID can be issued at a nearby Department of Motor Vehicles (DMVs) which can also allow only one vehicle from each household to be used for driving. In case of front-line workers like healthcare providers, first responders, or delivery personnel, exemptions can be made on a case by case basis for allowed vehicles. As a result of various social distancing policies limiting store/building occupancy, people are waiting outside various businesses like grocery stores and pharmacies. Queues have been formed outside such essential businesses to comply with various maximum headcount policy. In such a scenario, people are still exposed to risk of aerosol infection because of the waiting time outside the stores even though social distancing is followed. Using ITS and smart infrastructures, vehicles can input their destination in the car Global Positioning System (GPS), which can interact with a central command authority to decide if it is feasible and allowed to go to the designated location. Various AI assisted systems can be built to add this functionality for a smart city. A vehicle can be directed to other similar stores with a lower foot count and less wait time. It is also possible to send a message to the car from the store about various designated parking spots available. Law enforcement can automatically be notified in case of violations and automatically issue tickets/fines. \subsection{ITS, Big Data \& AI} An ITS collects a lot of data about vehicles and traffic patterns. Specifically, Dedicated Short Range Communications (DSRC) messages have been used in ITS to codify communication. DSRC are one-way or two-way short-range to medium-range wireless communication channels specifically designed for automotive use. These include fields like, latitude, longitude, time, heading angle, speed, acceleration, brake status, steering angle, headlight status, wiper status, external temperature, turn signal status, vehicle length, vehicle width, vehicle mass. Augmented with other data sources which include, ambient temperature, ambient air pressure, traction control status, road conditions, etc. This data source can serve as a medium to create multiple big data and AI systems that can provide value by enabling and enforcing social distancing measures. One such big data system can be leveraged to find traffic hotspots in a smart city. These traffic hot spots can inform the local government about areas which are frequented by the population and must be monitored regularly. Finding these traffic hotspots is also necessary during the disinfection phase. Multiple cities all over the world have deployed heavy machinery to spray antiseptic solutions along high traffic areas such as, markets, streets, shops, religious and public buildings. Leveraging smart city big data and AI applications will help empirically prioritize specific locations which are proven traffic hotspots. In a futuristic smart city environment, a system can be built to deploy drones to clean, disinfect and monitor these traffic hotspots. An ITS system can also be used to track vehicles currently on the road. This specific information can be used by the local law enforcement to create policies that enable enforcement of social distancing measures. An example situation for such a case is tracking vehicles which have come from areas that have a large number of COVID-19 cases. Here the DSRC messages or AI based registration plate readers, can be used to read state registration number plates that can inform the local authorities about the origins of a vehicle. \begin{figure}[t] \centering \includegraphics[width=.5\textwidth]{Challenges-v2.png} \caption{Research Challenges and Future Directions.} \label{fig-arch} \end{figure} \section{Challenges and Future Directions} Building such a social distancing enforcement system at a smart city level is challenging. Researchers and developers need to keep these in mind as in when they are developing such systems. Some of them have been discussed below. \textbf{Security and Privacy -} One concern relates to the security and privacy ~\cite{van2016privacy, fries2012meeting} of general citizens who live in smart cities and drive on roads equipped with intelligent transportation systems. While building these AI and big data systems, researchers need to make sure that they de-anonymize the data required. We should also use various access control techniques to ensure the data maintains its confidentiality, availability, and integrity. In the future, these smart cities will generate a large amount of personal data as in when citizens will interact with the smart city. Security and privacy preserving techniques need to be built in parallel as we develop these smart cities. \textbf{AI \& Big Data -} Another challenge in creating various big data and AI systems \cite{chauhan2016addressing} is availability and the amount of data needed. Most of the big data and AI applications described above require a large quantity of labeled data. Multiple partnerships must be developed between the private and the public sector to create datasets that can then be leveraged to build these smart city models. When we develop various AI assisted usecases, special attention needs to be given to keep these models fair and without bias. Techniques that ensure bias free decision computations are being created and need to introduced in various smart city systems. \textbf{Legislation and Policy -} As stated earlier, privacy is one technical concern for social distancing using smart cities and ITS; however, technological means must complement legislation~\cite{ncsl}. Smart city and ITS technologies are rapidly on the rise but legislation and policies are lacking and may fall short for a long period of time. Formal policies for social distancing privacy are necessary and must address several issues including secure data collection, video surveillance, users/residents consent, and trusted third-parties involved, to say the least. Such legislation must be abided by when deploying smart cities and ITS technologies. As such, research on legislation and policy, including engagement on public policy development debates, is necessary to successfully integrate technical privacy solutions in the smart city and ITS ecosystem. Not only privacy related legislation is needed, but other policies that encourage innovation, competition, and private investment in social distancing enforcement using smart cities and ITS technologies are essential. Such policies should include incentives and support for partnership between public and private sectors and removal of government barriers. They should also highlight societal benefits of advancements in large-scale social distancing enforcement such as economical growth and saving lives. \textbf{Deployment Cost -} Deployment cost of smart cities and ITS is massive ranging from infrastructure costs to operating costs. For instance, attaching devices to electric public lighting not only needs municipality collaboration but also isolation from other critical systems which poses a burden on time and effort and, in turn, increases the costs. Another example, battery powered devices (e.g., drones) are limited in the amount of time they operate and the information they can transmit by the battery lifetime. Not to mention, regular maintenance of such devices can be very costly, given they are usually deployed in large numbers. Costs also include operating costs. For instance, NYC operated an Automated Speed Enforcement program in 140 school zones with 180 speed cameras for over two years at a cost of \$69,460,446~\cite{itscosts}. It is worth mentioning that enforcing social distancing may add on to those aforementioned costs due to the need of particular devices and sensors (e.g., drones equipped with body heat sensors for crowd detection). Even though the deployment costs of smart cities and ITS are massive, they can help reduce costs on other occasions~\cite{lam2017study}. For example, drones monitoring crowds for social distancing can save the expenses of law enforcement officers physically monitoring the streets and allow them to attend to more crucial matters. Additionally, enforcing social distancing in and by itself reduces costs. During the COVID-19 outbreak cutting down the number of patients will substantially reduce the healthcare sector costs. As such, developing a framework for social distance enforcement in an effective, timely and cost-effective manner is an important future research direction. Another important future research direction includes benefit-cost analysis studies for smart cities and ITS. As an example, ITS traffic re-routing and predictive analysis can help reduce traffic congestion. Not only will it serve in enforcing social distancing rules but also save costs of unnecessary trips to crowded destinations (e.g., grocery stores). These, including aforementioned scenarios, are examples where enforcing social distancing helps in saving money. Analysis on the degree to which enforcing social distancing rules potentially reduces costs is crucial as it incentivizes the government and reduces the economic burdens of applying a large-scale social distancing enforcement. \section{Conclusion} COVID-19 outbreak is unprecedented and has disrupted lives of millions of people across the globe. This pandemic has opened several research challenges and opportunities that our community must address to equip itself for the future. The proposed architecture and AI assisted applications discussed in the article can be used to effectively and timely enforce social distancing community measures, and optimize the use of resources in critical situations. This article offers a conceptual overview and serves as a steppingstone to extensive research and deployment of automated data driven technologies in smart city and intelligent transportation systems. For future, we envision to develop these AI driven applications for wider adoption in the community. \bibliographystyle{unsrt}
{'timestamp': '2020-04-21T02:26:29', 'yymm': '2004', 'arxiv_id': '2004.09246', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09246'}
arxiv
\section{Introduction} Given a set of point sites in the plane, the Voronoi diagram is the corresponding partition of the plane into cells, where each cell is the locus of points in the plane sharing the same closest site. This fundamental structure has a wide variety of applications. When coupled with a point location data structure, it can be used to quickly answer nearest neighbor queries. Other applications include robot motion planning, modeling natural processes in areas such as biology, chemistry, and physics, and moreover, the dual of the Voronoi diagram is the well known Delaunay triangulation. See the book \cite{Franz2013} for an extensive coverage of the topic. Many of the varied applications of Voronoi diagrams require generalizing its definition in one way or another, such as adding weights or otherwise altering the distance function, moving to higher dimensions, or considering alternative types of sites. While some of these generalizations retain the highly desirable linear worst-case complexity of the standard Voronoi diagram, many others unfortunately have quadratic worst-case complexity or more. Within the field of Computational Geometry, particularly in recent years, there have been a number of works analyzing the expected complexity of various geometric structures when the input is assumed to have some form of randomness. Here we continue this line of work, by studying the expected complexity of two previously considered Voronoi diagram variants. \myparagraph{Directional and weighted Voronoi diagrams.} A natural generalization to consider is when each site is only visible to some subset of the plane. Here we are interested in the so called visual restriction Voronoi diagram (VRVD)~\cite{AurenhammerSXZ14,FanLWZ14}, where a given site $p$ is only visible to the subset of points contained in some cone with base point $p$ and angle $\alpha_p$. These diagrams model scenarios where the site has a restricted field of view, such as may be the case with various optical sensors or human vision. For example, in a football game, each player has their own field of view at any given time, and the location of the ball in the VRVD tells us which player is the closest to the ball among those who can see it. When the visible region for each site is a half-plane whose boundary passes through the site (i.e., a VRVD where $\alpha_p=\pi/2$ for each site $p$), such diagrams are called semi Voronoi diagrams~\cite{ChengLX10}. Just like general VRVD's, semi Voronoi diagrams have $\Theta(n^2)$ worst-case complexity. Our expected analysis is shown for the semi Voronoi diagram case, however, we remark a similar analysis implies the same bounds hold more generally for VRVD's. The other generalization we consider is when sites have weights. There are many natural ways to incorporate weights into the distance function of each site. Three of the most common are additive, power, and multiplicative Voronoi diagrams (see \cite{Franz2013}). (For brevity, throughout we use the prefix \emph{multiplicative}, rather than the more common \emph{multiplicatively-weighted}.) For additive Voronoi diagrams the distance from a point $x$ in the plane to a given site $p$ is $d(x,p) = ||x-p||+\alpha_p$, for some constant $\alpha_p$, which can vary for each site. For power diagrams the distance is given by $d(x,p) = ||x-p||^2-\alpha_p^2$. For multiplicative diagrams the distance is given by $d(x,p) = \alpha_p\cdot ||x-p||$. The worst-case complexity for additive and power diagrams is only linear. Here our focus is on multiplicative diagrams, whose worst-case complexity is known to be $\Theta(n^2)$~\cite{AurenhammerE84}. These diagrams are used to model, for example, crystal growth where crystals grow together from a set of sites at different rates. \myparagraph{Previous expected complexity bounds.} There are many previous results on the expected complexity of various geometric structures under one type of randomness assumption or another. Here we focus on previous results relating to Voronoi diagrams. For point sites in $\Re^d$, the worst-case complexity of the Voronoi diagram is known to be $\Theta(n^{\lceil d/2\rceil})$, however, if the sites are sampled uniformly at random from a $d$-ball or hypercube, for constant $d$, then the expected complexity is $O(n)$ \cite{bdms-accvd-05,d-hdvdl-89}. For a set of $n$ point sites on a terrain consisting of $m$ triangles, Aronov \textit{et al.}~\cite{AronovBT08} showed that, if the terrain satisfies certain realistic input assumptions then the worst-case complexity of the geodesic Voronoi diagram is $\Theta(m+n\sqrt{m})$. Under a relaxed set of assumption, Driemel \textit{et al.}~\cite{DriemelHR16} showed that the expected complexity is only $O(n+m)$, when the sites are sampled uniformly at random from the terrain domain. Relevant to the current paper, Har-Peled and Raichel~\cite{Har-PeledR15} showed that, for any set of point site locations in the plane and any set of weights, if the weights are assigned to the points according to a random permutation, then the expected complexity of the multiplicative Voronoi diagram is $O(n\log^2 n)$. The motivation for this work came from Agarwal \textit{et al.}\cite{AgarwalHKS14}, who showed that if one randomly fattens a set of segments in the plane, by taking the Minkowski sum of each segment with a ball of random radius, then the expected complexity of the union is near linear, despite having quadratic worst-case complexity. In a follow-up work to \cite{Har-PeledR15}, Chang \textit{et al.}\cite{ChangHR16} defined the candidate diagram, a generalization of weighted diagrams to multi-criteria objective functions, and showed that under similar randomized input assumptions the expected complexity of such diagrams is $O(n\operatorname{polylog} n)$. \myparagraph{Our results and significance.} Our first result concerns semi Voronoi diagrams, where the visible region of each site is a half-plane whose bounding line passes through the site, and where the worst-case complexity is quadratic. For any set of site locations and bounding lines, we show that if the visible side of each site's bounding line is sampled uniformly at random, then the expected complexity of the semi Voronoi diagram is linear, and $O(n\log^3 n)$ with high probability. To achieve this we argue that our randomness assumption implies that any point in the plane is likely to be visible by one of its $k$ nearest neighbors, for large enough $k$. Thus within each cell of the order-$k$ Voronoi diagram, one can argue the complexity of semi Voronoi diagram is $O(k^2)$, and so summing over all $O(nk)$ cells gives an $O(nk^3)$ bound. This is a variant of the candidate diagram approach introduced in \cite{Har-PeledR15}. Unfortunately, in general this approach requires $k$ to be more than a constant, which will not yield the desired linear bound. Thus here, in order to get a linear bound, we give a new refined version of this approach, by carefully allowing $k$ to vary as needed, in the end producing a diagram which is the union of order-$k$ cells, for various values of $k$. The main focus of the paper is the second part concerning multiplicative Voronoi diagrams, where the distance to each site is the Euclidean distance multiplied by some site-dependent weight, and where the worst-case complexity is quadratic. We first argue that if the weights are sampled from a set with constant size, then interestingly a similar refined candidate diagram approach yields a linear bound. Our main result, however, considers the more challenging case when no restrictions are made on the weights, but instead the site locations are sampled uniformly at random from the unit square. For this case we show that in any grid cell of side length $1/\sqrt{n}$ in the unit square the expected complexity of the multiplicative diagram is $O(1)$. This implies an $O(n)$ expected bound for the multiplicative diagram over the whole unit square. This improves over the $O(n\log^2 n)$ bound of \cite{Har-PeledR15} for this case, by using an interesting new approach which ``stretches'' sites about a given cell based on their weights, thus approximately transforming the weighted diagram into an unweighted one with respect to a given cell. As this main result is technically very challenging, it is placed last. It is important to note the significance of our bounds being linear. Given a randomness assumption, one wishes to prove an optimal expected complexity bound, and for the diagrams we consider linear bounds are immediately optimal. However, even when a linear bound seems natural, many standard approaches to bounding the expected complexity yield additional $\log$ factors. That is, not only are linear bounds desirable, but also they are nontrivial to obtain. However, when they are obtained, they reveal the true expected complexity of the structure, free from artifacts of the analysis. \section{ Preliminaries}\seclab{prelim} \myparagraph{The standard Voronoi diagram:} Let $S=\{s_1,s_2,...,s_n \}\subset \Re^2$ be a set of $n$ point \emph{sites} in the plane. Let $\dist{x}{y}$ denote the Euclidean distance from $x$ to $y$, and for two sites $s_i,s_j\in S$ let $\beta(s_i,s_j)$ denote their bisector, that is the set of points $x$ in plane such that $\dist{s_i}{x}=\dist{s_j}{x}$. Any site $s_i\in S$ induces a distance function $f_i(x) = \dist{s_i}{x}$ defined for any point $x$ in the plane. For any subset $T \subseteq S$, the \emph{Voronoi cell} of $s_i\in T$ with respect to $T$, $\VorCell{s_i}{T}=\{x\in \Re^2 \mid \forall s_j \in T \quad f_{i}(x) \leq f_{j}(x) \}$, is the locus of points in the plane having $s_i$ as their closest site from $T$. We define the \emph{Voronoi diagram} of $T$, denoted $\VorX{T}$, as the partition of the plane into Voronoi cells induced by the minimization diagram (see \cite{go-hdcg-04}) of the set of distance functions $\{f_i \mid s_i \in T\}$, that is the projection onto the plane of the lower envelope of the surfaces defined by these bivariate functions. One can view the union, $U$, of the boundaries of the cells in the Voronoi diagram as a planar graph. Specifically, define a \emph{Voronoi vertex} as any point in $U$ which is equidistant to three sites in $S$ (happening at the intersection of bisectors). For simplicity, we make the general position assumption that no point is equidistant to four or more sites. Furthermore, define a \emph{Voronoi edge} as any maximal connected subset of $U$ which does not contain a Voronoi vertex. (For each edge to have two endpoints we include the “point” at infinity, i.e., the graph is defined on the stereographic projection of the plane onto the sphere.) The complexity of the Voronoi diagram is then defined as the total number of Voronoi edges, vertices, and cells. As the cells are simply connected sets, which are faces of a straight-line planar graph, the overall complexity is $\Theta(n)$. \myparagraph{Order-$k$ Voronoi diagram:} Let ${S}$ be a set of $n$ point sites in the plane. The \emph{order-$k$ Voronoi diagram} of ${S}$ is the partition of the plane into cells, where each cell is the locus of points having the same set of $k$ nearest sites of ${S}$ (the ordering of these $k$ sites by distance can vary within the cell). It is not hard to see that this again defines a straight-line partition of the plane into cells where the edges on the boundary of a cell are composed of bisector pieces. The worst-case complexity of this diagram is $\Theta\pth{k(n-k)}$ (see \cite[Section 6.5]{Franz2013}). We also consider the diagram where every point in a cell not only has the same $k$ nearest sites, but also the same ordering of distances to these sites. We refer to this as the order-$k$ \emph{sequence} Voronoi diagram, known to have $O(nk^3)$ worst-case complexity (see \apndref{shallow}). \myparagraph{Semi Voronoi diagram:} Let $S=\{s_1,s_2,...,s_n \}$ be a set of $n$ point sites in the plane, where for each $s_i$ there is an associated closed half-plane $\mathsf{H}(s_i)$, whose boundary passes through $s_i$. We use $L(s_i)$ to denote the bounding line of $\mathsf{H}(s_i)$. For any point $x$ in the plane and any site $s_i\in S$, we say that $x$ and $s_i$ are visible to each other when $x\in \mathsf{H}(s_i)$. Given a point $x$, let $S(x)=\{s_i\in S \mid x\in \mathsf{H}(s_i)\}$ denote the set of sites which are visible to $x$. For any subset $T \subseteq S$, define the \emph{semi Voronoi cell} of $s_i\in T$ with respect to $T$ as, $\SVorCell{s_i}{T}=\{x\in \mathsf{H}(s_i) \mid \forall s_j \in T\cap S(x) \quad \dist{x}{s_i} \leq \dist{x}{s_j} \}$. It is possible that there are points in the plane which are not visible by any site in $S$. If desired, this technicality can be avoided by adding a pair of sites far away from $S$ which combined can see the entire plane. As before, semi Voronoi cells define a straight-line partition of the plane, where now the edges on the boundary of a cell are either portions of a bisector or of a half-plane boundary. In the worst case, the semi Voronoi diagram can have quadratic complexity~\cite{FanLWZ14}. \myparagraph{Random semi Voronoi diagram:} We consider semi Voronoi diagrams where the set of sites $S=\{s_1,\ldots,s_n\}$ is allowed to be any fixed set of $n$ points in general position. For each site $s_i$, the line bounding the half-plane of $s_i$, $L(s_i)$, is allowed to be any fixed line in $\Re^2$ passing through $s_i$. Such a line defines two possible visible closed half-spaces. We assume that independently for each site $s_i$, one of these two spaces is sampled uniformly at random. An alternative natural assumption is that the normal of the half-plane for each site is sampled uniformly at random from $[0,2\pi)$. Note our model is strictly stronger, that is any bound we prove will imply the same bound for this alternative formulation. This is because one can think of sampling normals from $[0,2\pi)$, as instead first sampling directions for the bounding lines from $[0,\pi)$, and then sampling one of the two sides of each line for the normal. \myparagraph{Multiplicative Voronoi diagram:} Let $S=\{s_1,s_2,...,s_n \}$ be a set of $n$ point sites in the plane, where for each site $s_i$ there is an associated weight $w_i>0$. Any site $s_i\in S$ induces a distance function $f_i(x) = w_i\cdot \dist{s_i}{x}$ defined for any point $x$ in the plane. For any subset $T \subseteq S$, the \emph{Voronoi cell} of $s_i\in T$ with respect to $T$, $\VorCell{s_i}{T}=\{x\in \Re^2 \mid \forall s_j \in T \quad f_{i}(x) \leq f_{j}(x) \}$, is the locus of points in the plane having $s_i$ as their closest site from $T$. The \emph{multiplicative Voronoi diagram} of $T$, denoted $\WVorX{T}$, is the partition of the plane into Voronoi cells induced by the minimization diagram of the distance functions $\{f_i \mid s_i \in T\}$. Note that unlike the standard Voronoi diagram, the bisector of two sites is in general an Apollonius disk, potentially leading to disconnected cells. Ultimately, the diagram still defines a planar arrangement and so its complexity, denoted by $|\WVorX{S}|$, can still be defined as the number of edges, faces, and vertices of this arrangement. Note the edges are circular arcs and straight line segments and thus are still constant complexity curves. In the worst case, the multiplicative Voronoi diagram has $\Theta(n^2)$ complexity \cite{AurenhammerE84}. \section{The Expected Complexity of Random Semi Voronoi Diagrams}\seclab{semi} \subsection{The probability of covering the plane} As it is used in our later calculations, we first bound the probability that for a given subset $X$ of $k$ sites of $S$ that there exists a point in the plane not visible to any site in $X$. \begin{lemma}\lemlab{probability} For any set $X=\{x_1,\ldots,x_k\}$ of $k$ sites $\Prob{(\bigcup_{x_i\in X} \SVorCell{x_i}{X} )\neq \Re^2} \leq (k(k+1)+2)/2^{k+1}= O(k^2/2^k)$. \end{lemma} \begin{proof} Consider the arrangement of the $k$ bounding lines $L(x_1),\ldots,L(x_k)$. Let $\mathcal{F}$ denote the set of faces in this arrangement (i.e., the connected components of the complement of the union of lines), and note that $|\mathcal{F}| \leq k(k+1)/2+1 = O(k^2)$. Observe that for any face $f\in \mathcal{F}$ and any fixed site $x_i\in X$, either every point in $f$ is visible by $x_i$ or no point in $f$ is visible by $x_i$. Moreover, the probability that face $f$ is not visible by site $x_i$ is $\Prob{\mathsf{H}(x_i) \cap f =\emptyset} \leq 1/2$. Hence the probability that a face $f$ is not visible by any of the $k$ sites is \[ \Prob{\bigcup_{x_i\in X} \mathsf{H}(x_i) \cap f =\emptyset} \leq 1/2^k. \] Hence the probability that at least one face in $\mathcal{F}$ is is not visible by any sites in $X$ is \[ \Prob{\!\pth{\bigcup_{x_i\in X} \SVorCell{x_i}{X} } \neq \Re^2} \leq \sum_{f\in \mathcal{F}} \Prob{\bigcup_{x_i\in X} \mathsf{H}(x_i) \cap f =\emptyset} \leq \!\frac{k(k\!+\!1)\!+\!2}{2^{k+1}} = O\pth{\frac{k^2}{2^k}} \] \end{proof} \subsection{A simple near linear bound} Ultimately we can show that the expected complexity of a random semi Voronoi diagram is linear, however, here we first show that \lemref{probability} implies a simple near linear bound which also holds with high probability. Specifically, we say that a quantity is bounded by $O(f(n))$ with high probability, if for any constant $\alpha$ there exists a constant $\beta$, depending on $\alpha$, such that the quantity is at most $\beta \cdot f(n)$ with probability at least $1-1/n^\alpha$. \begin{lemma} \lemlab{polybound} Let $S=\{s_1,\ldots, s_n\}\subset \Re^2$ be a set of $n$ sites, where each site has a corresponding line $L(s_i)$ passing through $s_i$. For each $s_i$, sample a half-plane $\mathsf{H}(s_i)$ uniformly at random from the two half-planes whose boundary is $L(s_i)$. Then the expected complexity of the semi Voronoi diagram on $S$ is $O(n \log^3 n)$, and moreover this bound holds with high probability. \end{lemma} \begin{proof} Let $k=c \log n$, for some constant $c$. Consider the order-$k$ Voronoi diagram of $S$. First triangulate this diagram so the boundary of each cell has constant complexity. (Note triangulating does not asymptotically change the number of cells.) Fix any cell $\Delta$ in this triangulation, which in turn fixes some (unordered) set $X$ of $k$-nearest sites. By \lemref{probability}, \[ \Prob{\pth{\bigcup_{x_i\in X} \SVorCell{x_i}{X}} \neq \Re^2} = O(k^2/2^k) = O((c\log n)^2/2^{c\log n}) =O(1/n^{c-\eps'}), \] for any arbitrarily small value $\eps'>0$. Thus with polynomially high probability for every point in $\Delta$ its closest visible site will be in $X$. Now let $T$ be the set of all $O(k(n-k)) = O(n\log n)$ triangles in the triangulation of the order-$k$ diagram. Observe that the above high probability bound applies to any triangle $\Delta\in T$. Thus taking the union bound we have that with probability at least $1-1/n^{c-(1+\eps)}$ (where $\eps>\eps'>0$ is an arbitrarily small value), simultaneously for every triangle $\Delta$, every point in $\Delta$ will be visible by one of its $k$ closest sites. Let $e$ denote this event happening (and $\overline{e}$ denote it not happening). Conditioning on $e$ happening, there are only $O(k)=O(\log n)$ relevant sites which contribute to the semi Voronoi diagram of any cell $\Delta$. Thus the total complexity of the semi Voronoi diagram restricted to any cell $\Delta$ is at most $O(\log^2 n)$, as the semi Voronoi diagram has worst-case quadratic complexity~\cite{FanLWZ14}. (Note that as $\Delta$ is a triangle, we can ignore the added complexity due to clipping the semi Voronoi diagram of these sites to $\Delta$.) On the other hand, if $\overline{e}$ happens, then the worst-case complexity of the entire semi Voronoi diagram is still $O(n^2)$. Now the complexity of the semi Voronoi diagram is bounded by the sum over the cells in the triangulation of the complexity of the diagram restricted to each cell. Thus the above already implies that with high probability the complexity of the semi Voronoi diagram is $O\pth{\sum_{\Delta\in T} \log^2 n} = O(n\log^3 n)$. As for the expected value, by choosing $c$ sufficiently large, \begin{align*} &= \Ex{|\SVorX{S}| \sep e}\Prob{e} + \Ex{|\SVorX{S}| \sep {\overline{e}} }\Prob{\overline{e}} = O\pth{\sum_{\Delta\in T} \log^2 n}\Prob{e} + O(n^2)\Prob{\overline{e}}\\ &= O(n\log^3 n)\Prob{e} + O(n^2)\Prob{\overline{e}} = O(n\log^3 n)\Prob{e} + O(n^2)\cdot (1/n^{c-(1+\eps)})\\ &= O(n\log^3 n) + O(1/n^{c-(3+\eps)}) = O(n\log^3 n) \end{align*} \end{proof} \subsection{An optimal linear bound} The previous subsection partitioned the plane based on the order-$k$ Voronoi diagram, for $k=c\log n$, and then argued that simultaneously for all cells one of the $k$ nearest sites will be visible. This argument is rather coarse, but instead of using a fixed large value for $k$, if one is more careful and allows $k$ to vary, then one can argue the expected complexity is linear. Note that in the following, rather than using the standard unordered order-$k$ Voronoi diagram, we use the more refined order-$k$ \emph{sequence} Voronoi diagram as defined above. \begin{theorem}\thmlab{refined} Let $S=\{s_1,\ldots, s_n\}\subset \Re^2$ be a set of $n$ sites, where each site has a corresponding line $L(s_i)$ passing through $s_i$. For each $s_i$, sample a half-plane $\mathsf{H}(s_i)$ uniformly at random from the set of two half-planes whose boundary is $L(s_i)$ (i.e., each has $1/2$ probability). Then the expected complexity of the semi Voronoi diagram on $S$ is $\Theta(n)$. \thmlab{linear} \end{theorem} \begin{proof} Consider the partition of the plane by the first order Voronoi diagram of $S$, i.e., the standard Voronoi diagram. We iteratively refine the cells of this partition into higher order sequence Voronoi diagram cells. At each iteration we have a collection of order-$i$ sequence Voronoi diagram cells, and for each cell we either mark it final and stop processing, or further refine the cell into its constituent order-$(i+1)$ sequence cells. Specifically, a cell $\Delta$ is marked final in the $i$th iteration if every point in $\Delta$ is visible by one of its $i$ nearest sites, or when $i=n$ and the cell cannot be refined further. The process stops when all cells are marked final. Below we use $F^k$ to denote the set of cells which were marked final in the $k$th iteration. Let $C^k$ be the set of all cells of the order-$k$ sequence Voronoi diagram of $S$. Note that the order-$k$ sequence Voronoi diagram can be constructed by iteratively refining lower order cells, and hence any cell seen at any point in the above process is a cell of the order-$k$ sequence diagram for some value of $k$. So consider any cell $\Delta_j\in C^k$ of the order-$k$ sequence diagram of $S$. Let $\#(\Delta_j)$ be the number of order-$(k+1)$ sequence diagram cells inside $\Delta_j$, and let $X_j$ be the indicator variable for the event that $\Delta_j$ is refined into its constituent order-$(k+1)$ sequence cells in the $k$th round of the above iterative process. Note that $\Prob{X_j=1}$ is upper bounded by the probability that $\Delta_j$ has not been marked final by the end of the $k$th round, which in turn is bounded by \lemref{probability}. Thus letting $Z^{k+1}$ be the random variable denoting the total number of order-$(k+1)$ sequence cells created in the above process, we have \[ \Ex{Z^{k+1}}=\Ex{\sum_{\Delta_j\in C^{k}} \!\! \#(\Delta_j)\cdot X_j} =\!\! \sum_{\Delta_j\in C^{k}}\!\! \#(\Delta_j) \cdot \Ex{X_j} = O\!\left(\frac{k^2}{2^k}\right) \cdot \! \sum_{\Delta_j\in C^{k}}\!\!\! \#(\Delta_j)= O\!\left(\frac{nk^5}{2^k}\right), \] as $\sum \#(\Delta_j)$ is at most the total number of cells in the order-$k$ sequence Voronoi diagram, which is bounded by $O(nk^3)$ (see \apndref{shallow}). Using the same argument as in \lemref{polybound}, the complexity of the random semi Voronoi diagram is bounded by $\sum_{k=1}^n |F^k|\cdot O(k^2)$. (If $k=n$ then a cell may not be fully visible, though the bound still applies as the worst-case complexity is $O(n^2)$.) Thus by the above, the expected complexity is \[ \Ex{|\SVorX{S}|} \leq \sum_{k=1}^n \Ex{|F^k|}\cdot O(k^2) \leq \sum_{k=1}^n \Ex{Z^k}\cdot O(k^2) \leq O\left(\sum_{k=1}^n \frac{nk^7}{2^k}\right)=O(n). \] \end{proof} \begin{remark} For simplicity the results above were presented for semi Voronoi diagrams, though they extend to the more general VRVD case, where the visibility region of $s_i$ is determined by a cone with base point $s_i$ and angle $\alpha_i$, where the orientation of the cone is sampled uniformly at random. Specifically, the plane can be covered by a set of $(2\pi)/(\alpha_i/2) = 4\pi / \alpha_i$ cones around $s_i$ each with angle $\alpha_i/2$. Any one of these smaller cones is completely contained in the randomly selected $\alpha_i$ cone with probability $\alpha_i / (4\pi)$. If the $\alpha_i$ are lower bounded by a constant $\beta$, one can then prove a variant of \lemref{probability} (and hence \lemref{polybound} and \thmref{refined}), as the arrangement of all these smaller cones still has $O(k^2)$ complexity, and the probability a face is not visible to any site is still exponential in $k$ but with base proportional to $1-\beta/(4\pi)$. \end{remark} \section{The Expected Complexity of Multiplicative Voronoi Diagrams}\seclab{weighted} In this section we consider the expected complexity of multiplicative Voronoi diagrams under different randomness assumptions. First, by using the approach from the previous section, we show that for any set of site locations, if each site samples its weight from a set of constant size $c$, then the expected complexity is $O(n c^6)$. Next, we consider the case when the sites can have arbitrary weights, but the site locations are sampled uniformly at random from the unit square. As making no assumptions on the weights makes the problem considerably more challenging, as a warm-up, we first assume the weights are in an interval $[1,c]$. In this case, we consider a $1/\sqrt{n}$ side length grid, and argue that locally in each grid cell the expected complexity of the multiplicative diagram is $O(c^4)$ (inspired by the approach in \cite{DriemelHR16}), and thus over the entire unit square the complexity is $O(n c^4)$. Finally, we remove the bounded weight assumption, and argue that for any set of weights, the expected complexity is linear when site locations are sampled uniformly at random from the unit square, by introducing the notion of ``stretched'' sites. \subsection{Sampling from a small set of weights} \begin{lemma}\lemlab{finite} Let $W=\{w_1,w_2,...,w_c\}$ be a set of non-negative real weights and let $S=\{s_1,s_2,s_3,\allowbreak \ldots \allowbreak,s_n\}$ be a set of point sites in the plane, where each site in $S$ is assigned a weight independently and uniformly at random from $W$. Then the expected complexity of the multiplicative Voronoi diagram of $S$ is $O(n \cdot c^6)$. \end{lemma} \begin{proof} Consider the partition of the plane determined by the unweighted first order Voronoi diagram of $S$, i.e., the standard Voronoi diagram. Following the strategy of the proof of \thmref{linear}, we iteratively refine the cells of this partition into higher order sequence Voronoi diagram cells, except now a cell $\Delta$ is marked final in the $i$th iteration if at least one of its $i$-nearest sites has weight $w_m =\min\{w_1,w_2,w_3,...,w_c \}$. Note that the probability that $k$ sites are all assigned weight larger than $w_m$ is $(1-1/c)^k$. Using the same notation as in the proof of \thmref{linear}, we have \begin{align*} \Ex{Z^{k+1}} &=\Ex{\sum_{\Delta_j\in C^{k}} \!\! \#(\Delta_j)\cdot X_j} = \sum_{\Delta_j\in C^{k}}\! \#(\Delta_j) \cdot \Ex{X_j}\\ &= O\left((1-1/c)^k\right) \cdot \! \sum_{\Delta_j\in C^{k}} \#(\Delta_j) = O\left({nk^3}{(1-1/c)^k}\right). \end{align*} As the worst-case complexity of the multiplicative Voronoi diagram of $k$ sites is $O(k^2)$, overall the complexity of the multiplicative Voronoi diagram is bounded by $\sum_{k=1}^n |F^k|\cdot O(k^2)$. Thus by the above, the expected complexity is \[ \Ex{|\WVorX{S}|} \leq \sum_{k=1}^n \Ex{|F^k|}\cdot O(k^2) \leq \sum_{k=1}^n \Ex{Z^k}\cdot O(k^2) \leq O\left(\sum_{k=1}^n {nk^5}{(1-1/c)^k}\right) =O(n \cdot c^6), \] where the last step is obtained by viewing the sum as a power series in $x=(1-1/c)$, \begin{align*} &\!\!\!\!\!\!\!\!\sum_{k>0} k^5 (1-1/c)^k = \sum_{k>0} k^5 x^k = \pth{x \cdot \frac{d}{dx}} \sum_{k>0} k^4 x^k = \pth{x \cdot \frac{d}{dx}}^5 \sum_{k>0} x^k = \pth{x \cdot \frac{d}{dx}}^5 \frac{x}{1-x}\\ &\!\!\!\!\!\!\!\!= \frac{(x^5+26x^4+66x^3+26x^2+x)}{(1-x)^6} =120c^6-360c^5+390c^4-180c^3+31c^2-c = O(c^6) \end{align*} \end{proof} \subsection{Sampling site locations with bounded weights} In this section we argue that the expected complexity of the multiplicative Voronoi diagram is linear when the site locations are uniformly sampled and the weights are in a constant spread interval. In the next section we remove the bounded weight assumption. Thus the current section can be viewed as a warm-up, and serves to illustrate the extent to which assuming bounded weights simplifies the problem. However, as the results of the next section subsume those here, this section can be safely skipped if desired. The following fact is used both in the proof of the lemma below and the next section. \begin{fact}\factlab{varHelp} Consider doing $m$ independent experiments, where the probability of success for each experiment is $\alpha$. Let $X$ be the total number of times the experiments succeed. Then $\Ex{X^2} \leq \alpha m + \alpha^2 m^2 = \Ex{X}+\Ex{X}^2$. \end{fact} Note that the above fact holds since $X$ is a binomial random variable, $Bin(\alpha,m)$, and so $\Ex{X^2} = \text{\bf Var}[X]+\Ex{X}^2 = m\alpha(1-\alpha)+(m\alpha)^2$. \begin{lemma \lemlab{boundedWeights} Let $S=\{s_1,s_2,s_3,...,s_n\}$ be a set of point sites in the plane, where for some value $c\geq 1$, each site in $S$ is assigned a weight $w_i\in [1,c]$. Suppose that the location of each site in $S$ is sampled uniformly at random from the unit square $U$. Then the expected complexity of the multiplicative Voronoi diagram of $S$ within $U$ is $O(n \cdot c^4)$. \end{lemma} \newcommand{\boundedweightsproof}{ \begin{proof} Place a regular grid over $U$, where grid cells have side length $1/\sqrt{n}$. Fix any grid cell $\square = \square_{x,y}$, where $(x,y)\in \sqrt{n}\times \sqrt{n}$. We now argue that the expected complexity of the multiplicative Voronoi diagram within $\square$ is $O(c^4)$, and thus by linearity of expectation, the expected complexity over all $n$ grid cells in $U$ is $O(n c^4)$. Let $\rho$ be the random variable denoting the unweighted distance of the closest site in $S$ to the center of the grid cell $\square$, and let $X_\rho$ be the random variable denoting the number of points which contribute to the multiplicative Voronoi diagram in $\square$ conditioned on the value $\rho$. (For now ignore the contribution of the point at distance exactly $\rho$.) Observe that any point in $S$ which contributes to the multiplicative Voronoi diagram within $\square$ must lie within the annulus centered at the center of $\square$, with inner radius $\rho$ and outer radius $c(\rho+\sqrt{2/n})$. Conditioned on the value $\rho$, let $\alpha_\rho$ be the probability for a point to fall in this annulus, and let $X_\rho$ be the binomial random variable $Bin(\alpha_\rho, n)$ representing the number of points which fall into this annulus. For now assume $\rho\leq 1/4$, in which case the region outside the disk centered at the center of $\square$ and with radius $\rho$ has area at least $3/4$. We then have that \begin{align*} \Ex{X_\rho}&\leq n \alpha_{\rho} \leq n\frac{(\pi (c(\rho+\sqrt{2/n}))^2- \pi\rho^2)}{3/4}\\ &= O(n c^2(\rho^2(1-1/c^2)+\rho/\sqrt{n}+1/n )) = O(c^2+n(c\rho)^2). \end{align*} Let $Y_\rho$ be the random variable denoting the complexity of the multiplicative Voronoi diagram within $\square$ when conditioned on the value $\rho$. As the worst-case complexity of the multiplicative Voronoi diagram is quadratic, we have $Y_\rho = O((1+X_\rho)^2) = O(1+X_\rho+X_\rho^2)$, where the plus 1 counts the point at distance exactly $\rho$. Thus using \factref{varHelp}, and again assuming $\rho\leq 1/4$, \[ \Ex{Y_\rho} = O(1+\Ex{X_\rho}+\Ex{X_\rho^2}) = O(c^2+n(c\rho)^2 + (c^2+n(c\rho)^2)^2) = O(c^4(1+n\rho^2+n^2\rho^4)). \] Now consider the event that $\rho\in [i/\sqrt{n},(i+1)/\sqrt{n}]$ for some integer $i$. For this to happen, the open disk with radius $i/\sqrt{n}$ centered at the center of $\square$ must be empty, and one of the $n$ points must lie in the annulus with inner radius $i/\sqrt{n}$ and outer radius $(i+1)/\sqrt{n}$. Therefore, \begin{align*} \Prob{\rho\in [i/\sqrt{n},(i+1)/\sqrt{n}]} \leq n\cdot (\pi ((i+1)/\sqrt{n})^2 - \pi (i/\sqrt{n})^2)\cdot (1-\pi (i/\sqrt{n})^2)^{n-1}\\ =\pi(2i+1)\cdot (1-\pi i^2/n)^{n-1} \leq \pi(2i+1) e^{-\pi i^2 (n-1)/n} \leq \pi(2i+1) e^{-i^2}. \end{align*} Furthermore, by the above, when $\rho\in [i/\sqrt{n},(i+1)/\sqrt{n}]$ and $\rho\leq 1/4$, we have \[ \Ex{Y_\rho}=O(c^4(1+n\rho^2+n^2\rho^4)) = O(c^4(1+(i+1)^2+(i+1)^4)), \] and for $\rho\geq 1/4$ we have the trivial bound $\Ex{Y_\rho}=O(n^2)$. Finally, let $Y$ be the random variable denoting the complexity of the multiplicative Voronoi diagram within $\square$. By the law of total expectation we have, \begin{align*} \Ex{Y} &\leq \left(\sum_{i=0}^{\sqrt{n}/4 - 1} \! \Prob{\rho\in \left[\frac{i}{\sqrt{n}},\frac{(i\!+\!1)}{\sqrt{n}}\right]} \cdot O(c^4(1+(i\!+\!1)^2+(i\!+\!1)^4))\right) \\ & ~~~~+ \left(\sum_{i=\sqrt{n}/4}^{\sqrt{n}} \! \Prob{\rho\in \left[\frac{i}{\sqrt{n}},\frac{(i\!+\!1)}{\sqrt{n}}\right]} \cdot O(n^2)\right)\\ &\leq \left(\sum_{i=0}^{\sqrt{n}/4 - 1} \! \frac{\pi(2i+1)}{e^{i^2}} \cdot O(c^4(1+(i\!+\!1)^2+(i\!+\!1)^4))\!\right) + \left(\sum_{i=\sqrt{n}/4}^{\sqrt{n}} \! \frac{\pi(2i+1)}{e^{i^2}} \cdot O(n^2)\!\right)\\ &= O(1)+\! \sum_{i=0}^{\sqrt{n}/4-1} \frac{\pi(2i+1)}{e^{i^2}} \cdot O(c^4(1+(i\!+\!1)^2+(i\!+\!1)^4))\\ &=O(1)+\! \sum_{i=0}^{\sqrt{n}/4} \frac{2i+1}{e^{i^2}} \cdot O(c^4(i\!+\!1)^4) = O(c^4)+ O\left(\sum_{i=1}^{\sqrt{n}/4} \frac{c^4 i^5}{e^{i^2}}\right) = O(c^4) \end{align*} \end{proof}% } \boundedweightsproof \subsection{Sampling sites locations in general} In this section we argue that the expected complexity of the multiplicative Voronoi diagram is linear when the site locations are uniformly sampled. Here the weights can be any arbitrary set of positive values. Without loss of generality we can assume the smallest weight is exactly $1$, as dividing all weights by the same positive constant does not change the diagram. Throughout, $m$ denotes the maximum site weight, hence all weights are in the interval $[1,m]$. Let $\sigma$ be an arbitrary point in the unit square. The high level idea is that we want to apply a transformation to the sites such that the weighted Voronoi diagram around $\sigma$ can be interpreted as an unweighted Voronoi diagram. Specifically, for a site $s$ with weight $w$ and distance $d=||s-\sigma||$, let the \emph{stretched site} of $s$ with respect to $\sigma$, denoted by $t$, be the point at Euclidean distance $w\cdot d$ from $\sigma$ which lies on the ray from $\sigma$ through $s$. That is, the weighted distance from $s$ to $\sigma$ is the same as the unweighted distance from $t$ to $\sigma$. So let $\sigma$ be an arbitrary fixed point in the unit square, $S=\{s_1,\ldots,s_n\}$ be a set of sites with weights $\{w_1,\ldots,w_n\}\subset [1,m]$ whose positions have been uniformly sampled from the unit square, and let $T=\{t_1,\ldots,t_n\}$ be the corresponding set of stretched sites. Let $\gamma=\sqrt{1/(2n)}$. Our goal is to argue that for any arbitrary choice of $\sigma$ in $U$ the expected complexity of the multiplicative Voronoi diagram in the ball $B(\sigma,\gamma)$ is constant, i.e., $\Ex{|\WVorX{S}\cap B(\sigma,\gamma)|}=O(1)$. Then by the grid argument in the previous section this immediately implies a linear bound on the expected complexity of the overall diagram in $U$. Namely, place a uniform grid over $U$, where the grid cell side length is $1/\sqrt{n}$. Then as each cell is contained in a ball $B(\sigma,\gamma)$ for some $\sigma$, and there are $n$ cells overall, by the linearity of expectation the expected complexity of the overall diagram is $O(n)$. At a high level, the idea is simple. We wish to argue that sites whose stretched location is far from $\sigma$ will be blocked from contributing by sites whose stretched location is closer to $\sigma$. However, putting this basic plan into action is tricky and requires handling various edge cases. In particular, later it will become clear why we need to consider the following cases for where sites lie relative to $\sigma$. \begin{definition}\deflab{sets} For a fixed point $\sigma$ in $U$, let $X$ be the subset of $S$ which falls in $B(\sigma,4\gamma)$, i.e., $X=S\cap B(\sigma,4\gamma)$. Let $Y$ be the complement set, i.e., $Y=S\setminus X$. \end{definition} \begin{remark}\remlab{fixed} In the following, we typically condition on the set of sites which fall in $Y$ as being fixed, but not the actual precise locations of those sites. We refer to this as ``Fixing $Y$''. Ultimately the statements below hold regardless of what sites actually fall in $Y$. \end{remark} Fix $Y$. Let $r_1$ be the radius such that the expected number of stretched sites from $Y$ that are contained in $B(\sigma,r_1)$ is $n\cdot \pi(16\gamma)^2$. Observe that a site can only be moved further from $\sigma$ after stretching, thus $r_1\geq 16\gamma$. (Potentially $r_1$ is significantly larger.) Also, note that as $Y$ is fixed, the value of $r_1$ is fixed. For any integer $j>0$, let $D_j$ be the disk with radius $r_j=r_1 \times 2^{j-1}$, centered at $\sigma$. Moreover, define the rings $R_{j+1} = D_{j+1} \setminus D_{j}$, for any $j> 0$. \begin{lemma} \lemlab{move} Consider two sites $s_j \in Y$, and $s_i$ such that either $s_i\in Y$ or $s_i\in X$ with $w_i \leq w_j$. For any $k'\geq k\geq 1$, if $t_i\in D_k$ and $t_j\in R_{k'+2}$, then $s_j$ cannot contribute to the multiplicative Voronoi diagram in $B(\sigma,\gamma)$. \end{lemma} \begin{proof} For site $s_i$, let $d_i=||s_i-\sigma||$ and $d'_i=w_i\cdot d_i$. Similarly define $d_j$ and $d_j'$ for site $s_j$. Note that the furthest weighted distance of a point in $B(\sigma,\gamma)$ to $s_i$ is $w_i \cdot (d_i+\gamma)$, and the closest weighted distance of a point in $B(\sigma,\gamma)$ to $s_j$ is $w_j \cdot (d_j-\gamma)$. Thus it suffices to argue $w_i \cdot (d_i+\gamma) <w_j \cdot (d_j-\gamma)$, or equivalently $(w_i+w_j)\gamma<d'_j-d'_i$. To that end, observe $d'_j-d'_i \geq d'_j - d_j'/2= d'_j/2$. Thus we only need to argue $(w_i+w_j)\gamma< d'_j/2$. Case 1, $w_i \leq w_j$: In this case $(w_i+w_j)\gamma \leq w_j \cdot 2\gamma< w_j\cdot d_j/2 = d'_j/2$. Case 2, $w_i > w_j$: In this case $(w_i+w_j)\gamma \leq w_i \cdot 2\gamma< w_i \cdot d_i/2 = d'_i/2 \leq d'_j/2 $. \end{proof} Note that a site with weight $1$ does not move after stretching. Thus as $S$ always has a site with weight $1$, there must be at least one stretched site in $U$. Therefore, if we define $Z-1$ to be the smallest value of $j$ such that $U\subseteq D_j$, then $D_{Z-1}$ must contain a stretched site. Thus the above lemma implies any site which contributes to the multiplicative Voronoi diagram within $B(\sigma,\gamma)$ must lie within $D_{Z}$ after being stretched, and so going forward we only consider stretched sites in $D_{Z}$. \begin{definition}\deflab{probability} Fix $Y$, and consider any $1 \leq j\leq Z-2$. For $s_i\in Y$, let $p_{i,j}$ denote the probability that $t_i$ is located in $D_j$. For $s_i\in Y$, let $q_{i,j}$ denote the probability that $s_i$ is located in $U\setminus B(\sigma,16\gamma)$ and $t_i$ is located in $R_{j+2}\cup R_{j+1}$, conditioned on the event that no stretched sites from $Y$ are located in $D_j$.\footnote{Note for $j \leq Z-2$, $D_j\subsetneq U$, thus the condition that no stretched sites are in $D_j$ has non-zero probability.} \end{definition} \begin{lemma} Fix $Y$. For any $1 \leq j \leq Z-2$ and $s_i\in Y$ we have $q_{i,j} \leq 32\cdot p_{i,j}$. \lemlab{relation} \end{lemma} \begin{proof} Note in the following we always take as given that $s_i\in Y$. Observe that \begin{align*} p_{i,j} &= \Prob{t_i\in D_j} = \Prob{s_i\in U\cap B(\sigma,r_j/w_i)} = \frac{area( (U\cap B(\sigma,r_j/w_i)) \setminus B(\sigma,4\gamma))}{area(U\setminus B(\sigma,4\gamma))}. \end{align*} Then as the location of the sites in $Y$ are independent, for $q_{i,j}$ we have, \begin{align*} q_{i,j} &= \Prob{(s_i\in U\setminus B(\sigma,16\gamma)) \cap (t_i\in D_{j+2}\setminus D_{j}) \mid \forall s_k\in Y, t_k\notin D_j}\\ &= \Prob{(s_i\in U\setminus B(\sigma,16\gamma)) \cap (t_i\in D_{j+2}\setminus D_{j}) \mid t_i\notin D_j}\\ &= \Prob{(s_i\in U\setminus B(\sigma,16\gamma)) \cap (t_i\in D_{j+2}\setminus D_{j})} / \Prob{t_i\notin D_j}\\ &= \Prob{s_i\in (U\cap B(\sigma,4 r_j/w_i)) \setminus (B(\sigma, r_j/w_i)\cup B(\sigma,16\gamma))} / \Prob{t_i\notin D_j}\\ &\leq \Prob{s_i\in (U\cap B(\sigma,4 r_j/w_i)) \setminus B(\sigma,16\gamma)} / \Prob{t_i\notin D_j}\\ &= \frac{area( (U\cap B(\sigma,4 r_j/w_i)) \setminus B(\sigma,16\gamma)) }{ area(U\setminus B(\sigma,4\gamma)) \cdot \Prob{t_i\notin D_j} } \leq \frac{16\cdot area( (U\cap B(\sigma, r_j/w_i)) \setminus B(\sigma,4\gamma)) }{ area(U\setminus B(\sigma,4\gamma)) \cdot \Prob{t_i\notin D_j}}\\ &= \frac{16\cdot p_{ij}}{ \Prob{t_i\notin D_j} } = \frac{16\cdot p_{ij}}{ 1-p_{ij} }. \end{align*} If $p_{ij}\leq 1/2$, then the above implies $q_{ij}\leq 16\cdot p_{ij}/ (1-p_{ij})\leq 32\cdot p_{ij}$. On the other hand, if $p_{ij}> 1/2$, then $p_{ij}> 1/2\geq q_{ij}/2$. \end{proof} \begin{fact}\factlab{indep} Fix $Y.$ For any $1 \leq j\leq Z-2$, consider the event, $C_j$, that $j$ is the largest index such that there are no stretched sites from $Y$ located in $D_j$. We have $\Prob{C_j} \leq \prod_{s_i\in Y} (1-p_{i,j})$. \end{fact} \begin{lemma}\lemlab{max} Fix $Y.$ Let $\psi$ be the number of sites that fall outside $B(\sigma,16\gamma)$ and contribute to the multiplicative Voronoi diagram within $B(\sigma,\gamma)$. Then we have \[ \Ex{\psi^2}\leq O(1)+ 2\sum _{j=1}^{Z-2}\left( \left(\prod_{s_i \in Y} (1-p_{i,j})\right) \cdot \left(1+3 \sum_{s_i \in Y} q_{i,j} + \left(\sum_{s_i \in Y} q_{i,j}\right)^2 \right) \right). \] \end{lemma} \begin{proof} For $1\leq j\leq Z-2$, let $C_j$ be the event that $j$ is the largest index such that $D_j$ contains no stretched sites from $Y$. (Note for $i\neq j$, $C_i$ and $C_j$ are disjoint events.) If $C_j$ occurs then only sites in $R_{j+1} \cup R_{j+2}$ can contribute to the weighted diagram in $B(\sigma,\gamma)$, based on \lemref{move}. Let $y_j$ be the random variable denoting the number of sites such that $s_i\notin B(\sigma,16\gamma)$ and $t_i\in R_{j+1}\cup R_{j+2}$. If $C_j$ occurs, then $y_j$ is an upper bound on the number of sites which fall outside $B(\sigma,16\gamma)$ and contribute to the weighted diagram in $B(\sigma,\gamma)$. Note we must also consider the event that $C_j$ does not occur for any $j\geq 1$, namely there exist stretched sites from $Y$ contained in $D_1$. Call this event $C_0$, and let $y_0$ be the random variable for the number of sites such that $s_i\notin B(\sigma,16\gamma)$ and $t_i\in D_2$. By the law of total expectation, \[ \Ex{\psi^2} = \sum _{j=0}^{Z-2} (\Prob{C_j} \cdot \Ex{(y_j)^2\mid C_j}), \] where the sum stops at $Z-2$ since there always exists a stretched site with weight $1$ in $D_{Z-1}$ (by definition of $Z$), and so stretched sites outside of $D_Z$ can be ignored. So consider any $\Ex{(y_j)^2\mid C_j}$ term, for some $j>0$. Let $A_j$ be the event that $D_j$ contains no stretched sites from $Y$ and let $B_j$ be the event that $R_{j+1}$ has a stretched site from $Y$, and observe that $C_j=A_j\cap B_j$. The following claim is intuitive, and its proof is in \apndref{claimproof}. \begin{claim}\claimlab{fix} $\Ex{y_j^2 \mid C_j} \leq 2\Ex{(y_j+1)^2\mid A_j}$. \end{claim} The events, over all $s_i\in Y$, that $s_i$ falls outside $B(\sigma,16\gamma)$ while $t_i$ is located in $R_{j+1} \cup R_{j+2}$, are independent. Moreover, this event for any $s_i\in Y$, when conditioned on $A_j$, has probability $q_{i,j}$ (see \defref{probability}). Hence conditioned on $A_j$, the random variable $y_j$ has a Poisson Binomial distribution. Thus we have $\Ex{y_{j}\mid A_j}= \sum_{s_i \in Y} (q_{i,j})$, and the variance is then $\text{\bf Var}[y_j\!\mid\! A_j] =\sum_{s_i \in Y} \left( q_{i,j}(1-q_{i,j}) \right) \leq \sum_{s_i \in Y} (q_{i,j})=\Ex{y_{j}\!\mid\! A_j}$. Thus using the above claim, \begin{align*} \Ex{(y_{j})^2 \mid C_j} &\leq 2\Ex{(y_j+1)^2\mid A_j} = 2\Ex{1+2y_j+y_j^2 \mid A_j} \\ &= 2(1+2\Ex{y_j\mid A_j}+(\text{\bf Var}[y_j\mid A_j]+\left(\Ex{y_{j}\mid A_j}\right)^2))\\ &\leq 2(1+3\Ex{y_j\mid A_j}+\left(\Ex{y_{j}\mid A_j}\right)^2) \leq 2\left(1+ 3\sum_{s_i \in Y} q_{i,j} +\left(\sum_{s_i \in Y} q_{i,j}\right)^2\right). \end{align*} Suppose that $\Prob{C_0}\cdot \Ex{(y_0)^2|C_0}=O(1)$, then the lemma statement follows. Specifically, by \factref{indep}, $\Prob{C_j}\leq \prod_{s_i \in Y} (1-p_{i,j})$, for any $1\leq j\leq Z-2$. Thus by the above, \begin{align*} \Ex{\psi^2} &= \sum _{j=0}^{Z-2} (\Prob{C_j} \cdot \Ex{(y_j)^2\mid C_j})\\ &\leq O(1)+2\sum _{j=1}^{Z-2} \left( \left( \prod_{s_i \in Y} (1-p_{i,j}) \right) \cdot \left(1+3 \sum_{s_i \in Y} q_{i,j} +\left(\sum_{s_i \in Y} q_{i,j}\right)^2\right) \right). \end{align*} Thus what remains is to show $\Prob{C_0} \cdot \Ex{(y_0)^2|C_0}=O(1)$. First, observe that \begin{align*} \!\!\!\!\!\!\!\Prob{C_0} \Ex{(y_0)^2|C_0}\!&=\! \Prob{C_0} \sum_{k=1}^{|Y|^2}\! k\cdot \Prob{(y_0)^2=k|C_0}\!=\! \Prob{C_0} \sum_{k=1}^{|Y|^2} \frac{k\cdot \Prob{((y_0)^2=k) \cap C_0}}{\Prob{C_0}}\\ &= \sum_{k=1}^{|Y|^2} k\cdot \Prob{((y_0)^2=k) \cap C_0} \leq \sum_{k=1}^{|Y|^2} k\cdot \Prob{(y_0)^2=k} = \Ex{(y_0)^2}. \end{align*}% Thus it suffices to argue $\Ex{(y_0)^2}=O(1)$. For any $s_i\in Y$, let $q_{i,0}$ denote the probability that $s_i\notin B(\sigma,16\gamma)$ while $t_i\in D_2$, then $\Ex{y_0}=\sum_{s_i\in Y} q_{i,0}$. Note that as $area( B(\sigma,r_2/w_i) \setminus B(\sigma,16\gamma)) \leq 4 \cdot area( B(\sigma, r_1/w_i) \setminus B(\sigma,4\gamma))$ it follows that $area( (U\cap B(\sigma,r_2/w_i)) \setminus B(\sigma,16\gamma)) \leq 4 \cdot area( (U\cap B(\sigma, r_1/w_i)) \setminus B(\sigma,4\gamma))$. This implies $q_{i,0} \leq 4\cdot p_{i,1}$, and hence $\sum_{s_i\in Y} q_{i,0} \leq 4 \sum_{s_i\in Y} p_{i,1}=4\cdot n\pi(16\gamma)^2=O(1)$, by the definition of $r_1$. Thus $ \Ex{y_0} =O(1)$, and since $y_0$ has a Poisson Binomial distribution, $ \Ex{(y_0)^2} = (\Ex{y_0})^2+\text{\bf Var}[y_0] \leq (\Ex{y_0})^2+\Ex{y_0}=O(1)$. \end{proof} \begin{lemma} \lemlab{step} Let $P_j=\sum_{s_i\in Y} p_{i,j}$. Then for any $j\leq Z-3$, we have $P_j\geq P_{j-1}+1$. \end{lemma} \newcommand{\quarterproof}{ \begin{proof} Note that by definition, the expected number of stretched sites from $Y$ that are contained in $B(\sigma,r_1)$ is $n\pi(16\gamma)^2>2$, and thus $P_1=(\sum_{s_i\in Y} p_{i,1})> 2$. \begin{figure}[t] \centering \includegraphics[width=.34\linewidth]{regions} \caption{The locations of the four defined quarters for each disk, and how they intersect $U$.} \figlab{cut} \end{figure} We argue that for any $j\leq Z-3$, that $area(U\cap D_j) \geq 2\cdot area(U\cap D_{j-1})$. To this end, break $D_j$ into 4 quarters, by cutting it with a vertical and horizontal line through $\sigma$. Let the quarters be labeled $Q_1$, $Q_2$, $Q_3$, and $Q_4$, in clockwise order, starting with the northwest quarter, see \figref{cut}. Similarly break $D_{j-1}$ into quarters, $Q'_1$, $Q'_2$, $Q'_3$, and $Q'_4$, with the same clockwise labeling order. Recall that by definition $Z-1$ is the smallest $j$ such that $U\subseteq D_j$. Since $\sigma\in U$, this implies that for any $j\leq Z-3$ at least one of the quarters of $D_j$ is fully contained in $U$, and without loss of generality assume it is $Q_2$. Note that $area(D_j)=4 area(D_{j-1})$, thus this implies that $area(U\cap Q_2) = area(Q_2) = 2(area(Q'_2)+area(Q'_4))\geq 2(area(U\cap Q'_2)+area(U\cap Q'_4))$. It is easy to argue that since $r_j=2r_{j-1}$ that $area(U\cap Q_1)\geq 2 area(U\cap Q'_1)$ and $area(U\cap Q_3)\geq 2 area(U\cap Q'_3)$, thus summing over all quarters $area(U\cap D_j) \geq 2\cdot area(U\cap D_{j-1})$. This implies that $area(U\cap B(\sigma,r_j/w_i)) \geq 2\cdot area(U\cap B(\sigma,r_{j-1}/w_i))$, which in turn implies $area((U\cap B(\sigma,r_j/w_i)) \setminus B(\sigma,4\gamma)) \geq 2 \cdot area( (U\cap B(\sigma,r_{j-1}/w_i)) \setminus B(\sigma,4\gamma))$. Hence by \defref{probability}, $p_{i,j} \geq 2p_{i,j-1}$, and therefore $P_j \geq 2 P_{j-1}\geq P_{j-1}+1 $. \end{proof} } \quarterproof \begin{lemma}\lemlab{constant} \[ \sum _{j=1}^{Z-2} \left( \left( \prod_{s_i \in Y} (1-p_{i,j}) \right) \cdot \left(1+3 \sum_{s_i \in Y} q_{i,j} +\left(\sum_{s_i \in Y} q_{i,j}\right)^2\right) \right) = O(1). \] \end{lemma} \begin{proof} We argue that $\sum _{j=1}^{Z-2} \left( \left( \prod_{s_i \in Y} (1-p_{i,j}) \right) \cdot \left(\sum_{s_i \in Y} q_{i,j}\right)^\alpha \right)= O(1)$, where $\alpha =0$, $1$, or $2$, thus implying the lemma statement. By \lemref{relation}, $q_{i,j}\leq 32\cdot p_{i,j}$, and therefore \begin{align*} \sum _{j=1}^{Z-2}\left( \left(\prod_{s_i \in Y} (1-p_{i,j})\right) \cdot \left(\sum_{s_i \in Y} q_{i,j}\right)^\alpha \right) \leq \sum _{j=1}^{Z-2} \left(\left(\prod_{s_i \in Y} (1-p_{i,j})\right) \cdot \left(32 \sum_{s_i \in Y} p_{i,j}\right)^\alpha \right) \\ \leq 32^\alpha \sum _{j=1}^{Z-2} \left(\left(e^{-\sum_{s_i \in Y} p_{i,j}}\right) \cdot \left(\sum_{s_i \in Y} p_{i,j}\right)^\alpha \right) = 32^\alpha \sum _{j=1}^{Z-2} \left(\left(e^{-P_j}\right) \cdot \left(P_j\right)^\alpha \right), \end{align*} where the last inequality follows as $1-x\leq e^{(-x)}$, and the last equality is by the definition of $P_j$ from the \lemref{step} statement. Note that by definition, the expected number of stretched sites from $Y$ that are contained in $B(\sigma,r_1)$ is $n\pi(16\gamma)^2$, and thus $P_1=(\sum_{s_i\in Y} p_{i,1})> 2$. Moreover, the function $x^\alpha e^{-x}$ is monotonically decreasing for $x>2$, and always has value less than $1$, for $\alpha = 0,1,\text{ or }2$. Thus since by \lemref{step}, $P_j\geq P_{j-1}+1$ for $j\leq Z-3$, and since $P_{Z-2}\geq P_{Z-3}$, we have, \begin{align*} \sum _{j=1}^{Z-2} P_j^\alpha \cdot e^{-P_j} \leq 1+ \sum _{j=1}^{Z-3} P_j^\alpha \cdot e^{-P_j} \leq 1+\sum _{x=2}^{\infty} x^\alpha \cdot e^{-x} \leq 2+\int_{2}^{\infty} x^\alpha\cdot e^{-x} dx \leq 4, \end{align*} for $\alpha =0, 1,\text{ or }2$. Combining the above two equalities thus yields the lemma statement. \end{proof} Now that we have the above lemmas for any fixed $Y$, we are finally ready to prove our main lemma (where $Y$ is no longer assumed to be fixed). \begin{lemma}\lemlab{alltogether} Let $S$ be a set of $n$ point sites in the plane, with arbitrary positive weights. Suppose that the location of each site in $S$ is sampled uniformly at random from the unit square $U$. Then for any point $\sigma\in U$, $\Ex{|\WVorX{S}\cap B(\sigma,\gamma)|}=O(1)$. \end{lemma} \begin{proof} Let $\hat{\Psi} = S\cap B(\sigma, 16\gamma)$ be the sites which fall in $B(\sigma, 16\gamma)$ and let $\Psi = S\setminus \hat{\Psi}$ be the complement set. Let $\hat{\psi}$, $\psi$, be the random variables denoting the number of sites respectively from $\hat{\Psi}$, $\Psi$, which contribute to the multiplicative diagram in $B(\sigma,\gamma)$. Recall that the worst-case complexity of the multiplicative diagram is quadratic in the number of sites. Thus it suffices to bound $\Ex{(\hat{\psi}+\psi)^2} \leq \Ex{2(\hat{\psi}^2+\psi^2)} = 2(\Ex{\hat{\psi}^2}+\Ex{\psi^2}).$ Thus we now show each of the above two expected value terms are constant. First, note that \lemref{max} and \lemref{constant} combined imply that $\Ex{\psi^2}=O(1)$ (as those lemmas hold regardless of which sites fall in $Y$). Thus we only need to bound $\Ex{\hat{\psi}^2}$. Observe that clearly $|\hat{\Psi}|\geq \hat{\psi}$. To bound $|\hat{\Psi}|$, observe that $area(B(\sigma, 16\gamma))=O(1/n)$, and thus $\Ex{|\hat{\Psi}|} = O(1)$. Moreover, the number of sites which fall into this ball is a binomial random variable. Thus by \factref{varHelp}, $\Ex{\hat{\psi}^2} \leq \Ex{|\hat{\Psi}|^2} \leq \Ex{|\hat{\Psi}|}+\Ex{|\hat{\Psi}|}^2 = O(1)$. \end{proof} Consider placing a uniform grid with side length $1/\sqrt{n}$ over the unit square $U$. Then for any grid cell, if we set $\sigma$ to be the center of the grid cell then $B(\sigma,\gamma)$ contains the grid cell, and hence the above lemma implies the expected complexity in the grid cell is constant. Thus using linearity of expectation over all $n$ grid cells implies the following main theorem. \begin{theorem} Let $S$ be a set of $n$ point sites in the plane, with arbitrary positive weights. Suppose the location of each site in $S$ is sampled uniformly at random from the unit square $U$. Then the expected complexity of the multiplicative Voronoi diagram of $S$ within $U$ is $O(n)$. \end{theorem} \bibliographystyle{plain}
{'timestamp': '2020-04-21T02:29:28', 'yymm': '2004', 'arxiv_id': '2004.09385', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09385'}
arxiv
\section{Introduction} \label{sec:Motivation} With increasingly large amounts of data being collected in numerous application areas ranging from science to industry, the importance of online analytical processing (OLAP) workloads increases constantly~\cite{DBLP:journals/cacm/ChaudhuriDN11}. OLAP queries typically access a small number of columns, but a high number of rows and are, thus, most efficiently processed by column-stores~\cite{DBLP:journals/cacm/ChaudhuriDN11}. Moreover, the significant developments in the main memory domain in recent years have rendered it possible to keep even large data sets entirely in main memory. For these reasons, in-memory column-store database management systems (DBMS) have established themselves as state-of-the-art for OLAP workloads~\cite{DBLP:journals/cacm/BonczKM08,DBLP:journals/ftdb/FaerberKLLNP17,DBLP:conf/vldb/StonebrakerABCCFLLMOORTZ05}. In these systems, lightweight integer compression algorithms already play an important role~\cite{DBLP:journals/ftdb/AbadiBHIM13,DBLP:conf/sigmod/AbadiMF06,DBLP:journals/ftdb/FaerberKLLNP17,DBLP:conf/sigmod/LangMFB0K16}. On the one hand, with the help of some additional lightweight computations for integer compression, the necessary memory space can be reduced~\cite{DBLP:journals/ftdb/AbadiBHIM13,DBLP:conf/sigmod/AbadiMF06,DBLP:journals/ftdb/FaerberKLLNP17,DBLP:conf/sigmod/LangMFB0K16}. As we have shown in~\cite{DBLP:conf/edbt/DammeHHL17,DBLP:journals/tods/DammeUHHL19}, there is a large variety of lightweight integer compression schemes available and there is no single-best algorithm, but the decision depends on several factors, most importantly on the data characteristic. On the other hand, compressed data also offers several advantages for data processing such as less time spent on load and store instructions and a better utilization of the cache hierarchy. Moreover, a direct processing of compressed integer data is possible in many cases~\cite{DBLP:conf/icde/FengL15,DBLP:conf/sigmod/FengLKX15,DBLP:conf/sigmod/LangMFB0K16,DBLP:journals/pvldb/LeeABCDHI0LLMMPQRSSSZ14,DBLP:conf/sigmod/LiP13,DBLP:journals/pvldb/WillhalmPBPZS09}. For example, several column scan approaches have been presented in the literature, where filter predicates are directly evaluated on compressed integer data~\cite{DBLP:conf/sigmod/FengLKX15,DBLP:conf/sigmod/LiP13,DBLP:journals/pvldb/WillhalmPBPZS09}. However, existing systems only provide a very limited set of compression algorithms for base data~\cite{DBLP:journals/ftdb/AbadiBHIM13,DBLP:conf/sigmod/AbadiMF06,DBLP:journals/ftdb/FaerberKLLNP17,DBLP:conf/sigmod/LangMFB0K16}. Furthermore, during query processing, these systems only keep the data compressed until an operator cannot process the compressed data directly, whereupon the data is decompressed, but not recompressed~\cite{DBLP:journals/ftdb/AbadiBHIM13,DBLP:conf/sigmod/AbadiMF06,DBLP:journals/ftdb/FaerberKLLNP17,DBLP:conf/sigmod/LangMFB0K16}. Thus, the full potential of compression during query processing is not exploited from our point of view. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/teaser.pdf} \caption{Comparing MonetDB and \emph{MorphStore} using SSB~\protect\cite{DBLP:journals/corr/Sanchez16a}. More details in Section~\ref{sec:Evaluation}.} \label{fig:teaser} \vspace{-0.7cm} \end{figure} \textbf{Core Contribution.} To exploit this potential as shown in Figure~\ref{fig:teaser}, we designed a novel \emph{holistic compression-enabled processing model} satisfying four design principles. \begin{compactenum} \item[\textbf{DP1}] Our model is a compression-aware optimization of the well-known operator-at-a-time processing model introduced by MonetDB~\cite{DBLP:journals/cacm/BonczKM08,DBLP:journals/debu/IdreosGNMMK12}. Thus, all intermediate results should be representable using a lightweight integer compression algorithm. With that, we want to enable the \emph{continuous} usage of compression for the whole query execution. \item[\textbf{DP2}] Since data characteristics have an impact on the compression scheme decision and usually change during query processing, a suitable scheme should be chosen for each intermediate from a rich and easily extensible set of schemes. Moreover, the selection for each intermediate should not depend on the scheme used for another one to independently adapt to its particular data characteristics. This implies that a change of the compression scheme from one intermediate to the next should be possible in a very efficient and flexible way. \item[\textbf{DP3}] No physical columnar query operator should require the uncompressed materialization of its entire input or output data, since this would severely limit the benefits achievable through compression. In particular, a full decompression of the input data should be avoided. \item[\textbf{DP4}] Related work in this domain is manifold. Thus, our novel approach should build on this and should extend this work so that the design principles DP1 to DP3 can be realized. That also means that existing work should be seamlessly integrable leading to a holistic approach. \end{compactenum} To prove the benefits of our \emph{holistic compression-enabled} processing model, we developed \emph{MorphStore}, an open-source analytical query engine written in C++~\cite{DBLP:conf/sigmod/HabichDUPKHL19}. As highlighted in Figure~\ref{fig:teaser}, \emph{MorphStore} provides an average runtime behavior comparable to MonetDB~\cite{DBLP:journals/cacm/BonczKM08,DBLP:journals/debu/IdreosGNMMK12} for all SSB queries in case of single-threaded scalar processing of uncompressed $64$-bit data. Generally, to improve the query performance, vectorization using SIMD (Single Instruction Multiple Data) instructions is state-of-the-art in this domain~\cite{DBLP:conf/sigmod/FengLKX15,DBLP:journals/pvldb/KerstenLKNPB18,DBLP:conf/sigmod/PolychroniouRR15,DBLP:conf/damon/PolychroniouR19,tvl,DBLP:conf/sigmod/ZhouR02}. Thus, with a vectorized processing of uncompressed data in \emph{MorphStore} using Intel's latest SIMD extension AVX-512, we are able to decrease the average query runtime by $19$\%. However, with our \emph{compression-enabled model} executed with AVX-512 as well, we achieve an average query runtime reduction of about $54$\%, while reducing the memory footprint by $52$\% at the same time. \textbf{Contributions in Detail and Outline.} Thus, to present \emph{MorphStore} with the novel \emph{holistic compression-enabled} processing model in detail, we make the following contributions: \begin{compactenum} \item We systematically summarize preliminary work in Section~\ref{sec:Preliminaries}. These works are manifold but there is no approach to holistically combine their potentials. \item Based on that, we describe our novel processing model in Section~\ref{sec:Model} by presenting four different degrees of integration opportunities of compression and operators. \item In Section~\ref{sec:Engine}, we introduce our analytical query engine \emph{MorphStore} as an implementation for our novel processing model. In particular, we discuss some implementation aspects in more detail. \item Then, we present selected results of our exhaustive evaluation of \emph{MorphStore} using micro-benchmarks and the SSB~\cite{DBLP:journals/corr/Sanchez16a} in Section~\ref{sec:Evaluation}. As we are going show, the continuous usage of compression for query execution is very beneficial from two perspectives: reducing \emph{memory footprint} and reducing \emph{query runtime}. \item Our evaluation shows that the choice of the compression scheme for intermediates is a new dimension for query optimization. Thus, we highlight some initial steps for a compression-aware optimization in Section~\ref{sec:Evaluation}. \end{compactenum} Finally, we present related work in Section~\ref{sec:RelatedWork} and briefly summarize the paper in Section~\ref{sec:Conclusion}. \section{Preliminaries} \label{sec:Preliminaries} Without claim of completeness, we start with a review of related work on light\-weight integer compression for in-memory column-store systems on: (i) lightweight compression algorithms, (ii) query operators for compressed data, and (iii) available integration approaches of compression into query execution. Based on that, we clearly motivate our novel \emph{holistic compression-enabled} processing model. \subsection{Lightweight Integer Compression} \label{sec:Narrow:Algos} Generally, each base data attribute is stored separately as a sequence of values~\cite{DBLP:journals/ftdb/AbadiBHIM13,DBLP:conf/sigmod/AbadiMF06,DBLP:journals/ftdb/FaerberKLLNP17}. To reduce the necessary memory space, the columns are compressed with a common approach~\cite{DBLP:journals/ftdb/AbadiBHIM13,DBLP:conf/sigmod/AbadiMF06,DBLP:journals/ftdb/FaerberKLLNP17}: (i) encode the values of each column as a sequence of integers using some kind of dictionary encoding~\cite{DBLP:conf/sigmod/BinnigHF09} and (ii) apply lightweight lossless integer compression to each sequence of integers resulting in a sequence of compressed column codes~\cite{DBLP:journals/ftdb/AbadiBHIM13,DBLP:conf/sigmod/AbadiMF06,DBLP:conf/edbt/DammeHHL17,DBLP:journals/ftdb/FaerberKLLNP17}. For the second point, a large corpus of lightweight integer compression schemes has been developed and we have to distinguish between techniques, algorithms, and implementations~\cite{DBLP:conf/edbt/DammeHHL17,DBLP:journals/tods/DammeUHHL19,DBLP:journals/spe/LemireB15}. \textbf{Techniques:} Five basic techniques are currently known and frequently used: frame-of-reference (FOR)~\cite{DBLP:conf/icde/GoldsteinRS98,DBLP:conf/icde/ZukowskiHNB06}, delta coding (DELTA)~\cite{DBLP:journals/spe/LemireB15,DBLP:journals/sigmod/RothH93}, dictionary encoding (DICT)~\cite{DBLP:conf/sigmod/AbadiMF06,DBLP:conf/sigmod/BinnigHF09,DBLP:journals/sigmod/RothH93,DBLP:conf/icde/ZukowskiHNB06}, run-length encoding (RLE)~\cite{DBLP:conf/sigmod/AbadiMF06,DBLP:journals/sigmod/RothH93}, and null suppression (NS)~\cite{DBLP:conf/sigmod/AbadiMF06,DBLP:journals/sigmod/RothH93}. FOR and DELTA represent each value as the difference to a certain given reference value or to its predecessor value, respectively. DICT replaces each value by its unique key given by a dictionary. The objective of these three techniques is to represent the original data as a sequence of small integers, which is then suited for actual compression using the NS technique. NS is the most well-studied technique and its basic idea is the omission of leading zeros in the bit representation of small integers. Finally, RLE tackles uninterrupted sequences of occurrences of the same value, so-called runs. In its compressed format, each run is represented by its value and run length. Thus, the compressed data is a sequence of such pairs. To sum up, FOR, DELTA, DICT, and RLE address the logical level, while NS considers the physical level. \textbf{Algorithms:} The genericity of these basic techniques is the foundation to tailor lightweight integer compression algorithms to different data characteristics~\cite{DBLP:conf/edbt/DammeHHL17,DBLP:journals/tods/DammeUHHL19}. Thus, a concrete algorithm can be described as a cascade of one or more of these basic techniques. On the algorithm level, NS has been studied most extensively \cite{DBLP:journals/ir/AnhM05,DBLP:journals/spe/AnhM10,DBLP:journals/ws/DelbruCT12,DBLP:journals/tit/Elias75,DBLP:journals/spe/LemireB15,DBLP:journals/ipl/LemireKR18,DBLP:journals/corr/PlaisanceKL15,1090789_Rice,DBLP:conf/damon/SchlegelGL10,DBLP:conf/cikm/SilvestriV10,DBLP:conf/cikm/StepanovGREO11,DBLP:conf/www/YanDS09,DBLP:conf/www/ZhangLS08,DBLP:journals/tois/ZhaoZLSNYW15,DBLP:conf/icde/ZukowskiHNB06}. An example NS algorithm is \emph{Binary Packing (BP)}~\cite{DBLP:journals/spe/LemireB15,DBLP:conf/cikm/SilvestriV10}. The basic idea of BP is to partition a sequence of integer values into blocks and compress every value in a block using a fixed bit width (namely, the effective bit width of the largest value in the block). The logical-level techniques, however, have not received much attention \emph{on the algorithm level}. Different algorithms for RLE differ, e.g., in the way they record the repetitions. The run value can be stored together with the run length \cite{DBLP:journals/isci/LemireK11}, or the run's start position in the input sequence \cite{DBLP:journals/isci/LemireK11}, or both \cite{DBLP:conf/sigmod/AbadiMF06}. Furthermore, runs of length one, which allow no actual reduction of the number of data elements, could be stored in a special way to avoid the overhead of storing the run length \cite{DBLP:journals/isci/LemireK11}. The preprocessing steps DELTA, FOR, and DICT have usually been investigated in connection with the NS technique \cite{DBLP:journals/ws/DelbruCT12,DBLP:conf/icde/ZukowskiHNB06}. \textbf{Implementation:} An \emph{implementation} is a hardware-specific executable code of an algorithm. In recent years, the efficient \emph{vectorized} implementation using SIMD instruction set extensions (Single Instruction Multiple Data) to reduce the runtime has attracted most of the attention~\cite{DBLP:journals/spe/LemireB15,DBLP:journals/corr/PlaisanceKL15,DBLP:conf/damon/SchlegelGL10,DBLP:conf/cikm/StepanovGREO11,DBLP:conf/icde/UngethumPDHL18,DBLP:journals/tois/ZhaoZLSNYW15}. The focus of those vectorized implementations is first and foremost on NS algorithms. For example, SIMD-BP~\cite{DBLP:journals/spe/LemireB15} is a vectorized implementation of the NS algorithm BP. In comparison, the logical-level techniques have been neglected, although there are also some papers presenting vectorized implementation for DELTA~\cite{DBLP:journals/spe/LemireB15} or RLE~\cite{DBLP:journals/tods/DammeUHHL19,DBLP:conf/icde/UngethumPDHL18}. \textbf{Experimental Survey.} In~\cite{DBLP:conf/edbt/DammeHHL17,DBLP:journals/tods/DammeUHHL19}, we presented an exhaustive experimental evaluation of this large corpus of light\-weight integer compression algorithms and implementations. Our analysis using the evaluation metrics compression rate, compression speed, decompression speed, and aggregation speed led us to the overall conclusion that there is no single-best lightweight compression algorithm, but the choice is non-trivial and depends on the following factors: \mbox{(i) data} characteristics, (ii) hardware properties, (iii) SIMD extension and (iv) objective. Moreover, we found out that the best algorithm with respect to the compression rate is not necessarily optimal regarding (de)compression speed. This allows interesting trade-offs between these two fundamental objectives for optimization. \subsection{Query Operators for Compressed Data} \label{sec:Narrow:Operators} A major advantage of lightweight integer compression is that some query operators can process the compressed data directly, without decompression. For that, there is a lot of related work available and we can classify them into processing data compressed at the logical and the physical level. \textbf{Logical Level:} DICT was the first compression scheme whose qualification for direct processing was investigated. In~\cite{143840_graefe}, the authors identified that the equality-preserving property of DICT can be exploited by query operators employing exact-match comparisons. For instance, selection scans can process dictionary keys directly, without looking up the actual values in the dictionary, by mapping the selection predicate’s constants to keys using the same dictionary as for the data. Furthermore, they note that duplicate elimination, grouping, equality joins, and set operations can directly work on dictionary keys. Especially for equality joins and set operations, the authors explicitly assume the same dictionary across different columns of the same domain. In contrast to that, Lee et al.~\cite{DBLP:journals/pvldb/LeeABCDHI0LLMMPQRSSSZ14} proposed to encode each attribute individually to exploit skew in the data distribution for an efficient encoding. However, this implies that join-operators can no longer compare dictionary keys from different inputs directly any more. To address this issue for hash joins, they propose to perform a so-called \emph{encoding translation} by re-encoding the keys of the build-side with the dictionary of the probe-side. After the dictionary encodings have been reconciled, dictionary keys, i.e., compressed values are inserted into the hash table to avoid decompression in both the build phase and the probe phase. Additionally, Abadi et al.~\cite{DBLP:conf/sigmod/AbadiMF06} sketched how database operators can directly process run-length encoded data. In detail, they mention that an RLE-compressed inner of a nested loop join does not need to be decompressed. Instead, the data elements in the outer need to be compared only to the run values of the inner. Each time a comparison succeeds, multiple join matches are found at once, whereby the number of matches is the corresponding run length in the inner. Furthermore, a summation on a run-length encoded column can be done by summing up the products of corresponding pairs of run value and run length. \textbf{Physical Level:} Most DBMSs support different data types for integral attributes and offer physical query operators tailored to these types. For instance, the SQL standard defines the types \texttt{TINYINT}, \texttt{SMALLINT}, \texttt{INTEGER}, and \texttt{BIGINT}, which represent a single value using 1, 2, 4, and 8 bytes, respectively. Representing data in one of these types is, perhaps, the simplest form of lightweight compression. Thus, it can be seen as a particular NS format, namely a form of BP, whereby a common bit width is used for all elements of a column and this bit width must be either 8, 16, 32, or 64, making the compressed data byte-aligned. Thus, most DBMSs can implicitly process data compressed directly. Indeed, even recent research works on compressed processing frequently restrict the physical-level compression to byte-aligned NS~\cite{DBLP:conf/sigmod/AbadiMF06,DBLP:journals/pvldb/BarberLPRSACLS14, DBLP:conf/sigmod/LangMFB0K16,DBLP:journals/sigmod/WestmannKHM00}. This has two reasons: (i) byte-alignment suits the byte-addressability of main memory naturally and (ii) data elements of 8, 16, 32, and 64 bits can be processed natively on current microprocessors using both classical scalar and modern vectorized instructions. The second reason is especially important, since it implies that all operators can be designed to directly work on compressed data with a low implementation effort. However, some authors observed that such simple byte-aligned packing approaches lack support for arbitrary bit widths and work at a sub-optimal bit-level parallelism~\cite{DBLP:conf/sigmod/FengLKX15,DBLP:conf/sigmod/LiP13,DBLP:journals/pvldb/WillhalmPBPZS09}. Thus, some query operators have been proposed for more sophisticated physical-level compression formats. In this direction, the column scan has received a lot of attention. For example, Willhalm et al. proposed \emph{SIMD-Scan}, a full column scan algorithm for data packed with arbitrary bit widths~\cite{DBLP:journals/pvldb/WillhalmPBPZS09}. They observed that such full column scans are usually memory-bound, but become compute-bound when performed on compressed data. To alleviate this, they focused on a vectorized implementation using Intel’s SSE instructions on 128-bit vector registers. Li and Patel criticize in~\cite{DBLP:conf/sigmod/LiP13} that the \emph{SIMD-Scan} algorithm suffers from a sub-optimal bit-level parallelism, since the employed 32-bit comparisons effectively waste available bits, if the bit width is below 32. To address this issue, they propose to use so-called \emph{bit-parallel methods}. In particular, the authors introduce two pairs of a physical memory layout and a column scan algorithm efficiently processing data in this layout using an algebraic framework. Feng et al.~\cite{DBLP:conf/sigmod/FengLKX15} build upon the work of Li and Patel and especially focus on using SIMD instructions. They call their approach \emph{ByteSlice} by proposing a new layout and a suitable scan algorithm. Besides selection, also aggregation has been studied for data compressed at the physical level. For example, Feng and Lo proposed bit-parallel implementations of common aggregation functions directly on compressed data~\cite{DBLP:conf/icde/FengL15}. \subsection{Compression and Query Execution} Besides individual operators for compressed data, there are different ways to employ compression in a query as a whole. Chen et al.~\cite{DBLP:conf/sigmod/ChenGK01} intensively investigated the integration of compression into query execution in the context of disk-centric row-stores and introduced three strategies: \begin{compactitem} \item[\textbf{Eager decompression:}] When base data is loaded into main memory, it is immediately decompressed and the entire query processing takes place on uncompressed data. \item[\textbf{Lazy decompression:}] Here, the data is kept in compressed form during query processing as long as possible. That is, base data and, perhaps, early intermediate results are represented in a compressed way and processed by compression-enabled operators. However, as soon as an operator cannot process the compressed data directly, the data is decompressed and from this point, all processing happens entirely on uncompressed data, which incurs unnecessarily large intermediates and wastes the potential of working on compressed data directly. \item[\textbf{Transient decompression:}] Here, operators incapable of processing compressed data directly decompress their inputs \emph{only temporarily} and \emph{keep the compressed input elements}. The processing is done on uncompressed data elements, but for the output, the compressed input elements are used again, such that subsequent query operators can still benefit from compression. \end{compactitem} For in-memory column-store systems, the \emph{lazy decompression} strategy has been investigated in several works~\cite{DBLP:journals/pvldb/DasYZVVKGKM15,DBLP:conf/sigmod/LangMFB0K16,DBLP:journals/pvldb/RamanABCKKLLLLMMPSSSSZ13,DBLP:conf/icde/ZukowskiHNB06}. For example,~\cite{DBLP:conf/sigmod/LangMFB0K16} proposes a storage format for cold (analyical) data subdividing a column into blocks, each of which can be represented in its individual compressed format. The formats to choose from are a variant of RLE as well as FOR and DICT combined with a byte-aligned NS algorithm. Based on that, they present an approach to integrate a vectorized column scan into the compilation-based query engine of HyPer~\cite{DBLP:conf/icde/KemperN11}. In particular, their scan outputs a list of logical positions in the compressed column, which are subsequently extracted and decompressed. After that, the query execution continues with uncompressed data. Another example is Oracle's in-memory engine \cite{DBLP:journals/pvldb/DasYZVVKGKM15} executing only selection scans on compressed data as well. A more sophisticated approach was presented in~\cite{DBLP:conf/sigmod/AbadiMF06}. The authors show how they integrate five compressed formats into the query execution of the column-store \emph{C-Store} \cite{DBLP:conf/vldb/StonebrakerABCCFLLMOORTZ05}. They observe that supporting $n$ compressed formats requires $n$ variants of all unary query operators and $n^2$ variants of all binary query operators. Since this amounts to a high total number, their main focus is on the reduction of the integration effort. Most importantly, each base and intermediate column is split into blocks that can be accessed by operators via a special API. This API abstracts from the particular format by exposing properties exploitable by query operators, e.g., whether the data in the block is sorted or whether the block contains only one distinct value. Consequently, query operators are not specialized to individual formats, but to such properties, which can reduce the number of variants. As a fallback, the API allows to decompress the block so that the operator can iterate over the uncompressed data elements. The authors' extension to C-Store also supports compressed intermediates. However, an operator's output format is hard-coded for each (combination of) input format(s) and chosen depending on what seemed easy to implement to the authors. In particular, data characteristics of the intermediates are not taken into account. In Hyrise \cite{DBLP:conf/vldb/Boissier18,DBLP:conf/edbt/0001J19,DBLP:conf/edbt/DreselerK0KUP19}, base data is represented as columns horizontally partitioned into segments, whereby each segment can have its individual compressed format. To limit the effort of integrating compression into the query execution, the authors also decide to introduce a layer of abstraction. In particular, they implement iterator-based methods for sequential and random access to each compressed format. Query operators make use of the general iterator-interface irrespective of the underlying compressed formats of their inputs. Intermediate results are not explicitly compressed. The only work we are aware of that explicitly investigates the compression of intermediate results is \cite{DBLP:journals/vldb/GuzunC16}. Unfortunately, the authors focus only on complex queries over \emph{bit vectors}, i.e., another data structure, with the operators \texttt{AND}, \texttt{OR}, and \texttt{XOR}. Furthermore, they distinguish only between uncompressed and compressed data, but not between different compressed formats. Nevertheless, their motivation is similar to ours: They also observe that the characteristics of intermediate bit vectors may change during query processing, rendering either the compressed or the uncompressed representation more suitable on a \emph{per-intermediate} basis. Therefore, they want to support operators on all possible combinations of (un)compressed inputs and outputs. While they can reuse (un)compressed-only operators from previous works, they contribute variants for mixed compressed and uncompressed inputs. Moreover, they decouple the output format from the input formats by reusing existing methods to append to (un)compressed bit vectors. \subsection{Lessons Learned} Lightweight integer compression is widely used by state-of-the-art systems \cite{DBLP:conf/sigmod/AbadiMF06,DBLP:journals/pvldb/DasYZVVKGKM15,DBLP:conf/edbt/DreselerK0KUP19,DBLP:conf/sigmod/LangMFB0K16,DBLP:journals/pvldb/RamanABCKKLLLLMMPSSSSZ13}, whereby the degree of integration varies. The approaches to integrate compression into query operators range from a generic and transparent decompression during the reading data access~\cite{DBLP:conf/icde/ZukowskiHNB06} over abstractions for compressed formats \cite{DBLP:conf/sigmod/AbadiMF06} to highly format-specific algorithms for particular operators \cite{DBLP:conf/icde/FengL15,DBLP:conf/sigmod/FengLKX15,DBLP:conf/sigmod/LiP13,DBLP:journals/pvldb/WillhalmPBPZS09}. However, the main focus of compression is always on the storage and processing of \emph{base data}. The lightweight compression of \emph{intermediate results} has only been considered for row stores \cite{DBLP:conf/sigmod/ChenGK01} and bit vectors \cite{DBLP:journals/vldb/GuzunC16}. To the best of our knowledge, a \emph{systematic} investigation of lightweight integer compression for intermediate results in complex analytical queries in in-memory column-stores has never been addressed before. Thus, we close this gap with our \emph{holistic compression-enabled} processing model. \section{Compression-enabled Model} \label{sec:Model} The overall goal of our \emph{holistic compression-enabled processing model} is to enable the continuous use of lightweight integer compression for intermediate results in in-memory column-stores while pursuing the design principles as introduced in Section~\ref{sec:Motivation}. In this sense, our novel model can be seen as an optimization of the \emph{operator-at-a-time} processing model pioneered by MonetDB~\cite{DBLP:journals/cacm/BonczKM08,DBLP:journals/debu/IdreosGNMMK12}. The operator-at-a-time model explicitly materializes intermediates, because each operator within an query execution plan (QEP) is evaluated to completion over its entire input data, before subsequent data-dependent operators are invoked~\cite{DBLP:journals/debu/IdreosGNMMK12}. In this section, we present the main concepts of our novel model by describing (i) the foundations, (ii) the compression-enabled operators and (iii) the integration into the query execution. \subsection{Foundations} First of all, base data, intermediate results, and query results of our compression-enabled processing model are of exactly the same nature, whereby the elements of each column are unsigned integers. Moreover, all base data and intermediates are fully materialized in compressed form using an arbitrary lightweight integer compression algorithm, whereby each column has exactly one format. Alternatively, a column can also be uncompressed if \emph{desired}. If the integers were obtained through a dictionary coding, we assume an individual dictionary per domain as proposed in~\cite{DBLP:journals/pvldb/LeeABCDHI0LLMMPQRSSSZ14}. If range predicates need to be evaluated, we assume the dictionary coding to be order-preserving. Otherwise, the equality-preserving property of DICT suffices without any changes to our processing model. Second, our query operators are strongly inspired by those of MonetDB~\cite{DBLP:journals/vldb/BonczK99}. Initially, MonetDB’s operators processed BATs consisting of a head and a tail column~\cite{DBLP:journals/cacm/BonczKM08,DBLP:journals/debu/IdreosGNMMK12}, but meanwhile, these operators have been re-engineered to work on headless BATs, i.e., mere sequences of values~\cite{MonetDBGoesHeadless}. We adapt this latter approach, since it fits our needs of processing sequences of integers very well. \begin{figure} \centering \includegraphics[width=0.9\linewidth]{figures/degrees_overview.pdf} \caption{Degrees of integrating lightweight integer compression into query operators at the example of an operator \texttt{op} with two inputs and one output.} \label{fig:proc:pm:degrees} \vspace{-0.5cm} \end{figure} \subsection{Compression-enabled Operators} A major challenge for our \emph{holistic compression-enabled processing} model is the interplay between operators and (de)compression. For that, we distinguish four degrees of integration possibilities and these are derived from two orthogonal dimensions as illustrated in Figure~\ref{fig:proc:pm:degrees}. The first dimension addresses the \emph{internal processing}: The operator could either execute its operations on \emph{uncompressed} data elements or on data elements \emph{compressed} according to a particular format, whereby the operator could expect an individual format for each of its input and output columns. The second dimension concerns the operator's \emph{data access}: Here, the first option is to access the data \emph{directly} in the format it is represented in. This is only possible if this format matches the format of the operator's internal processing. Alternatively, the operator could \emph{adapt} the data to the formats it expects internally. Input data needs to be adapted before it is consumed and output data is first produced in the operator's internal format and afterwards adapted to the desired output format. Each combination of these two dimensions is possible and each of them has its individual advantages and disadvantages with respect to both implementation effort and typical optimization objectives such as performance and memory footprint. In the following, we explain each degree of integration in more detail. \subsubsection*{Purely Uncompressed} This trivial degree (Figure~\ref{fig:proc:pm:degrees}(a)) is characterized by an internal processing of \emph{uncompressed} data with \emph{direct} data access. It involves no compressed data at all and serves merely as a baseline for the following concepts. \subsubsection*{On-the-Fly De/Re-Compression} Query operators adopting \emph{on-the-fly de/re-compression} can handle compressed inputs and outputs (adaptive data access), but process uncompressed data internally (Figure \ref{fig:proc:pm:degrees}(b)). This is currently the most important degree of integration for us, since it can easily be implemented, but already fulfills the design principles DP1 to DP3. Nevertheless, it leaves the potential of working directly on compressed data unexploited, such that additional degrees are sensible. This degree is achieved by a wrapper around the operator which temporarily decompresses the inputs and recompresses the outputs of the operator. This idea is not entirely new and it was inspired by \emph{transient decompression} proposed by Chen et al.~\cite{DBLP:conf/sigmod/ChenGK01}. However, \emph{on-the-fly de/re-compression} goes one step further than transient decompression, since it allows a recompression to \emph{another format} than the input. The employed wrapper can work at different levels of granularity at both the input and the output side. The coarsest granularity is the \textbf{entire column}. Using this approach for all operators in a QEP does not make sense, since this would mean that an operator first produces an entire uncompressed column, which is then compressed as a whole, but afterwards decompressed as a whole again by the following operator. A more reasonable granularity is the \textbf{L$x$-cache-resident block}. The basic idea is not to materialize uncompressed data in main memory, but only in the cache hierarchy. On the input side, the wrapper decompresses a block of compressed data when required and hands only the uncompressed block to the operator. On the output side, the operator first stores uncompressed data elements, which are recompressed when the block size is reached. Hence, (de)compression and operator execution are separated at the function/routine-level. On both sides, the block size does not need to match the compressed format's block size (if the format works with blocks at all). Instead, the block size should be chosen in a cache-conscious way to guarantee that the decompressed data is still in the L$x$-cache when the processing starts and the data to be recompressed is still in the L$x$-cache when the wrapper issues the recompression of a block. Note that this approach is related to RAM-cache decompression proposed by Zukowski et al.~\cite{DBLP:conf/icde/ZukowskiHNB06} with the difference that our \emph{on-the-fly de/re-compression} is designed to also output compressed data, thereby allowing for compressed intermediates. The finest granularity is the \textbf{vector register}. This is the most fine-grained option possible with a state-of-the-art vectorized processing~\cite{DBLP:conf/sigmod/FengLKX15,DBLP:journals/pvldb/KerstenLKNPB18,DBLP:conf/sigmod/PolychroniouRR15,DBLP:conf/damon/PolychroniouR19,tvl,DBLP:conf/sigmod/ZhouR02}. On the input side, the wrapper decompresses the data elements one vector at a time and forwards single vectors of uncompressed data elements to the operator. On the output side, the operator produces vectors of uncompressed data elements, which it passes to the wrapper for instantaneous recompression. This means that the borders between (de)compression and operator execution are blurred, as these are separated only at the instruction-level. Unfortunately, this granularity is not possible for all combinations of \emph{output} formats and operators. Some lightweight integer compression algorithms need to analyze a certain number of data elements to decide how to compress them. For instance, SIMD-BP128 \cite{DBLP:journals/spe/LemireB15} needs to determine the maximum bit width of a block of 128 data elements before it can pack the data. This bit width cannot be known when just one vector register of uncompressed data elements is available at a time. \textbf{Advantages:} This degree already enables a continuous use of compression for all intermediates (and base data) with a low integration effort. To support $n$ compressed formats for one operator, the original operator for uncompressed data is reused. Additionally, only $n$ compression and $n$ decompression algorithms are required, which can be used for wrapping other logical operators as well. Moreover, the decoupling of the decompression of the inputs and the recompression of the outputs allows the formats of all intermediates to be chosen independently from each other, such that a change of the compressed format during the query execution is easily possible by configuring the wrapper accordingly. \textbf{Disadvantages:} The obvious downside is its internal processing of \emph{uncompressed} data. This does not only limit the possible data-level parallelism, but also prohibits a more sophisticated exploitation of the particular compressed formats which could simplify the operators' work. \subsubsection*{Specialized Operators} A \emph{specialized} operator works on compressed data internally (Figure \ref{fig:proc:pm:degrees}(c)). It is tailored for a specific combination of compressed formats of its inputs and outputs and accesses these directly. Thus, the intermediates serving as the inputs and outputs must be represented in exactly the formats expected by the operator. Nevertheless, it can improve the performance by processing compressed data without \emph{any} decompression and through an increased data-level parallelism. Furthermore, it allows to employ operators on compressed data from the literature as presented in Section~\ref{sec:Narrow:Operators} and thus, fulfills our design principle D4. For example, the proposed column scan approaches BitWeaving~\cite{DBLP:conf/sigmod/LiP13} or ByteSlice~\cite{DBLP:conf/sigmod/FengLKX15} are specialized operators in this sense. \textbf{Advantages:} Specialized operators avoid the materialization of uncompressed data altogether. Owing to this, they are a promising approach for improving the operator performance compared to on-the-fly de/re-compression. Upon the bandwidth saving achieved through the avoidance of uncompressed data transfer between main memory and CPU, specialized operators add a reduction of the computational effort caused by the integration of lightweight integer compression. This is achieved by the avoidance of any (de)compression overhead, the increase of the data-level parallelism, and the exploitation of format-specific information to shortcut the operator execution. \textbf{Disadvantages:} The most decisive drawback of specialized operators is the high conceptual and integration effort they incur. To support all combinations of $n$ compressed formats for the $i$ inputs and $o$ outputs of one operator, $n^{i+o}$ variants of that operator must be provided. Unless all of these variants are available, the choice of the intermediates' formats is restricted, since they must match those expected by the operators. This is a significant burden to fulfilling design principle DP2. Therefore, we propose to employ specialized operators only selectively. Finally, a specialization also implies that a particular operator might only be applicable and beneficial in rare cases, depending on the data characteristics of the intermediate and the QEP structure. \subsubsection*{On-the-Fly Morphing} Operators employing \emph{on-the-fly morphing} process compressed data internally, but can handle inputs and outputs in \emph{different} compressed formats by means of an adaptive data access (Figure \ref{fig:proc:pm:degrees}(d)). Similar to \emph{on-the-fly de/re-compression}, this adaptation of the formats is performed by a wrapper. However, this wrapper does not employ (de)compression algorithms, but so-called \emph{direct morphing algorithms}, which are capable of changing the data representation from one compressed format to another one~\cite{DBLP:conf/adbis/DammeHL15a}. In fact, the idea of adapting the compressed formats of an operator's inputs has already been sketched by Lee et al.~\cite{DBLP:journals/pvldb/LeeABCDHI0LLMMPQRSSSZ14}. However, their \emph{encoding translation} addresses only (i) the inputs (ii) of join-operators, and (iii) only DICT-compressed data. In contrast, our proposed on-the-fly morphing~\cite{DBLP:conf/adbis/DammeHL15a} (i) can also be applied to an operator's outputs, (ii) is possible for any query operator, and (iii) supports arbitrary compressed formats. Thus, this integration degree enables more flexibility when using specialized operators, since it allows intermediates to have any format, independently from the operator. Analogous to on-the-fly de/re-compression, the wrapper enabling on-the-fly morphing can work at the same three levels of granularity and we only briefly comment on noteworthy differences compared to on-the-fly de/re-compression. Morphing at the granularity of the \textbf{entire column} is still not favorable. However, it does not introduce fresh \emph{uncompressed} intermediates any more, since these are now also \emph{compressed}. Regarding the granularity of the \textbf{L$x$-cache-resident block}, instead of materializing \emph{uncompressed} data in the caches, with on-the-fly morphing only \emph{compressed} data is materialized. Nevertheless, the cache-conscious materialization can be expected to be beneficial for compressed data as well. Morphing is also possible at the \textbf{vector register} granularity \cite{DBLP:conf/adbis/DammeHL15a}. However, the restrictions with respect to the operator's output remain unchanged. \textbf{Advantages.} On-the-fly morphing unifies the virtues of on-the-fly de/re-compression and specialized operators. It provides the full flexibility regarding the choice of the intermediates' formats and yields the benefits of processing compressed data internally. Using existing specialized operators as a basis, the integration effort is fair: To support all combinations of $n$ compressed formats for the inputs and output of one operator, $n^2 - n$ direct morphing algorithms are required, one for each ordered pair of two distinct formats. These morphing algorithms can be reused for all operators. \textbf{Disadvantages.} On-the-fly morphing also comes with a certain computational overhead caused by the wrapper, which might or might not be beneficial, depending on the situation and the optimization objective. Moreover, the direct morphing algorithms have to be developed. \subsection{Integration into Query Execution} A QEP exploiting compression is constructed using our \emph{compression-enabled} query operators in the same manner as for uncompressed processing since the operators' interfaces have the same semantics and only differ in the compressed formats. In such a QEP, each base column and intermediate result has a particular compressed format (or could remain uncompressed). However, it is crucial that the plan is \emph{consistent}. That means, the format of each input and output of each query operator must match the format of the accessed data. Furthermore, the final query output column(s) should always be uncompressed, since it cannot be assumed that a client application can interpret compressed data. It is possible to employ the same degree of integration for all query operators in the QEP. However, it is perfectly valid to use an individual (combination of) degree(s) for each operator. The decision of the degree of integration for a particular operator depends on two factors: (i) the availability of the respective compression-enabled variant, and (ii) typical objectives of query optimization, such as memory footprint or query runtime. \section{MorphStore Engine} \label{sec:Engine} The open-source analytical query engine \emph{MorphStore}\footnote{The complete source code is available on GitHub: \\ \url{https://morphstore.github.io}} provides our \emph{holistic compression-enabled} processing model implemented in C++. Since vectorization using SIMD instructions is state-of-the-art~\cite{DBLP:conf/sigmod/FengLKX15,DBLP:journals/pvldb/KerstenLKNPB18,DBLP:conf/sigmod/PolychroniouRR15,DBLP:conf/damon/PolychroniouR19,DBLP:conf/sigmod/ZhouR02}, all query operators and (de)compression algorithms in \emph{MorphStore} are also explicitly vectorized, whereby we use SIMD functionality through our recently introduced \emph{Template Vector Library} (TVL) \cite{tvl}. Our TVL allows to write explicitly vectorized C++ code independently of any particular SIMD extension. Besides generic data types, e.g., for vector registers, it offers so-called \emph{primitives}. These are C++ function templates providing typical SIMD functionality, such as loading a vector and numerous operations on vectors. A smart use of C++ template specialization and inlining allows the compiler to effectively substitute each primitive (i) by the corresponding SIMD intrinsic of a particular SIMD extension or (ii) by a corresponding scalar function \emph{with virtually no runtime overhead} \cite{tvl}. This allows a single operator implementation, which can be tailored (i) to a chosen SIMD extension or (ii) to a scalar version by simply passing a particular template parameter. Thus, our following descriptions abstract from any particluar SIMD extension or vector length. \subsection{Column Storage} We decided to assume (unsigned) \emph{64-bit} integers as the data type of the uncompressed data, since this is the native word width of most common microprocessors nowadays. Instead of supporting other typical integer widths, such as 8, 16, and 32 bits, as individual \emph{data types}, we view them as particular \emph{compressed formats}. Going from 32-bit integers assumed by most of the literature on lightweight integer compression \cite{DBLP:journals/spe/LemireB15,DBLP:conf/damon/SchlegelGL10,DBLP:conf/cikm/StepanovGREO11,DBLP:journals/tois/ZhaoZLSNYW15} to 64-bit integers implies that these existing implementations cannot be reused as-is. Therefore, we reimplemented some algorithms for 64-bit data elements, while otherwise adhering closely to the algorithms' ideas. In particular, at the logical level, we currently support (i) DELTA and (ii) FOR, and at the physical level, we currently support the following NS schemes (i) static BP (a variant of BP with one block and fixed bit width for all data elements) and (ii) SIMD-BP \cite{DBLP:journals/spe/LemireB15} (see Section~\ref{sec:Narrow:Algos}).\footnote{The low diversity is only due to the state of the implementation.} Additionally, cascades of one logical-level and one physical-level algorithm are possible. \begin{figure}[t] \centering \includegraphics[width=0.95\linewidth]{figures/column_layout.pdf} \caption{ Three representations of the same column. } \label{fig:proc:pm:column_layout} \vspace{-0.4cm} \end{figure} Base data, intermediates, and query results are exclusively represented as columns in \emph{MorphStore} and our column data structure is a continuous buffer of bytes. Therein, the entire data of the column is stored either uncompressed or compressed according to \emph{exactly one} of the formats mentioned above. Some lightweight integer compression algorithms are able to compress integer sequences of arbitrary lengths. However, others subdivide the data into blocks of a certain number of data elements and cannot represent smaller amounts of data, e.g., SIMD-BP512, our port of SIMD-BP128 to AVX-512~\cite{DBLP:journals/tods/DammeUHHL19}, assumes blocks of 512 data elements each. To be able to deal with columns of arbitrary lengths, each column is subdivided into a compressed main part and an uncompressed remainder as illustrated in Figure~\ref{fig:proc:pm:column_layout}. Assuming a column of $n$ data elements and a compression algorithm with a block size of $bs$, the compressed part contains the first $\lfloor n / bs \rfloor$ data elements of the column represented in the column's compressed format and the remainder contains the remaining $n \mod bs$ data elements as uncompressed 64-bit integers. The remainder is stored directly behind the compressed data in the column's buffer and has to be taken into account by operators, too. A separate structure of meta data stores the sizes of the compressed part and the uncompressed remainder. \subsection{Query Operators} Our current implementation is limited to a set of physical query operators that are sufficient to execute the well-established Star Schema Benchmark (SSB)~\cite{DBLP:journals/corr/Sanchez16a}. Nevertheless, since our presented integration concepts are not operator-specific, other operators could be embraced in the same way. Generally, we started with the implementation for a purely uncompressed processing inspired by MonetDB operators~\cite{DBLP:journals/cacm/BonczKM08,DBLP:journals/debu/IdreosGNMMK12}. Then, we focused on \emph{on-the-fly de/re-compression} because the continuous use of compression is completely realizable for all analytical queries in a very generic way using that degree of integration. Moreover, the \emph{specialized} and \emph{on-the-fly morphing} operators are just further optimizations of \emph{on-the-fly de/re-compression}. Generally, a na{\"i}ve implementation of the \emph{on-the-fly de/re-compression} degree would suffer from either (i) low performance due to, e.g., virtual function calls, or (ii) high source code duplication due to the explicit implementation of all combinations, resulting in hardly maintainable source code. To avoid both of these issues, we apply a number of specific techniques. As a natural fit to SIMD processing, operating the wrapper for adaptive data access at the vector register-granularity is desirable, since that way, the materialization of uncompressed data even in the caches can be avoided. Hence, we adopt this approach \emph{on the input side}. However, due to the reasons mentioned in Section~\ref{sec:Model}, this is not always possible \emph{on the output side}. Therefore, we use the granularity of an L$x$-cache-resident block here. Regarding the data access patterns, we can observe that almost all physical operators access both their input and output data in a sequential way. \begin{figure}[tb] \centering \includegraphics[width=\linewidth]{figures/otf_impl.pdf} \caption{ Execution of a query operator adopting on-the-fly de/re-compression. } \label{fig:proc:pm:otf_impl} \vspace{-0.4cm} \end{figure} As depicted in Figure \ref{fig:proc:pm:otf_impl}, each \emph{on-the-fly de/re-compression} operator follows a division-of-concerns approach by employing \emph{three layers} with the following responsibilities: The \emph{column layer} provides the interface to the operator and takes care of the subdivision of the column into a compressed part and an uncompressed remainder. The \emph{buffer layer} realizes the \emph{wrapper} for the adaptive read and write access to the input and output data, respectively. Eventually, the \emph{vector register layer} represents the actual \emph{operator core}. The name of each layer indicates the unit of data it consumes and produces. Each of these layers is implemented as a C++ function, whereby the column and buffer layers require individual functions for the \emph{input side} and the \emph{output side}. In the following, we describe the execution of an operator with one input and one output column, both of which are accessed \emph{sequentially}. With the numbers in brackets, we refer to those in Figure \ref{fig:proc:pm:otf_impl}. The column layer provides the interface for calling the operator. On the input side, it identifies the compressed main part and uncompressed remainder of the input column with the help of the column's meta data. Then, it calls the input-side buffer layer once for each of these two sub-buffers (1). The input-side buffer layer is essentially the decompression routine of the input column's compressed format (2) or a simple loading of uncompressed data for the remainder (3). However, instead of storing decompressed vectors to memory, it passes each of them on to the operator core at the vector register layer (4). The vector register layer consumes vectors of uncompressed 64-bit data elements. It executes the respective operator on each vector, whereby a vector of uncompressed output data elements is produced (5). For selective operators, a bit mask indicates which of the output vector's elements are valid. This output vector, perhaps accompanied by a bit mask, is handed over to the output-side buffer layer. The output-side buffer layer accepts one uncompressed vector at a time and appends it to its uncompressed internal L$x$-cache-resident buffer, whereby the valid data elements indicated by the bit mask are stored compactly (6). Once this internal buffer reaches its capacity, the compression algorithm of the output column's format is called (7). It loads uncompressed data from the internal buffer and appends compressed data to the output column's buffer (8). After both calls to the input-side buffer layer have terminated, the possible remaining data elements in the output-side buffer layer's internal buffer need to be flushed. Of this remaining data, as much as possible is appended to the output column in compressed form, while the possible remainder is appended uncompressed (9). Finally, the output-side column layer returns the output column to the caller of the operator (10). It is noteworthy that the input-side and output-side work in an \emph{interleaved} fashion, i.e., the output-side is active before the input-side returns. A close look reveals that the buffer layer is the only layer whose \emph{implementation} depends on the particular format, while the column layer only needs to know the format to invoke the buffer layer correctly, and the vector register layer is not concerned with formats at all. At the same time, the buffer layer is the only layer that is \emph{not specific to the logical operator}, while the vector register layer is obviously specific, and the column layer needs to know the operator core to pass to the buffer layer. This constellation enables an economical, non-repetitive implementation based on C++ template metaprogramming. In particular, the formats of the input and output columns are modeled as template parameters of the column and buffer layers. The column layer is implemented generically with respect to these formats. However, for both the input-side and the output-side of the buffer layer, template specializations must be provided for each format to be supported. These specializations are strongly based on the decompression and compression algorithms of the formats, respectively. Thus, these specializations can be reused by all operators. Furthermore, the input-side buffer layer receives the core operator to call as a template parameter as well. Finally, the column layer has to initialize the vector register layer such that it calls the output format's template specialization of the output-side buffer layer. The use of templates prevents expensive \emph{virtual} function calls, since the right specializations are determined at compile-time. Besides that, expensive frequent calls to the vector register layer are avoided by forcing the compiler to inline it into the input-side buffer layer. However, there are some operators employing random read access or random write access. For example, the \texttt{project}-operator requires random read access to compressed data, because this operator is used, for instance, to transfer the result of a selection result on one column (sequentical access) to another column (random access). Since lightweight integer compression algorithms are designed for efficient sequential access, random access incurs some challenges. At the logical level of compression, the interpretation of one particular compressed data element might require either meta information, as for FOR and DICT, or even information on all preceding compressed data elements, as for DELTA. At the physical level of compression, the challenge is threefold: (i) the physical byte or bit address corresponding to a logical position must be determined, (ii) depending on the format, one \emph{or more} random accesses are required to obtain all bits of a code word, and (iii) the original data element must be restored from the obtained bits. In the literature, random read access has been investigated to \emph{certain compressed formats} \cite{DBLP:conf/sigmod/FengLKX15,DBLP:conf/sigmod/LiP13,DBLP:journals/pvldb/WangLHCPS17}. However, we decided to follow a simple approach by restricting random access to BP with a fixed bit width for all data elements (which we call static BP) and uncompressed data. For these formats, all of the challenges mentioned above can be solved in a straightforward way. The integration of these formats is again accomplished using one specialization of a template function for random read access per format. In case of random write access to compressed data, we observed that this very often belongs to the query's result column(s), e.g., in a group-based aggregation. Since these shall be uncompressed anyway, we do not yet consider random write access to compressed data. \section{Experimental Evaluation} \label{sec:Evaluation} We conducted our experimental evaluation on a server machine equipped with an Intel Xeon Gold 6130 clocked at 2.1 GHz. The capacities of the L1, L2, and L3-caches are 32 KiB, 1 MiB, and 22 MiB, respectively. The system has 4 sockets with 32 cores each and exhibits a non-uniform memory access (NUMA). However, we only investigate the single-thread performance and ensured that all memory is allocated on the local socket to exclude NUMA effects~\cite{DBLP:conf/btw/KieferSL13,DBLP:conf/sigmod/LeisBK014}. The size of the ECC DDR4 main memory is 384 GiB and all experiments happened entirely in-memory. All our operator and (de)compression algorithm implementations are specialized to a scalar and an AVX-512 version through our TVL~\cite{tvl}. Unless stated otherwise, we report the AVX-512 measurements. We choose a size of 16 KiB, or 2,048 uncompressed data elements, for the internal buffer used at the output side of our on-the-fly de/re-compression operators. Note that this is half of the size of the L1 cache of our machine. We compiled our source code using \texttt{g++} version 8.3.0 with the optimization flag \texttt{-O3}. The operating system is a 64-bit Ubuntu 18.10 with Linux kernel version 4.18.0-13-generic. We repeated all time measurements 10 times and report only the means. Next, we present some micro-benchmarks to provide a clear understanding of \emph{MorphStore}, before we report our results using the Star-Schema Benchmark~\cite{DBLP:journals/corr/Sanchez16a} including a comparison with MonetDB. \subsection{Micro-Benchmarks} \begin{table} \centering \caption{ Properties of our synthetic columns. Each column contains 128 Mi data elements. } \label{tab:datach} \begin{tabular}{|c|l|c|c|} \hline & Data distribution & Sorted & Maximum \\ & & & bit width \\ \hline \hline C1 & uniform in $[0, 63]$ & no & 6 \\ \hline C2 & 99.99\% uniform in $[0, 63]$ & no & 63 \\ & 0.01\% constant $2^{63}-1$ & & \\ \hline C3 & uniform in $[2^{62}, 2^{62}+63]$ & no & 63 \\ \hline C4 & uniform in $[2^{47}, 2^{47} + 100\text{K}]$ & yes & 48 \\ \hline \end{tabular} \vspace{-0.4cm} \end{table} The behavior of lightweight integer compression algorithms depends strongly on the data characteristics~ \cite{DBLP:conf/edbt/DammeHHL17,DBLP:journals/tods/DammeUHHL19}. Since DBMSs have to handle data with arbitrary properties efficiently, we use synthetic columns (C1-C4) for our micro-benchmarks and Table \ref{tab:datach} summarizes their characteristics. \textbf{Single Operator.} We first investigate the runtime of a single operator as the building block for complex QEPs. In particular, we choose the \texttt{select}-operator, which takes a column as input and outputs a sorted column containing the \emph{positions} in the input column that store matching data elements. Note that these positions are themselves unsigned integers. For each input column, we want to select the (a-priori known) lowest data element in the column using a point predicate. We adapt the distributions mentioned in Table \ref{tab:datach}, such that 90\% of all data elements are this value, while the remaining 10\% are distributed as specified. Since \emph{MorphStore} currently supports five compression algorithms, there are 25 format combinations of input and output for the \texttt{select}-operator. Figure \ref{fig:select} gives an overview of the runtimes of \emph{all} combinations for all input columns (C1-C4). We see that the runtime of the purely uncompressed processing (red dot) is about the same for all input columns, which is expected. The employment of our \emph{on-the-fly de/re-compression} (blue and gray dots) can save between 72\% and 81\% of the runtime in the best case, depending on the input column. At the same time, the runtime can increase by 20\% for C1--C3 in the worst case. Compressing also the output column (gray dots) can reduce the runtime much further than compressing only the input column (blue dots). This is interesting, since the output column can only be an intermediate in the context of a QEP. The input format employed by the fastest combination depends on the input column. For C1, static BP is preferred, since it contains rather small values. C2 contains 0.01\% huge outliers, rendering SIMD-BP512 a better choice, since it can adapt to the local data distribution in each block of 512 data values. The distribution of C3 has a narrow range of huge values, thus, FOR + SIMD-BP512 is most suitable here. DELTA + SIMD-BP512 results in the best runtime for the sorted column C4. The output format employed by the fastest variant is DELTA + SIMD-BP512 in all cases, since the output is always sorted. We conclude that our \emph{on-the-fly de/re-compression} can reduce the runtime of a single operator \emph{significantly}, if the formats are chosen carefully. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/select_vldb.pdf} \caption{ Runtime evaluation \texttt{select}-operator. } \label{fig:select} \vspace{-0.5cm} \end{figure} \textbf{Simple Query.} We extend our evaluation to a simple analytical query: given a relation \texttt{R} with attributes \texttt{X} and \texttt{Y}, our query is \texttt{SELECT SUM(Y) FROM R WHERE X = c}. The first step of the query execution is the selection we have investigated above, i.e., the selectivity is 90\% again, with input column \texttt{X} and output column \texttt{X'}. After that, a \texttt{project}-operator extracts the data elements at the positions in \texttt{X'} from base column \texttt{Y} producing intermediate \texttt{Y'}. Finally, a \texttt{sum}-operator aggregates all data elements in \texttt{Y'}. Thus, our simple query consists of three operators accessing two base columns (\texttt{X} and \texttt{Y}), two intermediates (\texttt{X'} and \texttt{Y'}), and one result column with a single value which we ignore. We measured the memory footprint and runtime of this query for three cases, each of which is characterized by a certain combination of the base columns in Table \ref{tab:datach}. Each column can be assigned an individual compression format and there are $5 \cdot 2 \cdot 5 \cdot 5 = 250$ possible combinations.\footnote{Random access is currently only supported for uncompressed data and static BP. } However, here we concentrate on just a few interesting combinations, while not searching for the best one. Figure \ref{fig:select_sum}(a) shows the results for the query's memory footprint, broken down to the individual columns. First of all, the footprint of the purely uncompressed processing is the same irrespective of the characteristics of the base columns. Applying Static BP for the base columns results in a size reduction to 52\% in case 1, since \texttt{X} and \texttt{Y} contain only very small values here. The other extreme is case 3, where almost no size reduction can be achieved, since both base columns contain data elements of up to 63 bits. If Static BP is applied to the intermediates as well, further reductions to between 17\% (case 1) and 85\% (case 3) are the consequence. Representing both intermediates using DELTA + SIMD-BP512 reduces the size of \texttt{X'} significantly in all cases, since this column is always sorted. At the same time, DELTA + SIMD-BP512 is beneficial for \texttt{Y'} only in case 2, where a reduction to 24\% is achieved, while in case 1, it even yields a worse memory footprint than Static BP resulting in a reduction to only 30\% compared to the uncompressed processing. In fact, in cases 1 and 3, \texttt{Y'} should rather be represented using \mbox{FOR + SIMD-BP512} to achieve reductions to 11\% and 58\%, respectively. The runtimes of the whole query and the individual operators are displayed in Figure \ref{fig:select_sum}(b). Purely uncompressed processing is equally fast in all cases. Applying Static BP only for the base columns can decrease the runtime by only up to 4\% (case 1), since writing uncompressed intermediates is very expensive. In case 3, the query runtime is even \emph{increased} by 4\%. If the intermediates are compressed as well, the runtimes shrink to between 34\% (case 1) and 86\% (case 3). While using a suitable cascade for the intermediates could reduce the memory footprint in all cases, the runtimes can only be reduced in cases 2 and 3 by using DELTA or FOR cascaded with SIMD-BP512 in both cases. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/select_sum.pdf} \includegraphics[width=\linewidth]{figures/select_sum_legend.pdf} \caption{Evaluation results for a simple query.} \label{fig:select_sum} \vspace{-0.5cm} \end{figure} We conclude that the continuous compression of both base columns and intermediates can reduce the memory footprint as well as the runtime of a query, if the formats are chosen carefully. Furthermore, given two format combinations, the one that is better with respect to the memory footprint is not always better concerning runtime. \subsection{Star Schema Benchmark (SSB)} Next, we investigate the fitness of our novel processing model for complex analytical queries using SSB~\cite{DBLP:journals/corr/Sanchez16a} at scale factor 10. We applied an order-preserving dictionary encoding to all string columns in the schema to obtain integer columns. In fact, all 13 queries can be executed on dictionary keys without looking up the string values. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/ssb_formats.pdf} \includegraphics[width=\linewidth]{figures/ssb_formats_legend.pdf} \caption{ Impact of the format combinations in SSB. } \label{fig:ssb_formats} \vspace{-0.5cm} \end{figure} \textbf{Impact of Continuous Compression.} The QEPs of the SSB queries involve between 6 and 16 base columns and between 15 and 56 intermediates. Each of the columns can be represented in its individual compressed format, which results in a very high number of possible format combinations. Thus, we first want to find out the impact of different format combinations and the improvement through the optimal format combination. We allow compression for base columns and intermediates here. We consider the following format combinations for each query: (i) purely uncompressed, (ii) Static BP for all columns, and (iii/iv) the actual best/worst format combination. We determined the best/worst combination regarding memory footprint by exhaustively trying each available format for each column \emph{individually} (since column footprints add up) and employing the format yielding the lowest/highest physical size. Concerning runtime, we applied a greedy strategy which, starting at the base data, considers one column at a time by trying all available formats for that column, measuring the resulting query runtimes and fixing the column's format to the one yielding the best/worst runtime for the next steps of the search. Note that these best/worst combinations are allowed to employ the uncompressed format. Figure \ref{fig:ssb_formats}(a) shows the results for the memory footprint. The purely uncompressed processing achieves by far the worst memory footprints for all queries. Using Static BP for all columns reduces the memory footprint to between 30\% (Q3.2) and 55\% (Q1.2) (37\% on average). For Q1.x, 3.3, and 3.4 this is already the best choice. However, for the remaining queries, the optimal combinations yield a reduction to between 25\% (Q3.2) and 33\% (Q2.2) (35\% on average). Figure \ref{fig:ssb_formats}(b) depicts the query runtimes. Here, the worst combination results in a runtime \emph{increase} by 11\% on average, compared to the purely uncompressed case. Employing Static BP reduces the runtime for all queries except for Q3.3 and 3.4, while the ideal combination reduces the runtimes even for those queries. In detail, the best runtimes range between 49\% (Q3.2) and 93\% (Q3.3) (66\% on average), compared to purely uncompressed processing. To sum up, the continuous use of compression can significantly reduce memory footprint and runtime if the formats are well chosen, whereby the potential for reduction is query-dependent. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/ssb_base_vs_interm.pdf} \includegraphics[width=\linewidth]{figures/ssb_base_vs_interm_legend.pdf} \caption{Compression base data vs. intermediates.} \label{fig:ssb_base_vs_interm} \vspace{-0.6cm} \end{figure} \textbf{Impact Compression Base vs. Intermediates.} Our next question is in how far our continuous compression of \emph{intermediates} contributes to these reductions, compared to the already established compression of \emph{base data}. Thus, we start by not allowing compression at all, then we allow compression for the base columns only, and, finally, also for the intermediates. The results for the memory footprint can be found in Figure \ref{fig:ssb_base_vs_interm}(a). Allowing compression only for the base data already reduces the footprints significantly to between 33\% (Q3.4) and 74\% (Q3.1) (54\% on average). The impact of offering compression for intermediates too is highly query-dependent. For Q3.3 and 3.4, no further reduction is possible, while a further reduction to 25\% can be achieved for Q3.2. On average, compressing intermediates reduces the footprints to 35\%, i.e., 19\% further than with base columns only. Figure \ref{fig:ssb_base_vs_interm}(b) depicts the runtime results. These can either be reduced to up to 79\% (Q1.3) or not reduced (Q3.1) when compressing only base data (93\% on average), while the additional compression of intermediates achieves a reduction to between 49\% (Q3.2) and 92\% (Q3.4) (66\% on average). We can conclude that our continuous compression of intermediates contributes \emph{significantly} to the overall memory and runtime reductions achievable through compression. In fact, regarding the runtime, the intermediates' impact is even higher than that of the base columns, on average. \textbf{Comparison to MonetDB.} Next, we move on to a comparison to MonetDB, the system that is closest to our processing model \emph{in the uncompressed case}. To ensure a fair comparison, we compiled MonetDB-11.31.13 with all relevant optimization switches on using the same compiler (and version) and run it on the same machine as \emph{MorphStore}. We run MonetDB also in single-threaded and read-only mode. Although MonetDB supports string columns, we use the same dictionary-encoded base data. For our experiments, the QEPs used in \emph{MorphStore} imitate those of MonetDB as closely as possible, including the same join order. We used MonetDB's internal tools for measuring the mere query \emph{run}times, excluding the time spent on query optimization. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/ssb_morphstore_vs_monetdb.pdf} \includegraphics[width=\linewidth]{figures/ssb_morphstore_vs_monetdb_legend.pdf} \caption{ Comparing MonetDB and \emph{MorphStore}. } \label{fig:ssb_morphstore_vs_monetdb} \vspace{-0.5cm} \end{figure} The runtime results are given in Figure \ref{fig:ssb_morphstore_vs_monetdb}. Since MonetDB does not use SIMD instructions, we first compare the scalar execution on purely uncompressed data, i.e., all columns use 64-bit. None of the systems is faster than the other for all queries and on average, both systems are equally fast. The vectorized execution using AVX-512 can reduce the runtimes in \emph{MorphStore} by up to 54\% (Q1.2) or increase it by up to 16\% (Q4.1) (on average, it decreases by 19\%). Also employing our novel continuous compression for base columns and intermediates according to the ideal format combination reduces the runtimes further to between 35\% (Q1.3) and 79\% (Q4.1) of the scalar uncompressed processing in \emph{MorphStore} (54\% on average). While MonetDB has no explicit support for compression of intermediates, we try to simulate it by using the narrowest integer type possible for all base data columns in MonetDB. We can see that this improves the runtime of MonetDB to 84\% of its uncompressed runtime, on average, however, this is still much slower than \emph{MorphStore's} \emph{holistic compression-enabled} approach. Thus, we conclude that the query execution in \emph{MorphStore} achieves runtimes comparable to a state-of-the-art system \emph{in the purely uncompressed case}, while using our novel continuous compression of intermediates in combination with vectorization yields a speed up of $2\times$, on average. \textbf{Determining a good format combination.} Above, we have learned that a full exploitation of the potential of our \emph{compression-enabled} processing model requires a good combination of the columns' formats. Thus, our final question is how to find such a combination efficiently. In \cite{DBLP:journals/tods/DammeUHHL19}, we have proposed a cost-based selection strategy for lightweight integer compression algorithms, which adopts a gray-box approach by combining explicit modeling of functional properties of the algorithms and calibration capturing hardware-dependent behavior. Given a particular data set, our cost model can estimate the compression rate as well as (de)com\-pression performance of light\-weight integer compression algorithms and we have proven its effectiveness in \cite{DBLP:journals/tods/DammeUHHL19}. Here, we show that this cost model can be applied to determine a suitable format for each base column and intermediate in a QEP of a complex analytical query. In particular, we focus on minimizing the memory footprint as one very important optimization objective. For that purpose, we assume that some basic data characteristics required by our cost model, such as the number of (distinct) data elements, the bit width histogram, and the sort order, are known for all intermediates. We apply our cost model to obtain a good format combination by selecting a suitable compression algorithm for each base column and intermediate \emph{individually} with respect to the compression rate objective provided by our selection strategy for a single data set as described in \cite{DBLP:journals/tods/DammeUHHL19}. Figure \ref{fig:ssb_opt} compares the memory footprints resulting from the so-obtained format combinations to those achieved with static BP for all columns as well as the actual best combination found in an exhaustive search. While na{\"i}vely using static BP for all columns already comes very close to the optimal memory footprints for all SSB queries, the diagram clearly shows that our cost-based selection strategy yields memory footprints virtually equal to the actual optimal ones. We interpret these results as a promising first step into the direction of complementing our \emph{compression-enabled} processing model with a compression-aware query optimization to select suitable formats for all intermediates. However, to achieve the ultimate goal of a compression-aware optimization, more research in this direction is essential. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/ssb_opt.pdf} \includegraphics[width=\linewidth]{figures/ssb_opt_legend.pdf} \caption{ Fitness of our cost-based selection strategy~\protect\cite{DBLP:journals/tods/DammeUHHL19} for obtaining suitable format combinations. } \label{fig:ssb_opt} \vspace{-0.5cm} \end{figure} \section{Related Work} \label{sec:RelatedWork} Throughout the paper, we already covered related work regarding lightweight integer compression, query operators for compressed integer data and integration approaches of compression into query execution. Now, we focus on the description of different processing models to explain the differences between our novel model and existing ones. The classical processing model is the \emph{Volcano}-style iterator-based model (also called \emph{tuple-at-a-time}) proposed by Graefe for disk-oriented row-store database systems~\cite{DBLP:journals/tkde/Graefe94}. However, this classical model has shown to be unable to make effective use of the facilities of modern processors \cite{DBLP:conf/vldb/AilamakiDHW99,DBLP:conf/iccd/CaoTTLKW99}, especially due to data and instruction cache misses and branch mispredictions. Further disadvantages are described in~\cite{DBLP:journals/cacm/BonczKM08,DBLP:conf/cidr/BonczZN05,DBLP:conf/cidr/KissingerSHL13,DBLP:journals/pvldb/MenonPM17,DBLP:journals/pvldb/Neumann11,DBLP:conf/icde/PadmanabhanAMJ01,DBLP:conf/sigmod/ZhouR04}. To overcome these disadvantages and to increase the query performance, a variety of optimizations~\cite{DBLP:conf/icde/PadmanabhanAMJ01,DBLP:conf/icde/PadmanabhanAMJ01,DBLP:journals/tkde/StonebrakerRH90} and completely different processing models~\cite{DBLP:journals/cacm/BonczKM08,DBLP:conf/cidr/BonczZN05,DBLP:journals/tkde/Graefe94,DBLP:conf/cidr/KissingerSHL13,DBLP:journals/pvldb/MenonPM17,DBLP:journals/pvldb/Neumann11,DBLP:conf/icde/PadmanabhanAMJ01,DBLP:conf/sigmod/ZhouR04} have been proposed. For example, Kissinger et al.~\cite{DBLP:conf/cidr/KissingerSHL13} suggested an \emph{indexed-table-at-a-time} processing model for in-memory database systems. Their initial idea is the full materialization of each intermediate result in the form of an index. However, since the full materialization is expensive, the authors propose to fuse operators to \emph{composite operators}. A more sophisticated approach to avoid the materialization of intermediates was introduced by Neumann~\cite{DBLP:journals/pvldb/Neumann11} by maintaining the pipeline processing from one operator to the next. Since these pipelines are query-dependent, they must be compiled at query run-time. To reduce the implied overhead, the system builds upon the low-level virtual machine (LLVM) compiler framework \cite{DBLP:conf/cgo/LattnerA04} and directly generates the pipeline code in an LLVM intermediate representation. While the extra effort caused by the query dependent generation is a downside, it also enables the compiler to perform query-specific code optimizations, such that only the instructions required in the particular case need to be executed. While the overall aim is the avoidance of intermediate results, materialization is still required at the pipeline boundaries, for instance, when building the hash table of a hash join. The DBMS \emph{Peloton} \cite{DBLP:conf/cidr/PavloAALLMMMPQS17} employs an advancement of this approach that was proposed by Menon et al.~\cite{DBLP:journals/pvldb/MenonPM17}. The authors argue that the strict avoidance of intermediates and the tuple-at-a-time processing of the approach by Neumann disallow the exploitation of inter-tuple-parallelism offered by modern microprocessors. In particular, the authors show how to leverage SIMD and prefetching instructions. Moreover, they perform a strategic partial materialization of selected intermediate results, while otherwise they avoid intermediates using pipelining. In contrast to the previous approaches, MonetDB~\cite{DBLP:journals/cacm/BonczKM08,DBLP:journals/debu/IdreosGNMMK12} follows a completely different approach. Based on the decomposition storage model~\cite{DBLP:conf/sigmod/CopelandK85}, MonetDB uses an \emph{operator-at-a-time} model. That means, each operator takes one or more columns as input and produces one or more columns as output. Hence, all intermediate results are fully materialized. Moreover, each operator executes a simple operation on all input elements in a tight loop. This solves the problem of frequent instruction cache misses the iterator-based model suffers from, since the bulk of the data is processed by only a few instructions. Furthermore, it enables compilers to apply optimization techniques such as loop pipelining and makes it easier for the processor to apply out-of-order execution. Boncz et al.~\cite{DBLP:conf/cidr/BonczZN05,DBLP:journals/debu/ZukowskiBNH05} observe that a downside of the operator-at-a-time is that the full materialization of all intermediates can make the query processing memory-bound if the intermediates' size exceeds that of the cache. To address this issue, the authors present the \emph{X100} query engine, thereby proposing the \emph{vector-at-a-time} model. Their goal was to combine the column-wise processing of the operator-at-a-time model with the pipelined execution of the iterator-based model. The processing is done by so-called \emph{vectorized primitives}. These are operators which consume and produce partitions of a column, so-called \emph{vectors}. To sum up, a variety of different processing models have been proposed. On the one hand, some of these are designed to avoid the materialization of intermediates whenever it is possible \cite{DBLP:journals/tkde/Graefe94,DBLP:journals/pvldb/Neumann11}. However, in recent years, systems adopting these processing models have started to relax this aim and perform at least a selective or partial materialization of intermediates to further improve their query performance \cite{DBLP:journals/pvldb/MenonPM17,DBLP:conf/icde/PadmanabhanAMJ01,DBLP:conf/sigmod/ZhouR04}. On the other hand, some processing models explicitly materialize intermediates either fully \cite{DBLP:journals/cacm/BonczKM08,DBLP:conf/cidr/KissingerSHL13} or partially \cite{DBLP:conf/cidr/BonczZN05}. In this context, we developed a sensible alternative with our \emph{compression-enabled} processing model that has not yet been considered to this extent. In the future, we will enhance our novel model with some pipelining concepts. \section{Conclusion} \label{sec:Conclusion} In this paper, we presented \emph{MorphStore}, an in-memory analytical query engine with a novel \emph{holistic compression-enabled} processing model. As we have shown, our novel processing model is an optimization of the well-known \emph{operator-at-a-time} model by establishing a continuous use of integer compression for all intermediates in a query execution plan. In particular, we are able to \emph{significantly} reduce the memory footprint and the query runtime for analytical queries. In addition, our \emph{holistic compression-enabled} model builds on existing work, supplements it with meaningful approaches and combines them in one engine called \emph{MorphStore}. This holistic approach enables the seamless integration of previous work like BitWeaving~\cite{DBLP:conf/sigmod/LiP13} or ByteSlice~\cite{DBLP:conf/sigmod/FengLKX15} in this domain, but also opens up the possibility of driving the development of specialized operators for processing compressed integer data. Moreover, new challenges such as determining the best-suited compression scheme for intermediate results will become interesting and this opens ups a completely new dimension for query optimization. \section*{Acknowledgment} This work was partly funded by the German Research Foundation (DFG) within the CRC 912 (HAEC), RTG 1907 (RoSI) as well as by an individual project LE-1416/26-1. \balance \bibliographystyle{abbrv}
{'timestamp': '2020-04-21T02:28:40', 'yymm': '2004', 'arxiv_id': '2004.09350', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09350'}
arxiv
\subsubsection*{\bibname}} \begin{document} \twocolumn[ \aistatstitle{Thompson Sampling for Linearly Constrained Bandits} \aistatsauthor{ Vidit Saxena \And Joseph E. Gonzalez \And Joakim Jald\'{e}n } \aistatsaddress{ KTH Royal Institute of Technology\\Stockholm, Sweden\\[email protected] \And University of California\\Berkeley\\[email protected] \And KTH Royal Institute of Technology\\Stockholm, Sweden\\[email protected] } ] \begin{abstract} \input{sections/0_abstract.tex} \end{abstract} \section{Introduction} \input{sections/1_introduction.tex} \section{Problem Formulation} \label{sec:problem} \input{sections/2_problem.tex} \section{Algorithm and Finite-Time Analysis} \label{sec:linconts} \input{sections/3_algo.tex} \begin{figure*}[t!] \centering \subfigure[Regret]{ \includegraphics[width=0.23\textwidth]{figures/coupon_purchase_eta0_25_T10000_N16_REGRET.png} \label{fig:reg_coupon} } \subfigure[Violation]{ \includegraphics[width=0.23\textwidth]{figures/coupon_purchase_eta0_25_T10000_N16_VIOLATION.png} \label{fig:vio_coupon} } \subfigure[Cumulative Reward]{ \includegraphics[width=0.23\textwidth]{figures/coupon_purchase_eta0_25_T10000_N16_REWARD.png} \label{fig:rew_coupon} } \subfigure[Cum. reward / Violation]{ \includegraphics[width=0.23\textwidth]{figures/coupon_purchase_eta0_25_T10000_N16_REWARD_VIO.png} \label{fig:rew_vio_coupon} } \caption{ Experimental results for the Coupon-Purchase dataset for $N=142$ coupons with $\eta=0.25$. The LinConTS approach ouperforms the competing LinCon-KL-UCB approach by achieving a lower regret and violation, higher cumulative rewards and a higher ratio of cumulative rewards to violation. } \label{fig:Coupon} \end{figure*} \begin{figure*}[t!] \centering \subfigure[Regret]{ \includegraphics[width=0.23\textwidth]{figures/edX_eta0_50_T50000_N16_REGRET.png} \label{fig:reg_edx} } \subfigure[Violation]{ \includegraphics[width=0.23\textwidth]{figures/edX_eta0_50_T50000_N16_VIOLATION.png} \label{fig:vio_edx} } \subfigure[Cumulative Reward]{ \includegraphics[width=0.23\textwidth]{figures/edX_eta0_50_T50000_N16_REWARD.png} \label{fig:rew_edx} } \subfigure[Cum. reward / Violation]{ \includegraphics[width=0.23\textwidth]{figures/edX_eta0_50_T50000_N16_REWARD_VIO.png} \label{fig:rew_vio_edx} } \caption{ Experimental results for the edX-Course dataset for $N=290$ courses with $\eta=0.50$. The LinConTS approach ouperforms the competing LinCon-KL-UCB approach by achieving a lower regret and violation, higher cumulative rewards and a higher ratio of cumulative rewards to violation. } \label{fig:edx} \end{figure*} \section{Related Work} \input{sections/4_related.tex} \section{Numerical Experiments} \label{sec:numrel} \input{sections/5_numerical.tex} \section*{Acknowledgements} This work was partially supported by the Wallenberg Artificial Intelligence, Autonomous Systems and Software Program (WASP) funded by Knut and Alice Wallenberg Foundation. We thank Simon Lindst\r{a}hl for noting a flaw in the original formulation of Lemma~3, which has been updated in this version of the paper. \section*{Appendix A} Consider the Thompson samples $\theta_{i,t},\,i=1,\dots,N$ for any round indexed by $t$. The samples for stationary optimal arm $1$ and stationary suboptimal arm $i$ are denoted by $\theta_{1,t}$ and $\theta_{i,t}$ respectively. Let $M_i(t)$ denote the event \begin{eqnarray} M_i(t):\,\begin{cases}\theta_{j,t}\leq \kappa_j,\,j\not\in\{1,2,i\}\,,\text{ and}\\ \kappa_2 <\theta_{2,t}\leq \mu_2, \end{cases} \end{eqnarray} where we choose thresholds such that $\kappa_2>\eta$. Consider the probability of the event where suboptimal arm $i$ is selected under the filtration $\mathcal{F}_{t-1}$ and the Thompson sample $\theta_{i,t}$ such that $E_i^\theta$ is true, i.e., $\text{Pr}(i(t)=i|E_i^\theta(t),\mathcal{F}_{t-1})$. We have that arm $i$ is a part of the optimal solution only if arm $1$ is below the threshold $\kappa_1$, all other stationary arms are below their respective thresholds $\kappa_j,\,j\not\in\{1,2,i\}$, and the stationary optimal arm $2$ is above $\kappa_2$ (in which case at least some of the optimal solutions are supported by arms $i$ and $2$). Hence, we have \begin{align} \text{Pr}&(i(t)=i|E_i^\theta(t),\mathcal{F}_{t-1})\nonumber \\ &\leq \text{Pr}(i(t)=i, \theta_1(t)<\kappa_1,M_i(t)|E_i^\theta(t),\mathcal{F}_{t-1})\nonumber\\ &= (1-p_{i,t})\text{Pr}(M_i(t)|E_i^\theta(t),\mathcal{F}_{t-1}), \label{eq:lemma1_subopt} \end{align} where the second step follows from the independence of events conditional on the filtration $\mathcal{F}_{t-1}$. Next, we bound the probability of selecting arm $1$. We observe that, conditioned on $M_i(t)$ and $E_i^\theta$, arm $1$ forms a part of the optimal solution at time $t$ along with arm $2$. Further, the probability mass assigned to arm $1$ is $(\theta_{2,t}-\eta)/(\theta_{2,t}-\theta_{1,t})$. For any Thompson samples such that $\theta_2>\kappa_2$ and $\theta_1>\kappa_1$, the probability mass assigned to arm $1$ is at least $(\kappa_2-\eta)/(\kappa_2-\kappa_1)=\epsilon_{1,i}$. Consequently, we have \begin{align} &\text{Pr}\big(i(t)=1|E_i^\theta(t),\mathcal{F}_{t-1}\big) \nonumber \\ &\geq \text{Pr}\big(i(t)=1,M_i(t)|E_i^\theta(t),\mathcal{F}_{t-1}\big) \nonumber \\ &= \text{Pr}\big(M_i(t)|E_i^\theta(t),\mathcal{F}_{t-1}\big)\cdot\text{Pr}\big(i(t)=1|M_i(t),E_i^\theta(t),\mathcal{F}_{t-1}\big) \nonumber \\ &\geq \epsilon_{1,i}\cdot p_{i,t}\cdot\text{Pr}\big(M_i(t)|E_i^\theta(t),\mathcal{F}_{t-1}\big), \label{eq:lemma1_opt} \end{align} Combining~\eqref{eq:lemma1_subopt} and~\eqref{eq:lemma1_opt} we get the desired result. \newpage \section*{Appendix B} Similar to the approach in~\cite{agrawal2013further}, we bound the number of plays of any suboptimal arm in the following manner: \begin{align*} \mathbb{E}\big[k_i(T)\big] =& \sum_{t=1}^T\text{Pr}(i(t)=i) \\ =& \sum_{t=1}^T\text{Pr}(i(t)=i,E_i^\mu(t),E_i^\theta(t)) \\ &+ \sum_{t=1}^T\text{Pr}(i(t)=i,E_i^\mu(t),\overline{E_i^\theta(t)}) \\ &+\sum_{t=1}^T\text{Pr}(i(t)=i,\overline{E_i^\mu(t)}) \\ \end{align*} The last two terms of this expression are upper bounded by (17) and (16) respectively. Then, following the approach in \cite{agrawal2013further}, we bound the first term of the expression above using Lemma 1, where we exploit the fact that the number of plays of arm $i$ are a linear function of the number of playes of arm $1$, \begin{align*} \sum_{t=1}^T&\text{Pr}(i(t)=i,E_i^\mu(t),E_i^\theta(t)) \\ &=\sum_{t=1}^T\mathbb{E}\bigg[\text{Pr}(i(t)=i,E_i^\mu(t),E_i^\theta(t)\big|\mathcal{F}_{t-1})\bigg]\\ &\leq \sum_{t=1}^T\mathbb{E}\bigg[\frac{1-p_{i,t}}{\epsilon_{1,i}\cdot p_{i,t}}\text{Pr}(i(t)=1,E_i^\mu(t),E_i^\theta(t)\big|\mathcal{F}_{t-1})\bigg] \\ &= \sum_{t=1}^T\mathbb{E}\bigg[\mathbb{E}\bigg[\frac{1-p_{i,t}}{\epsilon_{1,i}\cdot p_{i,t}}I(i(t)=1,E_i^\mu(t),E_i^\theta(t)\big)\bigg]\bigg] \\ &\leq\sum_{k=0}^{T-1}\mathbb{E}\bigg[\bigg(\frac{1}{\epsilon_{1,i}\cdot p_{i,\tau_k+1}} - 1\bigg)\sum_{t=\tau_k+1}^{\tau_{k+1}}I(i(t)=1)\bigg] \\ &=\sum_{k=0}^{T-1}\mathbb{E}\bigg[\frac{1}{\epsilon_{1,i}\cdot p_{i,\tau_k+1}} - 1\bigg], \end{align*} where $I$ is the indicator function, and we have used the fact that $\epsilon_{1,i}$ is independent of the history of plays. From (18), we have an upper bound on $\mathbb{E}(\frac{1}{p_{i,\tau_j+1}})$. By collecting the upper bounds from (16), (17), and (18), we directly obtain Lemma 2. \newpage \section*{Appendix C} We present the pseudocode for the LinCon-KL-UCB algorithm in this section. \begin{algorithm} \caption{LinCon-KL-UCB} \label{alg:lin_con_kl_ucb} \begin{algorithmic}[1] \STATE {\bfseries Input:} Reward Values $r_{\{1,\dots,N\}}$, Constraint $\eta$, $c$ \STATE \textbf{Initialize:} $k_{\{1,\dots,N\},0}=0,s_{\{1,\dots,N\},0}=0$. \FOR{ Time index $t=1$ {\bfseries to} $T$ } \IF{ $t<N$ } \STATE $i(t) = t$ \ELSE \FOR{ Arm index $i=1$ {\bfseries to} $N$ } \item $\tilde{\mu}_{i,t} = \max\big\{q\in\Theta:k_id\big(\frac{k_i}{s_i},q\big)\log(t)+c\log\log(t)\big\}$ \ENDFOR \STATE Solve, if feasible, the linear program: \begin{align*} LP(\tilde{\mu}_t):\,\text{maximize}\,\sum_i x_{i,t}\tilde{\mu}_{i,t}r_i \qquad\qquad\qquad\qquad \end{align*} \begin{equation} \qquad\text{ subject to } \begin{cases} \sum_i x_{i,t}\tilde{\mu}_{i,t} \geq \eta\\ \sum_ix_{i,t} = 1\\ x_{i,t} \geq 0\quad \forall\,i\in\{1,\dots,N\} \end{cases}, \label{eq:linconts} \end{equation} \IF{ a (feasible) optimal solution existed } \STATE Sample $i(t)~\sim [x_{1,t},\dots,x_{N,t}]$ \ELSE \STATE Sample $i(t)$ uniformly from $\{1,\dots,N\}$. \ENDIF \ENDIF \STATE \textbf{Observe:} Reward event $c_{i(t)}\in\{0,1\}$. \STATE \textbf{Update:} \\ $\qquad k_{i(t)} = k_{i(t)} + 1$ \\ $\qquad s_{i(t)} = s_{i(t)} + c_{i(t)}$. \ENDFOR \end{algorithmic} \label{alg:linconts} \end{algorithm} \subsection{LinConTS} \begin{algorithm}[tb] \caption{LinConTS} \label{alg:ts_linprog} \begin{algorithmic}[1] \STATE {\bfseries Input:} Reward Values $r_{\{1,\dots,N\}}$, Constraint $\eta$ \STATE \textbf{Initialize:} $\alpha_{\{1,\dots,N\},0}=1, \beta_{\{1\dots N\},0}=1$. \FOR{ Time index $t=1$ {\bfseries to} $T$ } \IF{ $t<N$ } \STATE $i(t) = t$ \ELSE \STATE Sample $\widetilde{\mu}_{i,t}\sim \text{Beta}(\alpha_{i,t-1}, \beta_{i,t-1})$ for each arm $i=1,\dots,N$. \STATE Solve, if feasible, the linear program: \begin{align*} LP(\widetilde{\boldsymbol\mu}_t):\,\text{maximize}\,\sum_i x_{i,t}\widetilde{\mu}_{i,t}r_i \qquad\qquad\qquad\qquad \end{align*} \begin{equation} \qquad\text{ subject to } \begin{cases} \sum_i x_{i,t}\widetilde{\mu}_{i,t} \geq \eta\\ \sum_ix_{i,t} = 1\\ x_{i,t} \geq 0 \forall\,i\in\{1,\dots,N\} \end{cases}, \label{eq:linconts} \end{equation} \IF{ a (feasible) optimal solution exists } \STATE Sample $i(t)~\sim [x_{1,t},\dots,x_{N,t}]$ \ELSE \STATE Sample $i(t)$ uniformly from $\{1,\dots,N\}$. \ENDIF \ENDIF \STATE \textbf{Observe:} Reward event $c_{i(t),t}\in\{0,1\}$. \STATE \textbf{Update:} \\ $\qquad \alpha_{i(t),t} = \alpha_{i(t),t-1} + c_{i(t),t}$ \\ $\qquad \beta_{i(t),t} = \beta_{i(t),t-1} + (1-c_{i(t),t})$. \ENDFOR \end{algorithmic} \label{alg:linconts} \end{algorithm} TS assigns prior distributions over the unknown MAB parameters. Subsequently for the played arm in evey round, the arm posterior is updated using the observed reward. For the problem studied in this paper, the unknown parameters are the reward event means $\mu_1,\dots,\mu_N$. Since these parameters are Bernoulli-distributed, a suitable choice of prior is the Beta distribution~\cite{russo2018tutorial}. The LinConTS algorithm is described in Alg.~\ref{alg:linconts}. At the beginning of the experiment, the reward values $r_i,\,i\in\{1,\dots,N\}$ and the constraint $\eta$ are provided. For each arm, LinConTS assigns independent uniform priors distributed as $\text{Beta}(\alpha_{i,0}=1, \beta_{i,0}=1)$. At every time step $t=1,\dots,T$, LinConTS obtains \emph{Thompson samples} $\widetilde{\mu}_{i,t}\sim \text{Beta}(\alpha_{i,t-1}, \beta_{i,t-1})$ and subsequently solves a LP parameterized by these samples to obtain the instantaneous, probabilistic arm selection vector $x_t=[x_{1,t},\dots,x_{N,t}]$. This vector is sampled to obtain the playing arm, $i(t)\sim x_t$, if the LP is feasible. Subsequently, the reward event $c_{i(t),t}\sim \text{Bern}(\mu_{i(t)})$ is observed and the reward $c_{i(t)}r_{i(t)}$ is collected. The parameter distribution for the played arm is updated according to the rule $\text{Beta}(\alpha_{i(t),t-1}, \beta_{i(t),t-1})\leftarrow (c_{i(t),t}, 1-c_{i(t),t})$. \subsection{Regret and Violation Upper Bounds} The theoretical analysis of TS is challenging, and as such only an empirical evaluation of its performance was available until recently~\cite{chapelle2011empirical}. The chief reason for TS' theoretical intractability is that, owing to its randomized nature, novel techniques are required to bound the number of draws for suboptimal arms, which were first introduced in~\cite{agrawal2012analysis} and extended in~\cite{kaufmann2012thompson, agrawal2013further} . At a high level, these techniques compare the Thompson samples for each arm with carefully selected thresholds related to empirical estimates of the arm parameters and their true values. Subsequently, by using known bounds on the sums of Bernoulli random variables, these techniques bound the expected number of times that any suboptimal arm is played. In case of LinConTS, the selected arm in round $t$ depends on the solution of LP($\widetilde{\boldsymbol\mu}_t$). Therefore, to bound the probability of selecting a suboptimal arm, we need to analyze the LP in~\eqref{eq:linear_prog} with perturbed reward event means. We address this challenge by formulating the Lagrangian dual of the LP that can be solved to obtain specific thresholds for each suboptimal arm, which, when breached under certain well-specified conditions, lead to the suboptimal arm being selected with a nonzero probability. We use these thresholds in combination with the proof technique of~\cite{agrawal2013further} to show that for the suboptimal arms, the expected number of plays number is bounded by $O(\log T)$. A corollary to this result is that the optimal arms are selected at a linear rate. Consequently, the Thompson samples for the optimal arms converge to their true means polynomially fast. As a consequence, the optimal arms are selected with a frequency that does not deviate from the stationary optimal policy by more than $O(\sqrt{T})$. Under the assumption of no degenerate cases and that the reward-maximizing arm does not simultaneously satisfy the constraint, exactly two arms support~\eqref{eq:linear_prog}. This well-known result for LPs satisfies the following intuition: the optimal solution to~\eqref{eq:linear_prog} frequently selects a high-reward-value arm, which comes at the cost of frequent failures (i.e., no-reward events). Hence, to satisfy the constraint, the optimal solution sometimes picks another, low-reward-value arm that has a high success probability. Without loss of generality, we denote the optimal arm indices with $1$ and $2$ respectively with parameters that satisfy $0<\mu_1<\eta<\mu_2\leq 1$ and $r_1\mu_1>r_2\mu_2$. Subsequently, we obtain the following regret and violation bounds: \begin{theorem} The expected regret for LinConTS, \begin{align*} &\mathbb{E}\big[\mathcal{R}(T)\big]\\ &\leq\bigg[\sum_{\substack{i\neq\{1, 2\}}}\frac{(1+\gamma)^2}{d(\mu_i,\xi_i)}\Delta_i^+\bigg]\log T+\Delta^+_{\max}\cdot 18\sqrt{2T\log 2}+O(\frac{N}{\gamma^2}), \end{align*} where $\xi_i=\frac{(r_1-r_2)\mu_1\mu_2}{(r_i - r_2)\mu_2-(r_i-r_1)\mu_1}>\mu_i$, $\gamma\in(0,1]$ $d(\mu_i,\xi_i)=\mu_i\log\frac{\mu_i}{\xi_i}+(1-\mu_i)\log\frac{1-\mu_i}{1-\xi_i}$, $\Delta_i^+=\max\{0,r^*-\mu_ir_i\}$, and $\Delta^+_{\max}=\max_{i\in [N]}\Delta^+_i$. \end{theorem} \begin{theorem} The expected violation for LinConTS, \begin{align} &\mathbb{E}\big[\mathcal{V}(T)\big]\nonumber\\ &\leq\bigg[\sum_{i\neq\{1, 2\}}\frac{(1+\gamma)^2}{d(\mu_i,\xi_i)}\delta_i^+\bigg]\log T+\delta^+_{\max}\cdot 18\sqrt{2T\log 2}+O(\frac{N}{\gamma^2}),\nonumber \end{align} where $\delta_i^+=\max\{0,\eta-\mu_i\}$ and $\delta^+_{\max}=\max_{i\in [N]}\delta^+_i$ \end{theorem} \subsection{LP Perturbation Analysis} \label{sec:lp_pertub} The Lagrangian dual $\mathcal{L}(\boldsymbol{x},\lambda,\nu,\boldsymbol\psi)$ of the primal LP in~(\ref{eq:linear_prog}) can be formulated as \begin{align} \mathcal{L}(\boldsymbol{x},\lambda,\nu,\boldsymbol\psi) = &-\sum_ix_i\mu_ir_i \nonumber \\ &+ \lambda\bigg(\eta - \sum_ix_i\mu_i\bigg) \nonumber \\ &+\nu\bigg(\sum_ix_i - 1\bigg) \nonumber \\ &-\sum_i\psi_ix_i, \nonumber \\ = \lambda\eta-\nu &- \sum_i(r_i\mu_i+\lambda\mu_i-\nu+\psi_i)x_i, \label{eq:dual_problem} \end{align} where $\boldsymbol{x}\in\mathbf{R}^N$ is the optimization variable, and $\lambda\in\mathbf{R}$, $\nu\in\mathbf{R}$, and $\boldsymbol\psi\in\mathbf{R}^N$ are the Langrange dual variables. The corresponding dual function \begin{eqnarray} g(\lambda,\nu,\boldsymbol\psi) =& \inf_x\,\mathcal{L}(\boldsymbol{x},\lambda,\nu,\boldsymbol\psi)\qquad\qquad\qquad\qquad\qquad \\ =& \begin{cases} \lambda\eta-\nu\quad r_i\mu_i+\lambda\mu_i-\nu+\psi_i = 0,\\ \qquad\qquad\lambda \geq 0, \\ \qquad\qquad\psi_i \geq 0.\\ -\infty\quad\quad\text{otherwise.} \end{cases} \label{eq:dual_fn} \end{eqnarray} We assume that a strictly feasible solution exists to the $LP(\boldsymbol\mu)$, otherwise there can be no policy that achieves the objective. Then, strong duality holds from Slater's condition and the primal optimal is equal to the dual optimal, i.e., there no duality gap. Hence, from the KKT optimality conditions, \begin{align} \lambda^*\big(\eta - \sum_ix_i^*\mu_i\big)&=0 \\ \nu^*\big(\sum_ix_i^* - 1\big)&=0,\,\text{and}\\ \sum_i\psi_i^*x_i^*&=0, \end{align} where $\lambda^*,\nu^*,\boldsymbol\psi^*$ are the optimal duals. Since $\psi_i^*\geq 0,x_i^*\geq 0$, each term of $\sum_i\psi_i^*x_i^*$ is non-negative. Consequently for $\sum_i\psi_i^*x_i^*=0$ to hold, $x_i^*>0$ implies that $\psi_i^*=0$ and $x_i^*>0$ implies that $\psi_i^*=0$. Under the assumption of no degenerate cases, strict complementarity holds, i.e., either $x_i^*>0$ or $\psi_i^*>0$~\cite[Chap.~5]{boyd2004convex}. \emph{Optimal arms:} The arms for which $\psi_i^*=0$ are assigned positive probabilities $x_i^*>0$ by the solution to $LP(\boldsymbol\mu)$. We can then obtain the optimal dual variables by solving the system of linear equations \begin{align*} r_i\mu_i +\lambda^*\mu_i-\nu^* &= 0,\,i\in\{j:\psi_j^*=0,\,j\in\{1,\dots,N\}\}, \end{align*} which gives $ \lambda^* = \frac{r_1\mu_1-r_2\mu_2}{\mu_2-\mu_1} \geq 0$ and $ \nu^* = \frac{(r_1-r_2)\mu_1\mu_2}{\mu_2-\mu_1}$. Note that $\lambda^*$ is the slope of the hyperplane that optimizes $LP(\boldsymbol\mu)$. Further, by solving $\sum_{i=1,2}p_i^*\mu_i=\eta$, we get the optimal selection probabilities $x_1^*=(\mu_2-\eta)/(\mu_2-\mu_1)$ and $x_2^*=(\eta-\mu_1)/(\mu_2-\mu_1)$. \emph{Suboptimal arms and complementary slackness:} In contrast to the optimal arms, the arms where $x_i^*=0,\,\psi_i^*>0$ constitute suboptimal arms that are assigned zero probability mass by the optimal solution. For these arms, the constraints are \emph{slack} so that sufficiently small perturbations of their parameters does not alter the optimal solution to $LP(\boldsymbol\mu)$. We now quantify the slack for each suboptimal arm $i\not\in\{1,2\}$. For this, we observe that the arms stay suboptimal as long as $\psi_i^*>0$. Rearranging (\ref{eq:dual_fn}) to obtain $r_i\mu_i +\lambda^*\mu_i-\nu^* =-\psi_i^* < 0$, we get $\mu_i<\frac{\nu^*}{r_i+\lambda^*}$. Hence, we define \begin{align} \xi_i := \frac{\nu^*}{r_i+\lambda^*}=\frac{(r_1-r_2)\mu_1\mu_2}{(r_i - r_2)\mu_2-(r_i-r_1)\mu_1}>\mu_i. \label{eq:slack} \end{align} The value $\xi_i-\mu_i > 0$ is the \emph{complementary slackness} for arm $i$. As long as any (perturbed) mean value, $\mu_i'$, for arm $i$ satisfies $\mu_i' <\xi_i$ the arm $i$ stays suboptimal, i.e, the arm is assigned szero selection probability mass. \subsection{Arm Selection Bounds} To bound the regret and violation for LinConTS, we first bound $\mathbb{E}\big[k_i(T+1)\big]$, the expected number of times any suboptimal arm $i\not\in\{1,2\}$ is played until time $T+1$. Our proof technique is inspired by~\cite{agrawal2013further}: First, we show that the probability of playing a sub-optimal arm is a linear function of the probability of playing one of the optimal arms. In order to bound the number of plays of any suboptimal arm, \cite{agrawal2013further} carefully selected \emph{threshold} values that were used to compare the sampled suboptimal and optimal arm means. However, for the constrained problem studied here, the threshold depends on the slack $\xi_i$ for the $i^\text{th}$ suboptimal arm, and the comparison between sampled arm means relies on the LP perturbation analysis above. Next, we show that the coefficient of this linear function decreases exponentially with successive plays of the arm. For this, we use the concentration results from \cite{agrawal2013further} to upper bound the number of plays for each suboptimal arm. We begin by defining the following: \textbf{Definition 1:} The number of successes observed for arm $i=1,\dots,N$ until time step $t-1$ is denoted by $S_i(t)$. The empirical mean at time $t$ is $\hat{\mu}_i(t)=\frac{S_i(t)}{k_i(t)}$, with $\hat{\mu}_i(t)=1$ when $k_i(t)=0$. \textbf{Definition 2:} The history of plays until time $t-1$ are denoted by the \emph{filtration} $\mathcal{F}_{t-1}$, i.e., \begin{align*} \mathcal{F}_{t-1} = \{i(w), c_{i(w),w},\,w=1,\dots,t-1\}. \end{align*} \textbf{Definition 3:} For each suboptimal arm $i\not\in\{1,2\}$, we choose two thresholds $y_i$ and $z_i$ such that $\mu_i<y_i<z_i<\xi_i$, which are set at appropriate points of the proof. Further, we define $L_i(T)=\frac{\log T}{d(y_i,z_i)}$. \textbf{Definition 4:} We define the variable, $\kappa_1,\dots,\kappa_N$ such that $$ \frac{\kappa_jr_j-z_ir_i}{\kappa_j-z_i}=\lambda^*, $$ where $\kappa_i := z_i$. The hyperplane supported by any two points $(z_i,z_ir_i)$ and $(\kappa_j,\kappa_jr_j),\,j\neq i$ runs parallel to the optimal hyperplane for $LP(\boldsymbol\mu)$. \textbf{Definition 5:} We define the variable $$ \epsilon_{1,i} = \frac{\kappa_2-\eta}{\kappa_2-\kappa_1}>x_{1,t}>0, $$ which lower bounds the selection probability mass assigned to arm $1$, $x_{1,t}$, under certain conditions described later in the proof. \textbf{Definition 6:} We define two events: $E_i^\mu(t):\{\hat{\mu}_i(t)\leq y_i\}$ and $E_i^\theta(t):\{\theta_{i,t}\leq z_i\}$, where $\theta_{i,t}:=\widetilde{\mu}_{i,t}$ denotes the Thompson sample at time $t$. Intuitively, $E_i^\mu(t)$ and $E_i^\theta(t)$ denote the events that the empirical and sampled means for arm $i$ at time $t$ do not exceed the true arm mean by a large amount. \textbf{Definition 7:} We define the probability \begin{align} p_{i,t} &= \text{Pr}\big(\{\theta_{1,t}>\kappa_1\}\big|\mathcal{F}_{t-1}\big) \label{eq:arm_1_thresh} \end{align} \setcounter{theorem}{0} Next, we prove the following lemma that establishes the relationship between the number of plays of any suboptimal arm $i\not\in{1,2}$ and the optimal arm $i= 1$. \begin{lemma} For all $t\in\{1,\dots,T\}$, and $i\not\in\{1,2\}$, \begin{align} \text{Pr}&\big(i(t)=i,E_i^\mu(t), E_i^\theta(t)|\mathcal{F}_{t-1}\big)\nonumber \\ &\leq \frac{1}{\epsilon_{1,i}}\cdot\frac{1-p_{i,t}}{p_ {i,t}}\cdot\text{Pr}\big(i(t)=1,E_i^\mu(t), E_i^\theta(t)|\mathcal{F}_{t-1}\big). \label{eq:lemma1} \end{align} \end{lemma} \begin{proof} Similar to~\cite[Lemma 1]{agrawal2013further}, we note that $E_i^\mu(t)$ is determined by $\mathcal{F}_{t-1}$. Further, when $E_i^\mu(t)$ is false, the left hand side of~\eqref{eq:lemma1} is zero and the inequality is trivially satisfied. Hence, we assume that $\mathcal{F}_{t-1}$ is such that $E_i^\mu(t)$ is true . Subsequently, to prove~\eqref{eq:lemma1}, we show that under a suitably chosen set of conditions $M_i(t)$ that hold with a non-zero probability, the following relationships also hold: \begin{align} \text{Pr}\big(i(t)=i|E_i^\theta(t),\mathcal{F}_{t-1}\big)&\leq (1-p_{i,t})\text{Pr}\big(M_i(t)|E_i^\theta(t),\mathcal{F}_{t-1}\big),\nonumber \\ \text{Pr}\big(i(t)=1|E_i^\theta(t),\mathcal{F}_{t-1}\big) &\geq (\epsilon_{1,i}\cdot p_{i,t})\text{Pr}\big(M_i(t)|E_i^\theta(t),\mathcal{F}_{t-1}\big), \nonumber \end{align} which immediately gives the Lemma above. The proof details are provided in Appendix A. \end{proof} Subsequently, to bound the expected number of plays for any suboptimal arm $i$, we use the following three results available in the literature:~\cite[Lemma 2]{agrawal2013further} \begin{align} &\sum_{t=1}^T\text{Pr}(i(t)=i,\overline{E_i^\mu(t)})\leq \frac{1}{d(y_i,\mu_i)} + 1, \label{eq:agr_lemma2} \end{align} which relies on Chernoff-Hoeffding bounds on the concentration of the empirical mean around the true mean, ~\cite[Lemma 3]{agrawal2013further} \begin{align} &\sum_{t=1}^T\text{Pr}(i(t)=i,E_i^\mu(t),\overline{E_i^\theta(t)})\leq L_i(t) + 1, \label{eq:agr_lemma3} \end{align} which is based on the fact that after the arm has played a sufficient number of times, $L_i(t)$, the Thompson sample will be close to its mean value, and ~\cite[Lemma 4]{agrawal2013further} \begin{eqnarray} \mathbb{E}\bigg[\frac{1}{p_{i,\tau_j+1}}\bigg]\leq \begin{cases} 1+\frac{3}{\Delta_i'} \qquad\qquad\qquad\quad j<\frac{8}{\Delta'_i},\\ 1+O\big(e^{-\frac{{\Delta'}_i^2j}{2}}\\ \quad\quad+\frac{1}{(j+1){\Delta'}_i^2}e^{-D_ij}\quad j>\frac{8}{{\Delta'}_i}\\ \quad\quad+\frac{1}{e^{{\Delta'}_i^2j/4}-1}\big), \end{cases}, \label{eq:agr_lemma4} \end{eqnarray} where $\tau_j$ denotes the time step for the $j^\text{th}$ trial of arm $1$, ${\Delta'}_i=\mu_1-\kappa_1$ and $D_i=z_i\log\frac{z_i}{\mu_1}+(1-z_i)\log\frac{1-z_i}{1-\mu_1}$. This last result uses novel algebraic analysis developed from the concentration of Binomial sums. Based on the above, we obtain the following bound on the expected number of plays of the suboptimal arm $i$ until time $T$: \begin{lemma} The expected number of plays for any stationary suboptimal arm, $i\in\{1,\dots,K\}\setminus \{1,2\}$, is upper bounded by \begin{align} \mathbb{E}\big[k_i(T)\big]\leq& 2 + L_i(T) + \frac{1}{d(y_i,\xi_i)} + \frac{24}{\epsilon_{1,i}{\Delta'_i}^2} \nonumber\\ &+ \frac{1}{\epsilon_{i,i}}\sum_{j=0}^{T-1} O\bigg(e^{-\frac{{\Delta'}_i^2j}{2}} +\frac{1}{(j+1){\Delta'}_i^2}e^{-D_ij}\nonumber\\ &\qquad\qquad\qquad+\frac{1}{e^{{\Delta'}_i^2j/4}-1}\bigg) . \end{align} \end{lemma} \begin{proof} This proof essentially sums over the expressions obtained in~\eqref{eq:agr_lemma2},~\eqref{eq:agr_lemma3}, and~\eqref{eq:agr_lemma4} until time $T$. The details are provided in Appendix B. \end{proof} \begin{lemma} For the stationary optimal arms $i\in\{1,2\}$, \begin{align} \sum_{i=1,2}\Delta_i\mathbb{E}\big[k_i(T)\big]&\leq \Delta^+_{\max}\cdot 18\sqrt{2T\log 2}, \nonumber\\ \sum_{i=1,2}(\eta-\mu_i)\mathbb{E}\big[k_i(T)\big]&\leq \delta^+_{\max}\cdot 18\sqrt{2T\log 2}, \label{eq:reg_vio_optimal} \end{align} where $\Delta_i=r^*-\mu_ir_i$, $\Delta^+_{\max}=\max_{i\in [N]}\Delta^+_i$ and $\delta^+_{\max}=\max_{i\in [N]}\delta^+_i$. \end{lemma} \begin{proof} From Lemma 2, the rate of playing any suboptimal is a logarithmic function of $T$. Hence, the set of optimal arms is played at a linear rate. Viewing the play of optimal arms as a two-armed bandit, we can use existing results for constrained TS to bound the regret and violation contribution for the rounds when only the optimal arms are assigned nonzero arm selection probabilities by $LP(\widetilde{\boldsymbol{\mu}}_t)$. First, we decompose the regret and violation expressions separately using the decomposition in~\cite[EC.4]{ferreira2018online} that relies on a frequentist upper and lower bounds that holds with high probability for every $t\in[T]$. Subsequently, we apply~\cite[Lemma EC.2]{ferreira2018online}, which provides an upper bound on the expected regret and violation with respect to the frequentist upper and lower bounds. This directly gives us the bounds in~\eqref{eq:reg_vio_optimal} where we set $K=2$ since only the rounds where the optimal arms are played are taken into account. \end{proof} \subsection{Proof of Regret and Violation Bounds} For some $\gamma\in(0,1]$ we choose the thresholds $y_i\in(\mu_i,\xi_i)$ and $z_i\in(y_i,\xi_i)$ such that $d(y_i,\xi_i)=d(\mu_i,\xi_i)/(1+\gamma)$ and $d(y_i,z_i)=d(y_i,\xi_i)/(1+\gamma)=d(\mu_i,\xi_i)/(1+\gamma)^2$. This leads to \begin{align*} L_i(T) = \frac{\log T}{d(y_i,z_i)} = (1+\gamma)^2\frac{\log T}{d(\mu_i,\xi_i)}. \end{align*} Following the ideas in~\cite{agrawal2013further}, we obtain $y_i-\mu_i\geq\frac{\gamma}{1+\gamma}\cdot d(\mu_i,\xi)/\log{\frac{\xi_i(1-\mu_i)}{\mu_i(1-\xi_i)}}$, which gives $\frac{1}{d(y_i,\mu_i)}\leq \frac{2}{(y_i-\mu_i)^2}=O(1/\gamma^2)$. \textbf{Proof of regret bound:} From Lemma 2 and Lemma 3, we obtain \begin{align} &\mathbb{E}\big[\mathcal{R}(T)\big]=\bigg[\sum_i\Delta_i\mathbb{E}\big[k_i(T)\big]\bigg]_+\nonumber\\ &\leq\bigg[\sum_{i\neq\{1,2\}}\Delta_i\mathbb{E}\big[k_i(T)\big]\bigg]_+ + \bigg[\sum_{i=1,2}\Delta_i\mathbb{E}\big[k_i(T)\big]\bigg]_+\nonumber\\ &\leq \sum_{i\neq\{1,2\}}\Delta_i^+\mathbb{E}\big[k_i(T)\big] + \Delta^+_{\max}\cdot 18\sqrt{2T\log 2}\nonumber\\ &\leq \sum_{i\neq\{1, 2\}}(1+\gamma)^2\frac{\log T}{d(\mu_i,\xi_i)}\Delta_i^++O(\frac{N}{\gamma^2})\nonumber\\ &\qquad+\Delta^+_{\max}\cdot 18\sqrt{2T\log 2},\nonumber \end{align} where the first and second inequalities use $[a+b]_+\leq [a]_++[b]_+$. This completes the regret bound. \textbf{Proof of violation bound:} From Lemma 2 and Lemma 3, we obtain \begin{align} &\mathbb{E}\big[\mathcal{V}(T)= \bigg[\sum_i(\eta - \mu_i)\mathbb{E}\big[k_i(T)\big]\bigg]_+\nonumber\\ &\leq \sum_{i\neq\{1, 2\}}\mathbb{E}\big[k_i(T)\big]\big[(\eta - \mu_i)\big]_++ O(\log T)\nonumber\\ &\leq\sum_{i\neq\{1, 2\}}\frac{(1+\gamma)^2\log T}{d(\mu_i,\xi_i)}\delta_i^++O(\frac{N}{\gamma^2})+\delta^+_{\max}\cdot 18\sqrt{2T\log 2}\nonumber \\ &=\bigg[\sum_{i\neq\{1, 2\}}\frac{(1+\gamma)^2}{d(\mu_i,\xi_i)}\delta_i^+\bigg]\log T+O(\frac{N}{\gamma^2})\nonumber\\ &\qquad+\delta^+_{\max}\cdot 18\sqrt{2T\log 2},\nonumber \end{align} where the first and second inequalities use $[a+b]_+\leq [a]_++[b]_+$. This completes the violation bound. \section{Conclusions and Further Work} For constrained bandit problems, LP subroutines enable powerful sequential arm selection techniques. Combined with an underlying Thompson Sampling approach, these techniques promise efficient and robust solutions that are optimal in terms of their learning rate. We have addressed the MAB problem of maximizing the cumulative reward when the reward event probability is constrained above a fixed threshold in every round. For this problem, we described LinConTS, which incorporates a LP subroutine in every step of the Thompson Sampling heuristic. We have provided the first instance-dependent finite-time analysis our algorithm. Through numerical results for two real-world datasets, we have showed that LinConTS outperforms an optimal UCB-based algorithm in terms of the regret and violation metrics. We have considered a specific type of linear constraint in this paper. However, the proof technique developed in this paper can inspire solutions to other constrained MAB problems, for example to problems that deal with more general constraints. Further, it could be useful to develop a composite notion of regret and develop optimal lower bounds, for example by leveraging the recent results in~\cite{garivier2019explore}.
{'timestamp': '2020-05-14T02:00:52', 'yymm': '2004', 'arxiv_id': '2004.09258', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09258'}
arxiv
\section{Introduction}\label{S:INTRO} The estimation of weight and bias in neural networks is currently dominated by approaches employing point estimates when learning model parameters using gradient backpropagation \cite{rumelhart1986learning}. Although these approaches allow for the state-of-the-art performance in many domains of applications, it is recognized that they fall short in situations where, for instance, datasets are small, when the task requires quantifying the uncertainty about the prediction made, or for continual learning \cite{ghahramani2015probabilistic,kendall2017uncertainties,farquhar2019unifying}. In such situations, the Bayesian approach for infering the parameters'\! posterior probability, is known to be theoretically better suited than a point estimate. This is in theory because applying exact Bayesian inference on large neural networks has been considered to be intractable \cite{goodfellow2016deep}. Many researchers have already proposed approximate inference methods for \emph{Bayesian Neural Networks} (BNN). Early on, it was proposed to employ the \emph{Extended} and \emph{Unscented Kalman Filter} to estimate the Gaussian posterior for feedforward neural networks \cite{NIPS1988_101, puskorius1991decoupled,wan2000unscented}. More recently, this Gaussian framework was extended with the \emph{Cubature filter} \cite{arasaratnam2008nonlinear}, which, like the extended and unscented methods, is limited by the computational complexity of $\mathcal{O}(n^3)$, where $n$ is the number of parameters. In another approach, \citeauthor{mackay1992practical} (\citeyear{mackay1992practical}) employed the \emph{Laplace approximation} to describe the posterior covariance of parameters. Later, \citeauthor{neal1995Bayesian} (\citeyear{neal1995Bayesian}) explored the potential of BNN using \emph{sampling methods}. In parallel, several researchers have applied \emph{variational inference} for estimating the posterior distribution of neural networks'\! parameters \cite{hinton1993keeping,barber1998ensemble}. The development of moment matching and variational approaches for BNN is still nowadays an active research area \cite{hernandez2015probabilistic,blundell2015weight,louizos2016structured,Osawa2019PracticalDL}. Recently, the technique of using Dropout as a Bayesian approximation has received a lot of attention in the community \cite{gal2016dropout}. For all the recent methods that are either based on variational approaches or dropout, the inference of parameters is still treated as an optimization problem relying on gradient backpropagation. In this paper, we propose a \emph{tractable approximate Gaussian inference} method (TAGI) for Bayesian neural networks. The approach, which does not rely on backpropagation, allows for an analytical end-to-end treatment of uncertainty for the weight and bias parameters, as well as in observed covariates and system responses. The paper is organized as follows: Section \ref{S:GCBNN} first introduces the \emph{Gaussian multiplication approximation} (GMA) for propagating uncertainty in feedforward neural networks, and second, it presents how to perform tractable inference for the posterior mean vector and diagonal covariance of weight and bias parameters. Section \ref{S:experiments} validates the performance of the approach on benchmark regression problems and on the MNIST classification problem. \section{Gaussian Approximation for BNN}\label{S:GCBNN} \subsection{Gaussian Feedforward Neural Network}\label{SS:FFNN} Figure \ref{FIG:FNN} details the nomenclature for the feedforward neural network (FNN) employed in this paper. Let us consider a vector of input covariates $\bm{X}=[X_{1}~X_{2}~\ldots~X_{\mathtt{X}}]^{\intercal}:\bm{x}\in\mathbb{R}^{{\mathtt{X}}}$ that are described by random variables in order to take into account errors potentially arising from observation uncertainties, and then suppose we have a vector of $\mathtt{Y}$ observed system responses $\bm{Y}=[Y_{1}~Y_{2}~\ldots~Y_{\mathtt{Y}}]^{\intercal}:\bm{y}\in\mathbb{R}^{{\mathtt{Y}}}$. The relations between observed system responses and its covariates are described by the observation model \begin{equation} \bm{y}=\bm{z}^{(\mathtt{O})}+\bm{v}, \label{EQ:obs} \end{equation} where the vector of hidden variables $\bm{z}^{(\mathtt{O})}$ corresponds to the output layer of a neural network on which observation errors $\bm{v}:\bm{V}\sim\mathcal{N}(\bm{v};\mathbf{0},\mathbf{\Sigma}_{\bm{V}})$ are added. In common cases, $\mathbf{\Sigma}_{\bm{V}}$ is a diagonal covariance matrix assuming that observation errors are independent from each other. We can model the relations between covariates $\bm{x}$ and output hidden variables $\bm{z}^{(\mathtt{O})}$ using a feedforward neural network consisting of $\mathtt{L}$ hidden layers each having $\mathtt{A}$ activation units $a^{(j)}_{i}$ and hidden variables $z^{(j)}_{i}$, $\forall i=\{1,2,\cdots,\mathtt{A}\}$, where an activation unit $a^{(j)}_{i}$ is a non-linear transformation of its associated hidden variable, $a_{i}^{(j)}=\sigma(z_{i}^{(j)}).$ \begin{figure}[t!] \hspace{-6mm}\subfloat[][Expanded representation]{\input{FeedForward_NN.tex}} \hspace{-6mm}\subfloat[][Compact representation where $\bm{\theta}=\{\bm{w},\bm{b}\}$]{\input{FeedForward_NN_compact.tex}} \caption{Expanded and compact representations of the variable nomenclature associated with feedforward neural networks.} \label{FIG:FNN} \end{figure We go from the input layer containing the covariates $\bm{x}$, to the $i^{\text{th}}$ hidden variable on the first hidden layer, using an affine function of $\bm{x}$ so that \begin{equation} z_{i}^{(1)}=w_{i,1}^{(0)}x_{1}+w_{i,2}^{(0)}x_{2}+\cdots+w_{i,\mathtt{X}}^{(0)}x_{\mathtt{X}}+b^{(0)}_{i}. \label{E:input_layer} \end{equation} Equation \ref{E:input_layer} involves the product of weights $w_{i,j}^{(0)}$ and covariates $x_{j}$ with an additive bias term $b^{(0)}_{i}$. In the context of a neural network, the process of learning consists in estimating these weights and bias. Here we consider that weights and bias parameters are described by random variables so that our joint prior for $\{\bm{X},\bm{W}^{(0)},\bm{B}^{(0)}\}$ is a multivariate Gaussian. In Equation \ref{E:input_layer}, we note that the product of Gaussian random variables is not Gaussian. Despite this, we propose to employ moment generating functions in order to compute analytically its expected value, its variance, as well as the covariance between the product of Gaussian random variables and any other Gaussian random variable. For instance, let $\bm{X}=[X_1~\ldots~X_4]^{\intercal}\sim\mathcal{N}(\bm{x};\bm{\mu},\mathbf{\Sigma})$ be a generic vector of Gaussian random variables, where $\bm{\mu}$ is the mean vector and $\mathbf{\Sigma}$ is the covariance matrix, then the following statements are held, \begin{eqnarray} \mathbb{E}[X_1X_2]\!\!\!\!\!&=&\!\!\!\!\!\mu_1\mu_2+\text{cov}(X_1,X_2), \label{eq1}\\[4pt] \text{cov}(X_3,X_1X_2)\!\!\!\!\!&=&\!\!\!\!\!\text{cov}(X_1,\!X_3)\mu_2\!+\!\text{cov}(X_2,\!X_3)\mu_1 \label{eq2},\\[4pt] \text{cov}(X_1X_2,X_3X_4)\!\!\!\!\!&=&\!\!\!\!\!\text{cov}(X_1,X_3)\text{cov}(X_2,X_4) \label{eq3} \\[2pt] \!\!\!\!\!&&\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! +\text{cov}(X_1,X_4)\text{cov}(X_2,X_3)\nonumber \\[2pt] \!\!\!\!\!&&\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!+\text{cov}(X_1,X_3)\mu_2\mu_4+\text{cov}(X_1,X_4)\mu_2\mu_3\nonumber \\ \!\!\!\!\!&&\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!+\text{cov}(X_2,X_3)\mu_1\mu_4+\text{cov}(X_2,X_4)\mu_1\mu_3, \nonumber\\[4pt] \text{var}(X_1X_2)\!\!\!&=&\!\!\! \sigma_{1}^{2}\sigma_{2}^{2}+\text{cov}(X_1,X_2)^{2}\label{eq4}\\ \!\!\!\!\!&&\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!+2\text{cov}(X_1,X_2)\mu_{1}\mu_{2}+\sigma_{1}^{2}\mu_{2}^{2}+\sigma_{2}^{2}\mu_{1}^{2}. \nonumber \end{eqnarray} The development of statements (\ref{eq1}-\ref{eq4}) is presented in the Appendix \ref{Appendix:A}. In this paper, we define the \emph{Gaussian multiplication approximation} as the approximation of the probability density function (PDF) for any product term $X_{i}X_{j}$ by a Gaussian whose first two moments are defined by Equations (\ref{eq1}-\ref{eq4}). With this approximation, we can now employ $X_{i}X_{j}$ along with the random state vector ${\bm{X}}$ in affine functions. It allows propagating the uncertainty from the input covariates and prior knowledge on weight and bias parameter through a FNN. Figure \ref{FIG:GMA_CLT}a illustrates the passage from the activation units $\bm{A}^{(j)}$, to a subsequent hidden unit $\bm{Z}^{(j+1)}_i$. Figure \ref{FIG:GMA_CLT}b-d compare the true theoretical PDF with those obtained using the GMA for different number of activation unit $\mathtt{A}$, under the assumption that both $A^{(j)}_k\sim\mathcal{N}(a^{(j)}_k;\mu,\sigma^2)$, $W^{(j)}_{i,k}\sim\mathcal{N}(w^{(j)}_{i,k};\mu,\sigma^2)$ and $b^{(j)}_i=0$. This shows that even if the GMA is a crude approximation for the Chi-square PDF resulting from the product of two Gaussians, when several of these product terms are added, the result quickly tends to a Gaussian PDF as expected from the central limit theorem. \begin{figure}[htbp] \subfloat[][$\bm{a}^{(j)}\to{z}^{(j+1)}_1$]{ \raisebox{4mm}{\input{FeedForward_NN_layer_GMA.tex}}}~ \subfloat[][$\mathtt{A}=1$]{\includegraphics[width=40mm]{GMA.pdf}}\\ \subfloat[][$\mathtt{A}=5$]{\includegraphics[width=40mm]{GMA_CLT.pdf}}~ \subfloat[][$\mathtt{A}=10$]{\includegraphics[width=40mm]{GMA_CLT_10.pdf}} \caption{Illustration of the effect of the GMA on the PDF of a hidden unit ${Z}^{(j+1)}_i$ as a function of the number of activation units per layer $\mathtt{A}$. The blue curve represents the true PDF and the red one, the PDF resulting from the GMA approximation.} \label{FIG:GMA_CLT} \end{figure} The passage from the hidden variables $\bm{Z}$, to their corresponding activation units $\bm{A}$ cannot be done analytically using non-linear activation functions. In order to work around this difficulty, we propose to employ functions that are linearized at $\mathbb{E}[\bm{Z}]=\bm{\mu_Z}$. \emph{Linearized activation functions} $\tilde{\sigma}(\cdot)$ allow calculating analytically the expected vector $\mathbb{E}[\bm{A}]$, the covariance $\text{cov}(\bm{A})$, as well as the covariance between activation units and the weight and bias $\text{cov}(\bm{A},\bm{\theta})$, where $\bm{\theta}=\{\bm{W},\bm{B}\}$. Figure \ref{FIG:LACT} presents an example for the linearization of a softplus activation function. Note that a linearized activation function is not equivalent to having a linear activation function because for each instance of input covariates $\bm{x}_i$, the linearization is done at a different value $\mu_z$ which maintains the non-linear dependency between $\bm{x}_i$ and the output $\bm{y}_i$. It is known that this linearization procedure is an approximation of the \emph{change of variable rule} that would be required to obtain true theoretical PDF for $f(a)$. It is also known that more advanced sampling-based approches exist for propagating uncertainty through non-linear function , e.g. \cite{arasaratnam2009cubature}. Nevertheless, we choose to employ the linearization procedure because of its minimal computational cost which still allows, as it will be shown in \S\ref{S:experiments}, to match the state-of-the-art performance on equivalent neural networks architectures using backpropagation. Finally, note that the linearization procedure is compatible with all the common activation functions such as the relu, tanh, logistic sigmoid, etc. \begin{figure}[htbp] \centering \includegraphics[width=55mm]{Linearized_activation_fct.pdf}\\[-4pt] \caption{Examples of linearization for a softplus activation function ${\sigma}(\cdot)$ at the expected value $\mathbb{E}[{Z}]$ for $Z\sim\mathcal{N}(z;\mu_Z,0.25^2)$ where $\mu_Z=\{-1, 0, 1\}$.} \label{FIG:LACT} \end{figure} The transition from the knowledge of the $j^{\text{th}}$ layer's activation units to an activation unit on the $j+1$ layer is defined by $a_{i}^{(j+1)}=\tilde{\sigma}(z_{i}^{(j+1)})=\tilde{\sigma}(w_{i,1}^{(j)}a_{1}^{(j)}+w_{i,2}^{(j)}a_{2}^{(j)}+\cdots+w_{i,\mathtt{A}}^{(j)}a_{\mathtt{A}}^{(j)}+b^{(j)}_{i})$. Analogously, we go from the last hidden layer to the output layer by following $$z_{i}^{(\mathtt{O})}=w_{i,1}^{(\mathtt{L})}a_{1}^{(\mathtt{L})}+w_{i,2}^{(\mathtt{L})}a_{2}^{(\mathtt{L})}+\cdots+w_{i,\mathtt{A}}^{(\mathtt{L})}a_{\mathtt{A}}^{(\mathtt{L})}+b^{(\mathtt{L})}_{i},$$ for all $i\in\{1,2,\cdots,\mathtt{Y}\}$. All these steps define what we call the \emph{approximate Gaussian feedforward neural network} (AG-FNN), which can be summarized by the input-output relation \begin{equation}\!\left\{\bm{\mu}_{\bm{Z}}^{(\mathtt{O})},\mathbf{\Sigma}_{\bm{Z}}^{(\mathtt{O})},\mathbf{\Sigma}_{\bm{Z\theta}}^{(\mathtt{O})}\right\}=\text{AG-FNN}\left(\bm{\mu}_{\bm{X}},\mathbf{\Sigma}_{\bm{X}},\bm{\mu}_{\bm{\theta}},\mathbf{\Sigma}_{\bm{\theta}}\right).\label{EQ:LFNN}\end{equation} For the \emph{regression setup} where $\bm{y}\in\mathbb{R}^{\mathtt{\mathtt{Y}}}$, the observed model output is directly defined by the last layer as described in Equation \ref{EQ:obs} so that $\mathcal{N}(\bm{y};\bm{\mu}_{\bm{Y}},\mathbf{\Sigma}_{\bm{Y}})$, where, $\bm{\mu}_{\bm{Y}}=\bm{\mu}_{\bm{Z}}^{(\mathtt{O})}$, and $\mathbf{\Sigma}_{\bm{Y}}=\mathbf{\Sigma}_{\bm{Z}}^{(\mathtt{O})}+\mathbf{\Sigma}_{\bm{V}}$ For the \emph{classification setup}, we need to convert the output $\bm{y}\in\mathbb{R}^{\mathtt{\mathtt{Y}}}$ into a class observation ${y}^{(\mathtt{C})}\in\{1,2,\cdots,\mathtt{K}\}$, as depicted in Figure \ref{FIG:FeedForward_NN_classification}.\begin{figure}[h!] ~~~\subfloat[][Expanded representation]{ \!\!\!\!\!\!\!\!\input{FeedForward_NN_classification_full.tex}~~}~\subfloat[][Compact representation]{ ~~~~~\input{FeedForward_NN_classification.tex}~~~~~~~~~~} \caption{Expanded and compact representations of the output layer for the classification setup.} \label{FIG:FeedForward_NN_classification} \end{figure} Note that using the traditional \emph{Softmax} output layer would not allow for a closed-form solution in order to propagate and marginalize the uncertainty associated with the output $\bm{Y}$. Instead, we propose to employ a \emph{hierarchical binary decomposition} similar to what was employed by \citeauthor{morin2005hierarchical} (\citeyear{morin2005hierarchical}). For that, each class is encoded in a binary tree with $\mathtt{H}=\lceil\log_2(\mathtt{K})\rceil$ layers, and which is defined by $\mathtt{Y}=\mathtt{K}-1$ hidden states when $\log_2(\mathtt{K})\in\mathbb{Z}^+$. \begin{figure}[b!]\centering \includegraphics[width=0.7 \columnwidth]{Hierchical_tree_y.pdf} \caption{Representation of a 3-layers hierarchical binary decomposition of classes $y_{ijk}^{(\mathtt{C})}\in\{1,2,\cdots,8\}$ using the output layer variables $\bm{y}=[y\,y_{0}\,y_{1}\,y_{00}\,y_{01}\,y_{10}\,y_{11}]^{\intercal}\in\mathbb{R}^{7}$.} \label{FIG:Hierarchical_tree} \end{figure} Figure \ref{FIG:Hierarchical_tree} depicts the hierarchical decomposition for $\mathtt{K}=8$ classes and $\mathtt{H}=3$ layers, where a given class $y^{(\mathtt{C})}_{\mathcal{C}}:\mathcal{C}=\{j,k,l\}\in\{0,1\}^3$ is uniquely described by a set of $\mathtt{H}$ indices. In a binary context where $\mathtt{H}=1$, we can transform a regression problem into a probability for a class $y^{\mathtt{C}}_i,~i\in\{0,1\}$ by using $$p(y^{\mathtt{C}}_i|y)=\Phi\!\left(\!(-1)^i \frac{y}{\alpha}\right),$$ where, $\Phi(\cdot)$ denotes the standard normal CDF, and $\alpha\in\mathbb{R}^+$ is a scaling factor ensuring the compatibility with the output layer that is intended to return values in the interval $[-1,1]$. In the general case with $\mathtt{K}$-classes, the conditional probability of a class given the output values $\bm{y}$ is defined by $$p(y^{(\mathtt{C})}_{\mathcal{C}}|\bm{y})=\prod_{h=1}^{\mathtt{H}}\Phi\!\left(\!(-1)^{\mathcal{C}_h} \frac{[\bm{y}_\mathcal{C}]_{h}}{\alpha}\!\right),$$ where $\bm{y}_{\mathcal{C}}=[y\,y_{j}\,y_{jk}\,y_{jkl}\,\cdots]^\intercal\in \mathbb{R}^{\mathtt{H}}$. For the example in Figure \ref{FIG:Hierarchical_tree} where $\mathtt{H}=3$ layers, it simplifies to $\bm{y}_{\mathcal{C}}=[y\,y_{j}\,y_{jk}]^\intercal$, so that $$p(y^{(\mathtt{C})}_{\{ijk\}}|\bm{y})=\Phi\!\left(\!(-1)^i \frac{y}{\alpha}\!\right)\cdot \Phi\!\left(\!(-1)^j\frac{y_j}{\alpha}\!\right)\cdot \Phi\!\left(\!(-1)^k \frac{y_{jk}}{\alpha}\!\right).$$ For the special case where $\bm{Y}_{\mathcal{C}}|\mathcal{D}\sim\mathcal{N}(\bm{\mu}_{\bm{Y}_{\mathcal{C}}},\text{diag}(\bm{\sigma}_{\bm{Y}_{\mathcal{C}}}^2))$ follows a Gaussian distribution with diagonal covariance, we can employ the development found in \citeauthor{williams2006gaussian} (\citeyear{williams2006gaussian}) in order to obtain a closed-form solution to marginalize the output layer's uncertainty, \begin{equation}\begin{array}{ll} p(y^{(\mathtt{C})}_{\mathcal{C}}|\mathcal{D})&=\displaystyle\int p(y^{(\mathtt{C})}_{\mathcal{C}}|\bm{y}_{\mathcal{C}})\cdot f(\bm{y}_{\mathcal{C}}|\mathcal{D})d\bm{y}\\[-1pt] &\displaystyle=\prod_{h=1}^{\mathtt{H}}\Phi\!\left(\!(-1)^{\mathcal{C}_h}\frac{[\bm{\mu}_{\bm{Y}_{\mathcal{C}}}]_h}{\sqrt{\alpha^2+[\bm{\sigma}_{\bm{Y}_{\mathcal{C}}}^2]_h}}\!\right), \end{array}\label{EQ:class_marginal}\end{equation} where $\alpha$ is a scaling factor that enable working with either normalized or unnormalized data. Note that in the case where number of classes $\mathtt{K}$ does not correspond to an integer to the power $2$, it is required to normalize the marginal probabilities obtained in Equation \ref{EQ:class_marginal} in order to account for the unused leaves from the binary tree. During the training phase where we infer the network's parameters from observations $y^{(\mathtt{C})}\in\{1,2,\cdots,\mathtt{K}\}$, we convert each class into a $\mathtt{H}$-component vector $\bm{y}_{\mathcal{C}}\in\{-1,1\}^{\mathtt{H}}$ so that $[\bm{y}_{\mathcal{C}}]_i=(-1)^{\mathcal{C}_i}$. \subsection{Linear Algebra for AG-FNN}\label{SS:LAFFNN} In this section, we describe how the steps involved in the evaluation of Equation \ref{EQ:LFNN} can be performed using linear algebra. Our first hypothesis supposes that the knowledge for covariates, hidden units, as well as the weights and bias, is described by Gaussian random variables. We can then generalize the operations for going from the $\mathtt{A}$ activation units at a layer $j$ to the subsequent $\mathtt{A}$ hidden units at layer $j+1$ using linear algebra so that \begin{equation}\begingroup \setlength\arraycolsep{2pt} \underbrace{\begin{bmatrix}Z_{1}^{(j+1)}\\Z_{2}^{(j+1)}\\\vdots\\Z_{\mathtt{A}}^{(j+1)}\end{bmatrix}}_{\bm{Z}^{(j+1)}}\!=\!\underbrace{\begin{bmatrix}W_{1,1}^{(j)}&W_{1,2}^{(j)}&\cdots&W_{1,\mathtt{A}}^{(j)}\\W_{2,1}^{(j)}&W_{2,2}^{(j)}&\cdots&W_{2,\mathtt{A}}^{(j)}\\\vdots&\vdots&\ddots&\vdots\\W_{\mathtt{A},1}^{(j)}&W_{\mathtt{A},2}^{(j)}&\cdots&W_{\mathtt{A},\mathtt{A}}^{(j)} \\\end{bmatrix}}_{\bm{W}^{(j)}}\!\times\!\underbrace{\begin{bmatrix}A_{1}^{(j)}\\A_{2}^{(j)}\\\vdots\\A_{\mathtt{A}}^{(j)}\end{bmatrix}}_{\bm{A}^{(j)}}\!+\!\underbrace{\begin{bmatrix}B^{(j)}_{1}\\B^{(j)}_{2}\\\vdots\\B^{(j)}_{\mathtt{A}}\end{bmatrix}}_{\bm{B}^{(j)}}\label{E:Z_matrix}. \endgroup\end{equation} Our prior knowledge for activation units is described by $\bm{A}^{(j)}\sim\mathcal{N}(\bm{a}^{(j)};\bm{\mu}^{(j)}_{\bm{A}},\mathbf{\Sigma}^{(j)}_{\bm{A}})$ as well as by the covariance $\text{cov}(\bm{\theta},\bm{A}^{(j)})$ between the activation units and the vector $\bm{\theta}\in\mathbb{R}^{\mathtt{P}}$ containing all the weights and bias parameters defined for all the layers in the network. We can re-write Equation \ref{E:Z_matrix} by breaking down the matrix-vector product $\bm{W}\times\bm{A}$, into an operation-wise equivalent vector $(\bm{W\!\!A})\in\mathbb{R}^{\mathtt{A}^2\times1}$. We can then employ Equation \ref{eq1} in order to compute the expected vector $\bm{\mu}^{(j)}_{\bm{W\!\!A}}\equiv\mathbb{E}[(\bm{W\!\!A})^{(j)}]$, Equation \ref{eq3}-\ref{eq4} for the covariance matrix $\mathbf{\Sigma}^{(j)}_{\bm{W\!\!A}}\equiv\text{cov}\left((\bm{W\!\!A})^{(j)}\right)\in\mathbb{R}^{\mathtt{A}^{2}\times \mathtt{A}^{2}}$ associated with the product terms $(\bm{W\!\!A})^{(j)}\in\mathbb{R}^{\mathtt{A}^{2}}$, and Equation \ref{eq2} for the covariance matrix $\mathbf{\Sigma}^{(j)}_{\bm{W\!\!A\theta}}\equiv\text{cov}\left((\bm{W\!\!A})^{(j)},\bm{\theta}\right)\in\mathbb{R}^{\mathtt{A}^{2}\times \mathtt{P}}$. We then introduce two new deterministic matrices $\mathbf{F}_{\bm{wa}}^{(j)}\in\{0,1\}^{\mathtt{A}\times\mathtt{A}^{2}}$ and $\mathbf{F}_{\bm{b}}^{(j)}\in\{0,1\}^{\mathtt{A}\times\mathtt{A}}$, which allow rewriting Equation \ref{E:Z_matrix} as a system of linear equations involving the product-terms vector $(\bm{W\!\!A})$, \begin{equation}\bm{Z}^{(j+1)}=\mathbf{F}_{\bm{wa}}^{(j)} (\bm{W\!\!A})^{(j)}+\mathbf{F}_{\bm{b}}^{(j)}\bm{B}^{(j)}.\label{E:layer_matrix}\end{equation} Note that $\mathbf{F}_{\bm{wa}}^{(j)}$ and $\mathbf{F}_{\bm{b}}^{(j)}$ are non-unique as their specific definition depend on the ordering of variables in the problem. An exemple of structure for these matrices is presented in Appendix \ref{Appendix:B}. Using the properties of linear functions of Gaussian random variables, we obtain \begin{equation} \!\!\begin{array}{rrcl} \bm{\mu}^{(j+1)}_{\bm{Z}}\equiv&\!\!\!\!\!\mathbb{E}[\bm{Z}^{(j+1)}]&\!\!\!\!\!=\!\!\!\!\!&\mathbf{F}_{\bm{wa}}^{(j)}\bm{\mu}^{(j)}_{\bm{W\!\!A}}\!\!+\!\mathbf{F}_{\bm{b}}^{(j)}\!\bm{\mu}^{(j)}_{\bm{B}},\\[4pt] \mathbf{\Sigma}^{(j+1)}_{\bm{Z}}\equiv&\!\!\!\!\!\text{cov}(\bm{Z}^{(j+1)})&\!\!\!\!\!=\!\!\!\!\!&\mathbf{F}_{\bm{wa}}^{(j)} \mathbf{\Sigma}^{(j)}_{\bm{W\!\!A}}\mathbf{F}_{\bm{wa}}^{(j)\intercal}\\[4pt]\!&\!&\!\!\!&\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!+\mathbf{F}_{\bm{b}}^{(j)}\mathbf{\Sigma}^{(j)}_{\bm{B}}\mathbf{F}_{\bm{b}}^{(j)\intercal}\\[4pt]&&\!\!\!&\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! +2\mathbf{F}_{\bm{wa}}^{(j)}\text{cov}(\bm{W\!\!A}^{(j)}\!,\!\bm{B}^{(j)})\mathbf{F}_{\bm{b}}^{(j)\intercal},\\[4pt] \mathbf{\Sigma}^{(j+1)}_{\bm{Z\theta}}\equiv&\!\!\!\!\text{cov}(\bm{Z}^{(j+1)}\!\!,\bm{\theta})&\!\!\!\!\!=\!\!\!\!\!&\mathbf{F}_{\bm{wa}}^{(j)}\mathbf{\Sigma}^{(j)}_{\bm{W\!\!A\theta}}+\mathbf{\Sigma}^{(j)}_{\bm{B\theta}},\label{E:z_covariance} \end{array} \end{equation} where $\mathbf{\Sigma}^{(j)}_{\bm{B\theta}}\equiv \text{cov}(\bm{B}^{(j)},\bm{\theta})\in\mathbb{R}^{\mathtt{A}\times \mathtt{P}}$ is the covariance between the bias parameters from the $j^{\text{th}}$ layer and all the other parameters. In order to apply the linearized activation function $\bm{A}^{(j+1)}=\tilde{\sigma}(\bm{Z}^{(j+1)})$, \begin{equation}\bm{A}^{(j+1)}=\mathbf{J}^{(j+1)}\left(\bm{Z}^{(j+1)}-\bm{\mu}^{(j+1)}_{\bm{Z}}\right)+{\sigma}(\bm{\mu}^{(j+1)}_{\bm{Z}}),\label{EQ:activation} \end{equation} we need to define the diagonal Jacobian matrix of the transformation evaluated at $\bm{\mu}^{(j+1)}_{\bm{Z}}$, $\mathbf{J}^{(j+1)}=\text{diag}\big(\nabla_{\!\!\bm{z}} {\sigma}(\bm{\mu}^{(j+1)}_{\bm{Z}})\big)$. Using again the properties of linear functions of Gaussian random variables, we obtain \begin{equation} \begin{array}{rrcl} \bm{\mu}^{(j+1)}_{\bm{A}}\equiv&\mathbb{E}[\bm{A}^{(j+1)}]&=&\tilde{\sigma}(\bm{\mu}^{(j+1)}_{\bm{Z}}),\\[4pt] \mathbf{\Sigma}^{(j+1)}_{\bm{A}}\equiv&\text{cov}(\bm{A}^{(j+1)})&=&\mathbf{J}^{(j+1)}\mathbf{\Sigma}^{(j+1)}_{\bm{Z}}\mathbf{J}^{(j+1)\intercal},\\[4pt] \mathbf{\Sigma}^{(j+1)}_{\bm{A\theta}}\equiv&\text{cov}(\bm{A}^{(j+1)},\bm{\theta})&=&\mathbf{J}^{(j+1)}\mathbf{\Sigma}^{(j+1)}_{\bm{Z\theta}}.\label{E:a_covariance} \end{array} \end{equation} Equations \ref{E:z_covariance} \& \ref{E:a_covariance} allow propagating the information about the covariance of activation units and its dependence on parameters through any pairs of successive layers. For the input layer, the steps described in Equations \ref{E:Z_matrix}-\ref{E:a_covariance} remain the same excepted that the activation units $\bm{A}^{(j)}$ are replaced by the covariates $\bm{X}\sim\mathcal{N}(\bm{x};\bm{\mu}_{\bm{X}},\mathbf{\Sigma}_{\bm{X}})$. \subsection{Tractable Approximate Gaussian Inference (TAGI)}\label{SS:bayesian_estimation} Let us assume we have a set of joint observations for covariates and system responses so that $\mathcal{D}=\{\mathcal{D}_{x},\mathcal{D}_{y}\}=\{(\bm{x}_{i},\bm{y}_{i}),\forall i\in\{1:\mathtt{D}\}\}$. Given that our prior knowledge for the neural network's parameter is $f(\bm{\theta})=\mathcal{N}(\bm{\theta};\bm{\mu}_{\bm{\theta}},\mathbf{\Sigma}_{\bm{\theta}})$, the method presented in \S\ref{SS:FFNN} supposes that the joint PDF $f(\bm{\theta},\bm{y})$ for parameters $\bm{\theta}$ and observations $\bm{y}$ is Gaussian with mean vector and covariance $$\bm{\mu}=\left[\begin{array}{c}\bm{\mu}_{\bm{\theta}}\\\bm{\mu}_{\bm{Y}}\end{array}\right] ,~ \mathbf{\Sigma}=\left[\begin{array}{cc}\mathbf{\Sigma}_{\bm{\theta}}& \mathbf{\Sigma}_{\bm{Y\!\theta}}^\intercal\\ \mathbf{\Sigma}_{\bm{Y\!\theta}}& \mathbf{\Sigma}_{\bm{Y}} \end{array}\right].$$ The conditional PDF for the vector $\bm{\theta}$ given observations $\bm{Y}=\bm{y}$ is described by the Gaussian conditional equations $f(\bm{\theta}|\bm{y})=\mathcal{N}(\bm{\theta};\bm{\mu}_{\bm{\theta}|\bm{y}},\mathbf{\Sigma}_{\bm{\theta}|\bm{y}})$ defined by its conditional mean vector and covariance matrix, \begin{equation}\begin{array}{l} \bm{\mu}_{\bm{\theta}|\bm{y}}=\bm{\mu}_{\bm{\theta}}+\mathbf{\Sigma}_{\bm{Y\!\theta}}^{\intercal}\mathbf{\Sigma}_{\bm{Y}}^{-1}(\bm{y}-\bm{\mu}_{\bm{Y}})\\[4pt] \mathbf{\Sigma}_{\bm{\theta}|\bm{y}}=\mathbf{\Sigma}_{\bm{\theta}}-\mathbf{\Sigma}_{\bm{Y\!\theta}}^{\intercal}\mathbf{\Sigma}_{\bm{Y}}^{-1}\mathbf{\Sigma}_{\bm{Y\!\theta}}.\end{array}\label{E:Gaussian_conditional_theta}\end{equation} This 1-step network-wise inference procedure is computationally prohibitive because the forward propagation of uncertainty depicted in Figure \ref{FIG:FNN_inference_long}a involves large-sized densely populated matrices, and the inference using Equation \ref{E:Gaussian_conditional_theta} again involves full matrices. \begin{figure}[h!] \hspace{-9.5mm}\subfloat[][Intractable 1-step network-wise inference (Eq. \ref{E:Gaussian_conditional_theta})]{\input{FeedForward_NN_inference.tex}}\\ \hspace*{-9.5mm}\subfloat[][Tractable recursive layer-wise inference (Eq. \ref{EQ:output_inf}--\ref{EQ:RTS_inference_z})]{\input{FeedForward_NN_inference_TAGI.tex}} \caption{Representation of the \emph{forward} propagation of uncertainty ({\color{magenta!75}magenta arrows}) and \emph{inference} procedures ({\color{cyan!75}cyan arrows}).} \label{FIG:FNN_inference_long} \end{figure}} The solution we propose to overcome these challenges is twofold: (1) employ a diagonal covariance structure for both the parameters $\bm{\theta}$, and hidden units $\bm{Z}^{(j)}$, and (2) use the inherent conditional independence of hidden units between layers, that is, $\bm{Z}^{(j-1)}\independent\bm{Z}^{(j+1)}|\bm{z}^{(j)}$, in order to perform recursive layer-wise inference. As depicted in Figure \ref{FIG:FNN_inference_long}b, the first step consists in inferring the posterior mean vector and diagonal covariance for the output layer following \begin{equation} \begin{array}{rcl} f(\bm{z}^{(\mathtt{O})}|\bm{y})&=&\mathcal{N}(\bm{z}^{(\mathtt{O})};\bm{\mu}_{\bm{Z}^{(\mathtt{O})}|\bm{y}},\bm{\Sigma}_{\bm{Z}^{(\mathtt{O})}|\bm{y}})\\[6pt] \bm{\mu}_{\bm{Z}^{(\mathtt{O})}|\bm{y}}&=&\bm{\mu}_{\bm{Z}^{(\mathtt{O})}}+\mathbf{\Sigma}_{\bm{Y\!Z}^{(\mathtt{O})}}^{\intercal}\mathbf{\Sigma}_{\bm{Y}}^{-1}(\bm{y}-\bm{\mu}_{\bm{Y}})\\[4pt] \mathbf{\Sigma}_{\bm{Z}^{(\mathtt{O})}|\bm{y}}&=&\mathbf{\Sigma}_{\bm{Z}^{(\mathtt{O})}}-\mathbf{\Sigma}_{\bm{Y\!Z}^{(\mathtt{O})}}^{\intercal}\mathbf{\Sigma}_{\bm{Y}}^{-1}\mathbf{\Sigma}_{\bm{Y\!Z}^{(\mathtt{O})}}.\end{array} \label{EQ:output_inf} \end{equation} Note that for classification problems, because of the hierarchical formulation described in \S\ref{SS:FFNN}, even if there are $\mathtt{Y}$ classes, only $\mathtt{H}=\lceil\log_2(\mathtt{Y})\rceil$ hidden units from the output layer are updated for each observation. In order to perform layer-wise inference for hidden units and parameters, we define the short-hand notation $\{\bm{\theta}^{\text{+}},\bm{Z}^{\text{+}}\}\equiv\{\bm{\theta}^{(j+1)},\bm{Z}^{(j+1)}\}$ and $\{\bm{\theta},\bm{Z}\}\equiv\{\bm{\theta}^{(j)},\bm{Z}^{(j)}\}$. As depicted in Figure \ref{FIG:FNN_inference_long}b, the inference for the $j^\text{th}$ layer's weights $\bm{\theta}$ and hidden units $\bm{Z}$ is done using the Rauch-Tung-Striebel recursive procedure \cite{rauch1965maximum} where \begin{equation} \begin{array}{rcl} f(\bm{z}|\bm{y})&=&\mathcal{N}(\bm{z};\bm{\mu}_{\bm{Z}|\bm{y}},\bm{\Sigma}_{\bm{Z}|\bm{y}})\\[4pt] \bm{\mu}_{\bm{Z}|\bm{y}}&=&\bm{\mu}_{\bm{Z}}+\mathbf{J}_{\bm{Z}}\left(\bm{\mu}_{\bm{Z}^{\text{+}}|\bm{y}}-\bm{\mu}_{\bm{Z}^{\text{+}}}\right)\\[4pt] \bm{\Sigma}_{\bm{Z}|\bm{y}}&=&\bm{\Sigma}_{\bm{Z}}+\mathbf{J}_{\bm{Z}}\left(\bm{\Sigma}_{\bm{Z}^{\text{+}}|\bm{y}}-\bm{\Sigma}_{\bm{Z}^{\text{+}}}\right)\mathbf{J}_{\bm{Z}}^{\intercal}\\[4pt] \mathbf{J}_{\bm{Z}}&=&\bm{\Sigma}_{\bm{Z}\!\bm{Z}^{\text{+}}}\bm{\Sigma}_{\bm{Z}^{\text{+}}}^{-1},\end{array}\label{EQ:RTS_inference_y}\end{equation} \begin{equation} \begin{array}{rcl} f(\bm{\theta}|\bm{y})&=&\mathcal{N}(\bm{\theta};\bm{\mu}_{\bm{\theta}|\bm{y}},\bm{\Sigma}_{\bm{\theta}|\bm{y}})\\[4pt] \bm{\mu}_{\bm{\theta}|\bm{y}}&=&\bm{\mu}_{\bm{\theta}}+\mathbf{J}_{\bm{\theta}}\left(\bm{\mu}_{\bm{Z}^{\text{+}}|\bm{y}}-\bm{\mu}_{\bm{Z}^{\text{+}}}\right)\\[4pt] \bm{\Sigma}_{\bm{\theta}|\bm{y}}&=&\bm{\Sigma}_{\bm{\theta}}+\mathbf{J}_{\bm{\theta}}\left(\bm{\Sigma}_{\bm{Z}^{\text{+}}|\bm{y}}-\bm{\Sigma}_{\bm{Z}^{\text{+}}}\right)\mathbf{J}_{\bm{\theta}}^{\intercal}\\[4pt] \mathbf{J}_{\bm{\theta}}&=&\bm{\Sigma}_{\bm{\theta}\bm{Z}^{\text{+}}}\bm{\Sigma}_{\bm{Z}^{\text{+}}}^{-1}. \end{array} \label{EQ:RTS_inference_z} \end{equation The key aspect of this approach is that for each layer, we only need to store the mean vectors $\{\bm{\mu}_{\bm{\theta}},\bm{\mu}_{\bm{Z}}\}$ and the covariances $\{\bm{\Sigma}_{\bm{\theta}},\bm{\Sigma}_{\bm{Z}},\bm{\Sigma}_{\bm{\theta}\bm{Z}^{\text{+}}},\bm{\Sigma}_{\bm{Z}\!\bm{Z}^{\text{+}}}\}$, where in addition to the relations already given in \S\ref{SS:LAFFNN},$$\bm{\Sigma}_{\bm{Z}\!\bm{Z}^{\text{+}}}=\mathbf{F}_{\bm{wa}}^{(j)}\text{cov}(\bm{W\!\!A}^{(j)}\!,\!\bm{Z}^{(j)})+\mathbf{F}_{\bm{b}}^{(j)}\text{cov}(\bm{B}^{(j)}\!,\!\bm{Z}^{(j)}).$ With a diagonal covariance structure for both $\bm{Z}$ and $\bm{\theta}$, the covariance matrices defining each layer contain at most $\mathtt{A}^2+\mathtt{A}$ non-zero terms, i.e., the number of weights ($\mathtt{A}^2$) and bias ($\mathtt{A}$) per layer; Because of the diagonal structures of covariance matrices, equations \ref{EQ:output_inf}--\ref{EQ:RTS_inference_z} have a computational complexity $\mathcal{O}(\mathtt{A}^2)$, which scales linearly with the number of hidden layers $\mathtt{L}$. \subsection{Hyper-parameter estimation} There are typically tens of thousands, if not millions, of parameters in $\bm{\theta}$, for which we typically have little or no prior information for defining the hyper-parameters ${\bm{\eta}}^{(0)}=\{\bm{\mu}_{\bm{\theta}}^{(0)},\mathbf{\Sigma}_{\bm{\theta}}^{(0)}\}$. In the case where we have small datasets, the weakly informative prior combined with limited data will lead to a weakly informative posterior. One solution to go around this difficulty while avoiding overfitting is to learn the model parameters over multiple epochs, $\mathtt{E}>1$, using a training $\mathcal{D}_{\mathtt{T}}$ and validation set $\mathcal{D}_{\mathtt{V}}$. Here, we propose to employ the posterior's hyper-parameter values at the $i^{th}$ iteration ${\bm{\eta}}^{(i)}=\{\bm{\mu}_{\bm{\theta}|\mathcal{D}_{\mathtt{T}}}^{(i)}, \mathbf{\Sigma}_{\bm{\theta}|\mathcal{D}_{\mathtt{T}}}^{(i)}\}$ and use them as the prior's hyper-parameters at the next iteration $i+1$. This recursive procedure is stopped when the marginal likelihood $f(\mathcal{D}_{y,\mathtt{V}}|\mathcal{D}_{x,\mathtt{V}},{\bm{\eta}}^{(i)})\,=\,\mathcal{N}\big(\mathcal{D}_{\mathtt{V}};\bm{\mu}_{\bm{y}_{\mathtt{v}}|\mathcal{D}_{\mathtt{T}}}^{(i)}, \mathbf{\Sigma}_{\bm{y}_{\mathtt{v}}|\mathcal{D}_{\mathtt{T}}}^{(i)}\big)$ for the validation set $\mathcal{D}_{\mathtt{V}}$, has reached its maximal value. This procedure is analogous to the empirical Bayes approach \cite{efron2012large} where the prior knowledge's hyper-parameters are learnt through the maximization problem \begin{equation}\hat{\bm{\eta}}=\underset{\bm{\eta}}{\arg\,\max}~\int f(\mathcal{D}_{y,\mathtt{V}}|\mathcal{D}_{x,\mathtt{V}},\bm{\theta})\cdot f(\bm{\theta}|\bm{\eta})d\bm{\theta}.\label{EQ:empirical_bayes}\end{equation} Note that unlike in Equation \ref{EQ:empirical_bayes} where the maximization is explicit, in our case the maximization is implicitly performed by updating over multiple epochs. \section{Experiments}\label{S:experiments} \subsection{1D toy problem} We apply TAGI to the 1D regression problem $y=x^{3}+v$, $v:V\sim\mathcal{N}(0,9)$ taken from \cite{hernandez2015probabilistic}, using an AG-FNN having a single hidden layer with 100 units, and a ReLU activation function. The objective of this case study is to showcase how TAGI can be applied on small datasets ($\mathtt{D}=20$ points), and to compare the results obtained by considering either diagonal or full covariance matrices. In this example, the inference is performed using one observation at a time, where both the covariates $x$ and observations $y$ were normalized in the range $[-1,1]$. The optimal number of epochs is identified from a validation set $\mathcal{D}_{\mathtt{V}}$ consisting in 20 additional points. The prior covariance for bias is initialized to $\Sigma_{\bm{B}}^{0}=0.01\cdot\mathbf{I}$, and for weights $\Sigma_{\bm{W}}^{0}$, by multiplying the Xaviers's approach \cite{glorot2010understanding} by a factor 0.25. The prior mean vector is randomly sampled from $\bm{\mu}_{\bm{\theta}}^{0}\sim\mathcal{N}(\mathbf{0},\Sigma_{\bm{\theta}}^{0})$. Figure \ref{fig:1D_reg} compares the true function employed to generate the data, with the AG-FNN (with diagonal covariances) predictions described by their expected values and $\pm3\sigma$ confidence regions. We can see in (a) that the prior predictive obtained before updating with observations ($\mathtt{E}=0$) is weakly informative, and that the posterior predictive obtained after the first epoch (b, $\mathtt{E}=1$) is still a poor approximation of the true function. The log-likelihood reported in (d) for the validation set allows identifying that the optimal number of epochs is $\mathtt{E}=24$. The log-likelihood values reported in Figure \ref{fig:1D_reg}d confirms that employing a training set to identify the number of epoch would not be able to prevent overfitting as depicted in (c). \begin{figure}[h!] \centering\!\!\!\subfloat[][$\mathtt{E}\!=\!0$]{{\includegraphics[height=27.5mm]{regression_1D_early_stop_0.pdf}}} \subfloat[][$\mathtt{E}\!=\!1$]{{\includegraphics[height=27.5mm]{regression_1D_early_stop_1.pdf}}}\subfloat[][$\mathtt{E}\!=\!50$]{{\includegraphics[height=27.5mm]{regression_1D_early_stop_50.pdf}}}\\\subfloat[][$\mathtt{E}\!=\!24$]{{\includegraphics[height=28mm]{regression_1D_early_stop_24.pdf}}} \caption{Application of AG-FNN with diagonal covariances to a toy regression problem where (a-c) describe the evolution of the predictive distribution with respect to the number of epochs $\mathtt{E}$. In (d), we compare the training and validation log-likelihood in order to identify the optimal number of epochs, i.e., $\mathtt{E}=24$.} \label{fig:1D_reg} \end{figure} \begin{figure}[t!]\subfloat[][$\mathtt{L}\!=\!1$, $\mathtt{A}\!=\!100$]{\includegraphics[width=1 \columnwidth]{Toy_example_fullCOV_100.pdf}}\\[-2pt] \subfloat[][$\mathtt{L}\!=\!2$, $\mathtt{A}\!=\!50$]{\includegraphics[width=1 \columnwidth]{Toy_example_fullCOV_50_50.pdf}} \caption{Representation of the sorted correlation coefficients extracted from upper-triangular posterior covariance matrices for the parameters $\bm{\theta}^{(j)}$ and hidden units $\bm{z}^{(j)}$. The left-most graphs present the correlations for each of the 20 observations within the first epoch, and the center graphs present the correlations at the end of each epoch.} \label{FIG:full_covariance} \end{figure} In a second experiment, we now apply TAGI to the same dataset while considering the full covariance matrices for $\bm{\theta}^{(j)}$ and $\bm{z}^{(j)}$. Two networks are studied: $\mathtt{L}\!=\!1$, $\mathtt{A}\!=\!100$ and $\mathtt{L}\!=\!2$, $\mathtt{A}\!=\!50$. Figure \ref{FIG:full_covariance} displays the sorted correlation coefficients extracted from the upper-triangular posterior covariances, either for each observation from the first epoch, or for the last observation from subsequent epochs. In Figure \ref{FIG:full_covariance}a, for a single hidden layer of 100 units, we can see that the correlation is close to zero for most pairs of parameters and hidden units. In Figure \ref{FIG:full_covariance}b, for a network made of two hidden layers of 50 units, we can see that the correlation is again negligible for most pairs of parameters, and for the hidden units from the first layer, $\bm{z}^{(1)}$. For the hidden units on the second layer, $\bm{z}^{(2)}$, the correlation is up to $\approx 0.5$ during the firsts epochs. This positive correlation on the second hidden layer is caused by the forward propagation of uncertainty from $\bm{z}^{(1)}\to\bm{z}^{(2)}$. This positive correlation is not present while going from $x\to\bm{z}^{(1)}$ because here $x$ is treated as a constant. We can see in Figure \ref{FIG:full_covariance}b that as the number of epochs increases and the parameters' posterior allow capturing the pattern in the data, the positive correlation between the pairs of hidden units in $\bm{z}^{(2)}$ vanishes. These results provide empirical evidence explaining why considering only diagonal covariance matrices may lead to results that are comparable to those obtained while considering the full covariance structure. \begin{table*}[t!]\small \caption{Comparison TAGI's results with PBP \cite{hernandez2015probabilistic}, VMG \cite{louizos2016structured}, and MC-dropout \cite{gal2016dropout}, for $\mathtt{E}=40$ epochs (Rank legend: {\bf\color{orange} first}, {\bf{\color{teal}second}}). \\[0pt]}\centering \scalebox{1}{\begin{tabular}{r|cccc|cccc} \toprule &\multicolumn{4}{c|}{Root mean square error (RMSE)}&\multicolumn{4}{c}{Average log-likelihood (LL)}\\ Datasets&PBP&VMG&MC-Dropout&{\bf TAGI}&PBP&VMG&MC-Dropout&{\bf TAGI}\\[2pt] \cmidrule{1-9} Boston &3.01$\pm$0.18&\bf\color{orange}2.70$\pm$0.13&\bf\color{teal}2.97$\pm$0.85&3.02$\pm$0.83 &\bf\color{teal}-2.56$\pm$0.12&\bf\color{orange}-2.46$\pm$0.09&\bf\color{orange}-2.46$\pm$0.25&\bf\color{teal}-2.56$\pm$0.33\\ Concrete &5.67$\pm$0.09&\bf\color{orange}4.89$\pm$0.12&\bf\color{teal}5.23$\pm$0.53&5.84$\pm$0.57&-3.14$\pm$0.11&\bf\color{orange}-3.01$\pm$0.03&\bf\color{teal}-3.04$\pm$0.09&-3.19$\pm$0.10\\ Energy &1.80$\pm$0.05&\bf\color{orange}0.54$\pm$0.02&1.66$\pm$0.19&\bf\color{teal}1.54$\pm$0.16&-2.04$\pm$0.02&\bf\color{orange}-1.06$\pm$0.03&-1.99$\pm$0.09&\bf\color{teal}-1.87$\pm$0.11\\ Kin8nm &0.10$\pm$0.00&0.10$\pm$0.00&0.10$\pm$0.00&0.10$\pm$4E-3&0.90$\pm$0.01&\bf\color{orange}1.10$\pm$0.01&\bf\color{teal}0.95$\pm$0.03&0.86$\pm$0.04\\ Naval &0.01$\pm$0.00&\bf\color{orange}0.00$\pm$0.00&0.01$\pm$0.00&7E-3$\pm$5E-4&\bf\color{teal}3.73$\pm$0.01&2.46$\pm$0.12&\bf\color{orange}3.80$\pm$0.05&3.27$\pm$0.20\\ Power &4.12$\pm$0.03&\bf\color{teal}4.04$\pm$0.04&\bf\color{orange}4.02$\pm$0.18&4.13$\pm$0.15&-2.84$\pm$0.01&\bf\color{teal}-2.82$\pm$0.01&\bf\color{orange}-2.80$\pm$0.05&-2.84$\pm$0.04\\ Protein &4.73$\pm$0.01&\bf\color{orange}4.13$\pm$0.02&\bf\color{teal}4.36$\pm$0.04&4.64$\pm$0.15&-2.97$\pm$0.00&\bf\color{orange}-2.84$\pm$0.00&\bf\color{teal}-2.89$\pm$0.01&-2.96$\pm$6E-3\\ Wine &0.64$\pm$0.01&\bf\color{teal}0.63$\pm$0.01&\bf\color{orange}0.62$\pm$0.04&\bf\color{teal}0.63$\pm$0.04&-0.97$\pm$0.01&\bf\color{teal}-0.95$\pm$0.01&\bf\color{orange}-0.93$\pm$0.06&-0.96$\pm$0.06\\ Yacht &1.02$\pm$0.05&\bf\color{orange}0.71$\pm$0.05&1.11$\pm$0.38&\bf\color{teal}0.86$\pm$0.25&-1.63$\pm$0.02&\bf\color{orange}-1.30$\pm$0.02&\bf\color{teal}-1.55$\pm$0.12&\bf\color{orange}{-1.30$\pm$0.23}\\ \bottomrule \end{tabular}} \end{table*}\label{TAB:Benchmark_reg} \subsection{Benchmark regression problems} The performance of TAGI is now compared with PBP \cite{hernandez2015probabilistic}, VMG \cite{louizos2016structured}, and MC-dropout \cite{gal2016dropout} using benchmark regression datasets. For the purpose of comparison with the results from other methods, all the datasets are analyzed for a fixed number of epochs, that is $\mathtt{E}=40$. For all cases, the data is normalized, the activation function is a ReLU, and the batch size is one, i.e. the inference is performed using one observation at a time; The prior covariance for bias is initialized to $\Sigma_{\bm{B}}^{0}=0.01\cdot\mathbf{I}$, and for weights $\Sigma_{\bm{W}}^{0}$, by multiplying the Xaviers's approach \cite{glorot2010understanding} by a factor 0.25; The initial value for the observation error's standard deviation is set to $\sigma_{V}=1$, and this value is optimized using a 5-fold cross-validation setup. The results reported in Table \ref{TAB:Benchmark_reg} indicate that TAGI matches the performance of existing methods in term of root mean square error (RMSE) and log-likelihood (LL). Even if VMG displays the best predictive performance, its computational time is two order of magnitude greater than TAGI, PBP and MC-Dropout \cite{sun2017learning}. The current TAGI's implementation has a computation time that is comparable to PBP and MC-Dropout \cite{gal2016dropout}. The timing details for each dataset is reported in the Appendix \ref{Appendix:C}. Because TAGI had to be implemented from scratch, it is currently not yet fully optimized for computational efficiency. The same is true for the optimization of hyper-parameters such as $\sigma_{V}$ which currently rely on a gradient-based approach. Furthermore, the results reported for TAGI did not employ dropout \cite{srivastava2014dropout}. Also, as it is the case for the other methods reported in Table \ref{TAB:Benchmark_reg}, the number of epochs employed was not optimized. Note as presented in Appendix \ref{Appendix:C}, TAGI is not limited to using ReLU and can employ any common activation function. Moreover, the results presented in Appendix \ref{Appendix:C} confirm that TAGI is also able to handle deeper architectures, where having more than one hidden layer leads to a performance improvement in 7 out of 9 dataset. \subsection{Application on MNIST}\label{S:MNIST} We apply TAGI to the MNIST classification problem \cite{lecun1998gradient} consisting of $\mathtt{D}=70\,000$ $(28\times28)$ greyscale images for $\mathtt{K}=10$ classes ($60\,000$ training and $10\,000$ test). Here, we compare the performance of two AG-FNN configurations, each having $\mathtt{L}=2$ hidden layers with a number of hidden units equal to $\mathtt{A}\in\{100, 800\}$. Each AG-FNN has the same structure for the input ($\mathtt{X}=784$ nodes) and the output layer ($\mathtt{Y}=11$ nodes). The ReLU activation function is used for the two hidden layers. For each digit, the vector of covariates $\mathbf{x}_{i}\in(0,1)^{784}$ is assumed to be deterministic so that $\bm{\mu}_{\bm{X}_{i}}=\mathbf{x}_{i}$ and $\mathbf{\Sigma}_{\bm{X}_{i}}=\mathbf{0}$. The prior covariance for bias is initialized to $\Sigma_{\bm{B}}^{0}=0.01\cdot\mathbf{I}$, and by using the Xaviers's initialization approach \cite{glorot2010understanding} for weights $\Sigma_{\bm{W}}^{0}$. The prior mean vector is randomly sampled from $\bm{\mu}_{\bm{\theta}}^{0}\sim\mathcal{N}(\mathbf{0},\Sigma_{\bm{\theta}}^{0})$. The hyper-parameter associated with the output layer is set to $\alpha=1/3$. The posterior mean vector as well as the main diagonal of the posterior covariance are learnt using two setups: (1) a single observation per batch, that is, $\mathtt{B}=1$, and (2) $10$ observations per batch, $\mathtt{B}=10$. Each network is evaluated for $\sigma_{V} = \{0.1, 0.2, 0.3, 0.4\}$ and the optimal value for $\sigma_{V}$ is selected using a randomly selected validation set corresponding to 5\% of the training set. The optimal number of epochs $\mathtt{E}$ is identified using an early-stop procedure evaluated on the validation set. Table \ref{T:TE} presents the average test error evaluated on $10\,000$ images for the different AG-FNN configurations for $\mathtt{E}=1$ epoch, and for the optimal number of epochs found using early stop. In order to factor in the effect of random weight initialization, the results reported are the average and standard deviations from five runs. The performance achieved with respect to the average classification errors matches the reported state-of-the-art results of approximately 1.6\% for FNNs having a same architecture with 2 layers and 800 hidden units and trained using gradient backpropagation \cite{simard2003best,pmlr-v28-wan13}. We can see by comparing the results for 100 and 800 hidden units that increasing the hidden layer's size improves the performance both for the first and the optimal number of epochs. Moreover, the results in Table \ref{T:TE} indicate that TAGI's classification accuracy is not significantly affected by the usage of batch sizes greater than one. Nevertheless, we noticed though our experiments that using large batch sizes makes the learning phase sensitive to the network initialization as well as the observation noise parameter $\sigma_{V}$. \begin{table}[h]\small \caption{\small MNIST test-set average classification error [\%] for the first and last epoch. $\mathtt{A}$: number of hidden units on each layer; $\mathtt{B}$: number of observations per batch; $\mathtt{E}$: number of epochs; $e$: optimal number of epoch found using early-stop. The results reported are the average of five runs along with $\pm$ one standard deviation.} \centering\scalebox{0.89}{ \!\!\!\setlength{\tabcolsep}{1.5pt} \begin{tabular}{ccccc|cccc} \addlinespace \toprule \multicolumn{1}{l}{}&\multicolumn{4}{c}{$\mathtt{B}=1$} &\multicolumn{4}{c}{$\mathtt{B}=10$} \\[0pt] \cmidrule{2-9} $\mathtt{A}$&$\mathtt{E}=1$& $\mathtt{E}=e$ &$e$&$\sigma_V$&$\mathtt{E}=1$& $\mathtt{E}=e$ &$e$&$\sigma_V$\\[0pt] \cmidrule{1-9} \multirow{1}{*}{$100$}&$3.45\!\pm\!0.19$&$2.35\!\pm\!0.12$&$12\!\pm\!5$&$0.2$&$3.57\!\pm\!0.09$&$2.17\!\pm\!0.10$&$24\!\pm\!5$&$0.4$\\[2pt] $800$&$3.21\!\pm\!0.11$ &$1.51\!\pm\!0.05$&$8\!\pm\!1$&$0.1$&$3.26\!\pm\!0.10$&$1.53\!\pm\!0.05$&$24\!\pm\!11$&$0.4$\\[2pt] \bottomrule\\[-20pt] \end{tabular}} \label{T:TE} \end{table} {\captionsetup[subfloat]{farskip=5pt,captionskip=1pt} \begin{figure}[t!] \subfloat[][TAGI -- $\mathtt{D}\!=\!0$ observation]{\includegraphics[width=0.95 \columnwidth]{mnist_0_0p2.pdf}}\\[-2pt] \subfloat[][TAGI -- $\mathtt{D}\!=\!60$ observations]{\includegraphics[width=0.95 \columnwidth]{mnist_60_0p2.pdf}}\\[-2pt] \subfloat[][TAGI -- $\mathtt{D}\!=\!600$ observations]{\includegraphics[width=0.95 \columnwidth]{mnist_600_0p2.pdf}}\\[-2pt] \subfloat[][TAGI -- $\mathtt{D}\!=\!6\,000$ observations]{\includegraphics[width=0.95 \columnwidth]{mnist_6000_0p2.pdf}}\\[-2pt] \subfloat[][TAGI -- $\mathtt{D}\!=\!60\,000$ observations]{\includegraphics[width=0.95 \columnwidth]{mnist_60000_0p2.pdf}}\\[-2pt] \subfloat[][Standard Backpropagation -- $\mathtt{D}\!=\!60\,000$ observations]{\includegraphics[width=0.95 \columnwidth]{mnist_60000_BP.pdf}} \caption{Leftmost graphs describe the posterior predictive probabilities for each class from the test set. The height of each region on rightmost graphs describe the probability of correct (white), incorrect (black), and unknown (gray) classes as a function of the threshold classification probability employed $\phi\in(0.1,0.999)$. All cases are for a single epoch, i.e., $\mathtt{E}\!=\!1$.} \label{FIG:online_mnist} \end{figure}} We perform a second experiment for an AG-FNN with 2 hidden layers, each having 100 activation units, and where $\sigma_V=0.2$. Figure \ref{FIG:online_mnist} presents on the leftmost plots, the posterior predictive probability of each class for the test set, where $\mathtt{D}=\{0,60,600,6\,000,60\,000\}$ observations have been seen during a single epoch, $\mathtt{E}=1$. The rightmost plots present the probability of correct, incorrect, and unknown classes as a function of the threshold classification probability employed $\phi\in(0.1,0.999)$. A \emph{correct class} correspond to the case where the true label has the highest probability among all classes and its probability is $\geq\phi$. An \emph{incorrect class} corresponds to the case where an incorrect label has the highest probability among all classes and its probability is $\geq\phi$. An \emph{unknown class} correspond to the case where no class has a probability $\geq\phi$. Figure \ref{FIG:online_mnist}a-e show a gradual transition from uniform posterior predictive probabilities for $\mathtt{D}\!=\!0$ observations, to a low entropy one as $\mathtt{D}$ increases. This confirms that TAGI is suited for online learning whereas it can learn continuously using a single observation at a time and over a single epoch. For reference, Figure \ref{FIG:online_mnist}f shows a how standard neural network relying on backpropagation is unable to learn from a single epoch. \section{Conclusion} \label{S:Conclusion} The tractable approximate Gaussian inference method proposed in this paper allows for: (1) the analytical inference of the posterior mean vector and diagonal covariance matrix for the parameters of Bayesian neural networks, (2) the end-to-end treatment of uncertainty from the input layer to the output layer, and (3) the online Bayesian estimation of model parameters using a single observation at a time. The applications on the regression and classification datasets validate that the approach matches the performance of existing methods with respect to computational efficiency and accuracy. TAGI's performance and its linear complexity with respect to the number of parameters makes it a viable alternative to gradient backpropagation. By allowing the end-to-end treatment of uncertainty and online inference, we foresee that the approach will enable transformative developments in supervised, unsupervised, and reinforcement learning. Through our experiments, we noticed that the current architectures and theories developed for backpropagation and employed for defining the network components and initializing its parameters may be sub-optimal for TAGI. Future work in this direction may further improve the performance of the approach. \bigskip \section*{Acknowledgements} The second author was financially supported by research grants from Hydro-Quebec, and the Natural Sciences and Engineering Research Council of Canada (NSERC). The third author was supported by a research grant from the Institute for Data Valorization (IVADO). \newpage
{'timestamp': '2020-04-21T02:27:03', 'yymm': '2004', 'arxiv_id': '2004.09281', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09281'}
arxiv
\section{INTRODUCTION} \label{sec:introduction} How can a population of agents self-organise an effective and efficient communication system that allows them to communicate about their native environment? This fundamental research question concerning the mechanisms underlying human-like communication systems has for a long time sparked the interest of researchers from many fields, including artificial intelligence (e.g. \cite{steels1995self,mordatch2017emergence}), linguistics (e.g. \cite{van2013linguistic,lestrade_2016}), and statistical physics (e.g. \cite{baronchelli2006sharp,puglisi2008cultural}). Well-attended workshops at important conferences, such as the NeurIPS emergent communication workshop, indicate that the community interested in models of emergent communication is growing ever more rapidly. A common methodology for studying emergent communication consists of carrying out multi-agent experiments in which a population of agents takes part in a series of scripted and task-oriented communicative interactions, called `language games' \cite{steels1995self}. Each game is typically played locally by two agents in the population without any form of central control and without the agents having any mind-reading capacities. Through self-organisation, the population converges on a shared communication system after playing a large number of games \cite{de2006reach}. The most widely studied language game is the Naming Game \cite{steels1995self, steels1998spatially, baronchelli2006sharp}, in which the task involves referring to individual objects and thereby establishing a shared lexicon of proper nouns. More advanced scenarios include games in which the agents refer to the properties of objects or events \cite{van2008emergence}, use multi-word expressions \cite{van1999multiple}, or develop grammatical structures \cite{beuls2013agent}. Mathematical investigations and computer simulations help making the assumptions of a specific theory explicit, allowing researchers to study the emergence of a particular communication system in a simulated world, comparing different scenarios and parameter settings. Yet, the step from such a simulated world to the real world with noisy sensori-motor values is crucial to make and requires the use of physical robots, as has been advocated in the work of many researchers studying the emergence and evolution of speech and language \cite{loetzsch10why, language-grounding-in-robots, oudeyer2006discovering}. The increased realism leads to the need for more robust and fine-grained models, as has for instance been shown when moving from the Naming Game in a simulated world to the Grounded Naming Game in the real world \cite{steels2012grounded, steels2016boy}. \begin{figure}[t] \includegraphics[width=\columnwidth]{img/semiotic-cycle} \caption{Grounded robot interactions follow a semiotic cycle that involves three main levels: the sensori-motor level, the conceptual level and the language level. The speaker agent (on the left hand-side) and the hearer agent (on the right hand-side) only share the world in which they are situated and the utterance that the speaker produces.} \label{fig:semiotic-cycle} \end{figure} Setting up such grounded language game experiments requires taking into consideration a set of processes that has been referred to as \textit{the semiotic cycle} \cite{steels2012grounding}, and implementing each of the processes involved. During each game, the speaker and hearer move through this cycle as depicted in Figure \ref{fig:semiotic-cycle}. First, both agents perceive the world through their own sensors and construct an internal world model (\textit{grounding}). Then, the speaker determines which information needs to be conveyed to the hearer in order for the task to succeed and conceptualises it into a semantic structure (\textit{conceptualisation}). This meaning representation is then expressed through a linguistic expression that is passed to the hearer (\textit{production}). The hearer then parses the utterance into a meaning representation (\textit{comprehension}). He interprets the resulting semantic structure in relation with his world model and performs the relevant action (\textit{interpretation}). Finally, the speaker provides feedback on the outcome of the game, allowing both agents to update their individual knowledge. The described processes take place on three main levels: grounding on the sensori-motor level, conceptualisation and interpretation on the conceptual level, and production and comprehension on the language level. There are a number of tools available that can be used for implementing language game experiments. A general-purpose, widely used platform is \textit{NetLogo} \cite{netlogo}, which was developed as an educational tool to teach students about agent-based modelling. It is mainly targeting the complex systems science community and contains a large number of sample models on many topics. NetLogo provides an excellent architecture for setting up and monitoring multi-agent simulations but does not contain any built-in functionalities for implementing the processes involved in the semiotic cycle. \textit{NaminggamesAL} is a recent tool for implementing a variety of basic naming games in simulated worlds \cite{schueller2018}. It includes a multi-agent simulation framework and a number of built-in learning strategies, but lacks modules for implementing more advanced versions of the three levels of the semiotic cycle. A software tool that stems from the linguistic community is \textit{MoLE} (\textit{Modelling Language Evolution}) \cite{mole}. MoLE focuses on the language level and was especially designed for conducting experiments on the emergence of case \cite{lestrade_2016}. It includes the necessary building blocks for setting up multi-agent language games in which lexical items can be recruited as grammatical markers. It does not include an advanced semantic processing engine, an elaborate language processing engine, and interfaces to physical robots or rich world models. Finally, \textit{Babel} is a software package that was originally implemented as a testbed for research on the origins of language \cite{McIntyre:1998}. In its first version, it provided users with a basis for running computer simulations and allowed the rapid construction of experiments and a flexible visualisation of the results. Later versions of Babel (see \cite{steels2010babel, loetzsch2008babel2}) introduced more elaborate tools for setting up language games with advanced modules for dealing with the conceptual level (IRL -- \cite{steels00e, spranger2012irl}) and the language level (FCG -- \cite{steels2011design, steels2017basics}). Although Babel has often been used in grounded experiments, involving amongst others the AIBO dog-like robot \cite{steels2000aibo}, the QRIO humanoid \cite{spranger12perceptual} and the PERACT vision system \cite{vantrjip2016}, it has never included a standardised interface to connect to robotic platforms. The contribution of this paper is twofold. On the one hand, it introduces a high-level robot interface that extends the Babel software system, presenting for the first time a toolkit that provides flexible modules for dealing with each subtask involved in running advanced grounded language game experiments. On the other hand, it provides a practical guide to using the toolkit for implementing such experiments, taking a grounded colour naming game experiment as a didactic example. The remainder of this paper is structured as follows. Section \ref{sec:colour} introduces the challenges involved in establishing a shared colour lexicon and discusses the grounded colour naming game as a solution. Section \ref{sec:implementing-a-game} serves as a practical explanation of how this solution can be implemented on a high level using the Babel system. Finally, Section \ref{sec:robot-interface} provides more technical detail on the architecture and main features of the newly developed robot interface. \section{EMERGENT COMMUNICATION FOR THE COLOUR DOMAIN} \label{sec:colour} The goal of the colour naming game experiment is to show how a shared communication system for referring to objects by their colour can emerge in a population of autonomous agents. The agents start without any concepts or words, perceiving only the average colour values of the objects in the scene. In a real-world setting, transmitting raw sensor values does not lead to successful communication, because the sensors of each agent will always record slightly different values due to differences in the agents' perspectives on the scene, changes in lighting conditions and in some cases differences in robot morphology\footnote{Traditional sensor calibration is undesirable here, as it requires a notion of central control which conflicts with the autonomous nature of the agents.}. Therefore, concepts and words form the necessary layers to abstract away from sensor data, in order to achieve more robust communication. A large body of previous work has shown how colour categories and words can emerge through self-organisation in a population of autonomous agents, including robots \cite{steels2005coordinating,puglisi2008cultural,bleys2009grounded, bleys2016language,cornudella2016role}. In essence, the solution resides in the agents dividing their continuous colour space into convex regions that correspond to colour categories that are functional in the world, and in establishing a shared lexicon to refer to each region. An operationalisation of this solution has been proposed in the form of \textit{the grounded colour naming game experiment} \cite{steels2005coordinating}. Figure \ref{fig:naos} shows an instantiation of a grounded colour naming game. In this game, the world consists of a number of toy monsters, each with a different colour. Two randomly selected agents from the population are physically embodied in the two robots, one playing the role of speaker and the other the role of hearer. The task of the speaker is to use a vocalisation to draw the attention of the hearer to one of the monsters in the world. The task of the hearer is to point to this monster, signalling that he has understood the message. Finally, the speaker signals success if the hearer pointed to the right monster, or points himself if this was not the case. \begin{figure} \centering \includegraphics[width=\columnwidth]{img/IMG0888} \caption{Two Nao robots play a grounded colour naming game with a scene consisting of coloured monsters. For each game, two agents from the population are physically instantiated in the two robot bodies.} \label{fig:naos} \end{figure} Once the basic interaction script is in place, we can start experimenting with different mechanisms for inventing, adopting and aligning colour categories and words. Suppose that the orange robot in the back of Figure \ref{fig:naos} needs to refer to the green monster in front of him. As he enters the experiment without any colour categories or words, he needs to invent both a new category and a new word to express this category. He takes the observed colour value as the first prototypical value of this new category (e.g. [(7, 246, 9) $\leftrightarrow$ \texttt{CATEGORY-1}]) and associates the category with a newly generated word form, in this case ``fusemo", assigning to the association a default initial score (e.g. [\texttt{CATEGORY-1} $\leftrightarrow$ \textit{fusemo}]). He then utters the word to the hearer. The hearer does not know this newly invented word and is therefore unable to determine which monster the speaker is referring to. The speaker provides feedback by pointing to the green monster. At that point, the hearer associates the colour value that he observed for this object to a new category (e.g. [(5, 243, 2) $\leftrightarrow$ \texttt{CATEGORY-2}]) and associates this category to the word ``fusemo" with a default initial score (e.g. [\texttt{CATEGORY-2} $\leftrightarrow$ \textit{fusemo}]). Crucially, each association between a sensor value and a category, as well as between a category and a word form is internal to the individual agent and cannot be shared as such. While agents are able to invent new categories and words throughout the experiment, they will prefer to reuse existing ones. When a novel observation comes in, the agents will determine whether the category that is the closest in sensory distance to the observation discriminates the topic monster from the other monsters in the world. In other terms, they will calculate the distance between the observed sensory value and each of their categories, and select the closest one. Then, they verify that no other object is closer to this category, which means that the category uniquely discriminates the monster in the world. If no such category can be found, a new category is invented following the procedure explained in the previous paragraph. When it comes to the words, the speaker will always choose the word form most strongly associated with the selected category and the hearer will choose the category most strongly associated with the selected word form. When agents invent, adopt and reuse colour categories and words as described above, the categories of the agents never align and their vocabularies become enormous in size. To overcome this issue, speaker and hearer go through an alignment phase at the end of each interaction. If the interaction succeeds, the agents reinforce the association between the category and the word form that was used and punish competing associations. Moreover, they also slightly shift the prototypical value of the used category towards the observed sensor value. If the game fails, the agents punish the association that was used. Using these mechanisms for invention, adoption and alignment, a population of agents will eventually converge on a stable colour category system, and on a shared inventory of words for referring to these categories. Importantly, the emerged system is tailored towards the distinctions that are functional in the world, both in terms of number of categories and in the way in which the colour space is subdivided. The concrete mechanisms described in this section are the ones most commonly used in the literature. A complete overview of invention, adoption and alignment strategies that have been explored for the colour naming game falls outside the scope of this paper, but can be found in earlier work by Joris Bleys \cite{bleys2016language}. \section{IMPLEMENTING A GROUNDED COLOUR NAMING GAME EXPERIMENT} \label{sec:implementing-a-game} We will now demonstrate how the Babel toolkit can be used to implement a grounded colour naming game experiment like the one that was introduced in the previous section. Babel's experiment framework and submodules for dealing with the sensori-motor level, conceptual level and language level provide abstractions that allow specifying the game on a high level and in an intuitive way, while most technical detail is taken care of by the system itself \footnote{In this example experiment, all processes in the semiotic cycle are implemented using standard Babel modules. It is however perfectly possible to only use Babel modules for implementing some of these processes, and different software for the others.}. Actual source code that corresponds to the explanation in this section has become an integral part of the Babel toolkit\footnote{The complete source code for running the Grounded Colour Naming Game Experiment is part of the Babel toolkit and can be found in the subfolder \texttt{experiments/grounded-colour-naming-game-experiment}. A simulator mode has also been provided, to run the experiments if you do not have a Nao robot at your disposal.}, which can be obtained via \url{https://emergent-languages.org}. Additionally, an online web demonstration of the grounded colour naming game experiment is available at \url{https://ehai.ai.vub.ac.be/demos/babel-grounded-colour-naming-game-experiment}. \subsection{Multi-agent architecture} \label{sec:multi} Implementing a language game experiment involves keeping track of the agents in the population, selecting the agents to participate in each game, assigning them the role of speaker or hearer, and, most importantly, specifying the language game script according to which the agents will interact. Within Babel, the multi-agent simulation part of the experiment is handled by the `experiment-framework' submodule. The experiment framework is entirely customisable when it comes to how the population is structured, which and how many agents are selected for each interaction, how their role is determined and what an interaction looks like. For this grounded colour naming game experiment, we will make use of the experiment framework's default settings: a fully connected population structure, one speaker and one hearer per game, both randomly selected, and communicative success as a measure for evaluation. The interaction script itself is specified as shown in Listing \ref{interaction-script} and consists of the following steps (with the Babel function names between parentheses): \begin{enumerate} \item Two agents are downloaded into the robot bodies (\textsc{embody}) \item Both agents scan the world and construct their world model (\textsc{agent-observe-world}) \item The speaker chooses an object to refer to (\textsc{choose-topic}) \item The speaker conceptualises the topic in relation to his world model (\textsc{conceptualise}) \item The speaker chooses a word for the topic (\textsc{produce-utterance}) \item The speaker utters the word while the hearer is listening (\textsc{pass-utterance}) \item The hearer parses the observed word into a semantic structure (\textsc{comprehend-utterance}) \item The hearer interprets the semantic structure in relation to his world model (\textsc{interpret}) \item The hearer points to the hypothesized topic (\textsc{point-and-observe}) \item The speaker provides feedback by nodding (\textsc{agent-nod}) in case of success, or pointing (\textsc{point-and-observe}) in case of failure \item Both agents align (\textsc{align-agent}) \end{enumerate} \textsc{embody}, \textsc{agent-observe-world}, \textsc{pass-utterance}, \textsc{point-and-observe} and \textsc{agent-nod} all happen at the sensori-motor level; \textsc{choose-topic}, \textsc{conceptualise} and \textsc{interpret} at the conceptual level; and \textsc{produce-utterance} and \textsc{comprehend-utterance} at the language level. Finally, \textsc{align-agent} takes place on both the conceptual and the language level. \begin{figure} \begin{lstlisting}[caption=Interaction Script, label=interaction-script, basicstyle=\scriptsize\tt] (defmethod interact ((experiment gcng-experiment) interaction &key) (let ((speaker (speaker interaction)) (hearer (hearer interaction))) ;; 1 (embody speaker (first (robots experiment))) (embody hearer (second (robots experiment))) ;; 2 (agent-observe-world speaker) (agent-observe-world hearer) ;; 3 (choose-topic speaker (world speaker)) ;; 4 (conceptualise speaker (topic speaker) (world speaker)) ;; 5 (produce-utterance speaker (meaning-representation speaker)) ;; 6 (pass-utterance speaker hearer (utterance speaker)) ;; 7 (comprehend-utterance hearer (observed-utterance hearer)) ;; 8 (interpret hearer (meaning-representation hearer)) ;; 9 (point-and-observe hearer (hypothesized-topic hearer)) ;; 10 (if (communicated-successfully interaction) (agent-nod speaker) (point-and-observe speaker (topic speaker))) ;; 11 (align-agent speaker) (align-agent hearer))) \end{lstlisting} \end{figure} \subsection{Sensori-motor level \label{sec:perception-and-action} The agents' action and perception capabilities are handled at the sensori-motor level by Babel's `robot-interface' submodule, which is presented for the first time in this paper. The robot interface defines a standard set of functions that are particularly useful for conducting language games, for example scanning the robot's environment, speaking, listening and pointing. It abstracts away these high-level instructions from their specific implementation, which heavily depends on the hardware that is used, and is different for each type of robot. More technical detail can be found in Section \ref{sec:robot-interface} below, with an overview of the available functionality in Table \ref{tab:robot-interface}. In the example experiment presented in this paper, the robot interface makes use of the sensors and actuators of the Nao robotic platform. Concretely, the \textsc{embody} step embodies the speaker and hearer agents into the available robots. The \textsc{agent-observe-world} step uses the camera of the robot to make a picture of the scene, and uses the OpenCV library \cite{opencv_library} to construct a world model by segmenting the scene and extracting certain features for the objects, including their average colour value. \textsc{pass-utterance} lets one robot speak via text-to-speech while the other listens and performs speech recognition. \textsc{point-and-observe} is used by the hearer to indicate the hypothesized object. Finally, either \textsc{agent-nod} or \textsc{point-and-observe} is used by the speaker at the end of the game to signal success or provide feedback. \subsection{Conceptual level} \label{sec:conceptualisation-and-interpretation} Bridging the gap between the world model and the meaning that needs to be expressed by the speaker or interpreted by the hearer is handled at the conceptual level by Babel's `IRL' (Incremental Recruitment Language) submodule \cite{steels00e,spranger2012irl}. IRL implements a form of procedural semantics, which means that semantic representations consist of primitive operations that directly correspond to actual function calls, and which can be combined into semantic networks for expressing more complex meanings. In conceptualisation, the IRL engine uses a search process to compose such a semantic network that singles out a given topic in the current scene. In interpretation, the IRL engine executes the semantic network by calling the functions underlying the primitive operations and propagating the resulting values. Suppose that in this example experiment the speaker needs to refer to the green monster. \textsc{conceptualise} will then trigger the IRL engine to compose the smallest possible semantic network that uniquely discriminates the object by its colour, relying on the agent's ontology. As the present experiment is only concerned with basic colour categories, the semantic network will always consist of a single \textsc{filter-by-closest-colour} operation, in this case using \texttt{CATEGORY-1}, as shown in Figure \ref{fig:irl-example}. On the hearer's side, \textsc{interpret} calls the IRL engine to execute the semantic network that results from the comprehension process, also consisting here of a single \textsc{filter-by-closest-colour} operation, in order to retrieve the topic object. During the alignment phase at the end of a successful game, the prototypical value of the used categories in the speaker's and hearer's ontologies are updated by slightly shifting them towards the values that were observed in this game. \begin{figure} \centering \includegraphics[width=.75\columnwidth]{img/irl-example-network} \caption{The speaker's semantic network that singles out an object discriminating it by \texttt{CATEGORY-1}.} \label{fig:irl-example} \end{figure} For didactic purposes, only the very basic functionality of IRL is used in this experiment. For experiments that necessitate more complex semantic structures, we refer the reader to earlier work by Spranger (on spatial language) \cite{spranger2012grammar}, Bleys (on colour) \cite{bleys2016language} and Pauw (on quantification) \cite{pauw2012emergence}. \subsection{Language level} \label{sec:production-and-comprehension} The task of mapping between a semantic structure and an utterance is taken care of by Babel's `FCG' (Fluid Construction Grammar) submodule \cite{steels2011design, steels2017basics}. FCG performs this mapping based on emergent form-meaning pairings, in this context called constructions. On the form side, a construction can include any form-related features, such as word forms, morphological properties and word order constraints. On the meaning side, it can include any type of semantic information, for example (parts of) a semantic network composed at the conceptual level. In the example above, the speaker invented the word ``fusemo" to refer to the colour of the green monster. He will use FCG to create a new construction that maps between this word form and the semantic network that was the outcome of the conceptualisation process. The construction is initialised with a default entrenchment score of 0.50, as illustrated by Figure \ref{fig:fcg-example}. As the hearer had never heard this word before, after feedback he will create his own construction that maps between the observed word form ``fusemo" and the semantic network that results from conceptualising in his world model the object that was pointed at. If the necessary constructions are already in place, the speaker uses \textsc{produce-utterance} to find the word form most strongly associated to his meaning network and the hearer uses \textsc{comprehend-utterance} to retrieve the meaning network most strongly associated to the word form that he observed. \begin{figure} \centering \includegraphics[width=\columnwidth]{img/fusemo-cxn} \caption{The speaker's construction that maps between the word form ``fusemo" and its meaning.} \label{fig:fcg-example} \end{figure} During the alignment phase after a successful game, both agents will increase the entrenchment score of the constructions that they have used. The agents will also decrease the score of competing constructions, i.e. constructions that map the same meaning to other word forms in the case of the speaker, and constructions that map the same word form to other meanings in the case of the hearer. After a failed game, both agents decrease the score of the constructions that were applied. When the score of a construction reaches zero, the construction is removed from the agent's inventory. The constructions that are used in this didactic example are always direct mappings between a single word form and a complete meaning network. Moreover, a single construction always suffices to comprehend and produce an utterance. Examples of experiments that involve more complex linguistic structures can for example be found in previous work by Garcia Casademont (on hierarchical structures) \cite{garcia2016insight} and Beuls (on grammatical agreement) \cite{beuls2013agent}. \subsection{Running and monitoring experiments} The Babel toolkit comes with a `monitors' submodule that is designed to track a multitude of experimental parameters in real time. The data recorded during a series of experiments can be displayed using dynamically updating graphs or exported to data files for later data exploration. Experimental parameters that are typically tracked include communicative success, the number of constructions in the inventories of the interacting agents, the categories in their ontologies and the size of the semantic (IRL) and syntactic (FCG) search spaces. Figure \ref{fig:results} shows a graph that was created by the monitoring system during a single experimental run of the grounded colour naming game experiment. There were five agents in the population, communicating about six distinctly coloured monsters of which three were shown during each game. The x-axis represents the time dimension, indicating the total number of games that were played. The turquoise line indicates the average communicative success that was achieved over the last fifty games (left y-axis). At the beginning of the run, the communicative success equals zero as the agents start without any categories or words. Over the course of 250 games, it rises to 1, as the emerged communication system becomes powerful enough to solve the task. The ontology size (red line), i.e. the average number of categories per agent, starts at zero and goes to six in just over 100 games (right y-axis). This number is optimal for this experimental set-up, as there are indeed six colour distinctions that are useful in the world. The average lexicon size (dark yellow line) clearly shows how the agents locally introduce new words (leading to 13 different forms), before gradually converging on the optimal number of six words, one for each category (right y-axis). The blue line tracks the average number of forms per meaning in the population (right y-axis). In the phase in which many words are being invented, this number reaches its maximum, after which it gradually declines to a single form for each meaning. The green line shows the opposite, namely the average number of meanings per form (right y-axis). While the agents are still building up their ontologies, it can happen that two word forms get associated to the same meaning. As an effect of alignment, the meaning-per-form ratio gradually decreases to 1. \begin{figure} \includegraphics[width=\columnwidth]{img/1-serie-500-games} \caption{A graph showing the results of monitoring a single experimental run of the grounded colour naming game experiment. The population consists of five agents that develop a communication system to refer to six distinctly coloured monsters.} \label{fig:results} \end{figure} \begin{figure}[h!] \centering \begin{subfigure}{\columnwidth} \includegraphics[width=.5\columnwidth]{img/series-1-interaction-10-agent-3} \end{subfigure} \begin{subfigure}{\columnwidth} \includegraphics[width=.65\columnwidth]{img/series-1-interaction-20-agent-3} \end{subfigure} \begin{subfigure}{\columnwidth} \includegraphics[width=.8\columnwidth]{img/series-1-interaction-40-agent-3} \end{subfigure} \begin{subfigure}{\columnwidth} \includegraphics[width=\columnwidth]{img/series-1-interaction-100-agent-3} \end{subfigure} \begin{subfigure}{\columnwidth} \includegraphics[width=\columnwidth]{img/series-1-interaction-250-agent-3} \end{subfigure} \caption{A visualisation of agent 3's colour lexicon after 10, 20, 40, 100 and 250 games. Note that the word ``ponuro" was first exclusively used to refer to blueish objects (interaction 10) and was later also used to refer to reddish objects (interaction 40). In the end, the form did not survive, as the population converged on ``rilala" and ``sobele" for referring to reddish and blueish objects respectively (interaction 250).} \label{fig:colour-lexicons} \end{figure} A different kind of visualisation that was created using the monitoring system is presented in Figure \ref{fig:colour-lexicons}. Each row in the figure shows a snapshot of single agent's ontology of colour categories and their associated word forms at a specific point in time. In this case, the ontology and word forms of agent 3 are shown after 10, 20, 40, 100 and 250 interactions. We can see how the agent gradually distinguishes more colour categories, until he reaches the optimal number of six. We can also observe that after 100 interactions, the agent has learned multiple words for certain colour categories, but that most have already disappeared after 250 interactions. The rise and fall of the word ``ponuro'' is particularly interesting. It was first exclusively used to refer to blueish objects (interaction 10), was then also associated to the colour category used to refer to reddish objects (interaction 40), but dies out as the population has converged on the words ``ribala'' and ``sobele'' to refer to reddish and blueish objects respectively (interaction 250). Babel's monitoring system can in real-time track, aggregate and visualise series of experiments that are run in parallel, and can easily be extended to record other experimental parameters or measures. \section{THE ROBOT INTERFACE: TECHNICAL SPECIFICATION} \label{sec:robot-interface} The robot interface is a newly developed part of the Babel software system, facilitating the implementation of processes that take place at the sensori-motor level of the semiotic cycle. It allows Babel users to seamlessly integrate the use of physical robot bodies in their language game experiments, by providing a hardware-independent interface to the functionality that is most frequently used in language games. This section first gives an overview of the general architecture of the robot interface, and then describes how it can be concretely used in combination with the Nao hardware that was employed in the experiment reported in the previous section. \subsection{General architecture} The robot interface standardises a number of core capabilities that can be exerted by a wide range of robotic platforms, abstracting away from their low-level implementation details. An overview of the most relevant capabilities, such as speaking, listening and pointing, is presented in Table \ref{tab:robot-interface}. \begin{table} \caption{Selected functions from the Babel robot interface API.} \begin{tabular}{lll} \toprule \textbf{Function} & \textbf{Arguments} & \textbf{Return value}\\ \midrule \textsc{make-robot} & ip-address, port, type & robot-connection \\ \midrule \textsc{observe-world} & robot-connection & world-model\\ \midrule \textsc{speak} & robot-connection, utterance & boolean \\ \textsc{hear} & robot-connection & perceived-utterance \\ \midrule \textsc{point} & robot-connection, arm & boolean \\ \textsc{nod} & robot-connection & boolean \\ \textsc{shake-head} & robot-connection & boolean \\ \textsc{look-direction} & robot-connection, dir, angle & boolean \\ \bottomrule \end{tabular} \label{tab:robot-interface} \end{table} In order to be able to use the robot interface, a robot-connection object of a specific type needs to be created first. This is done using the function \textsc{make-robot}, which takes an IP address, a port number and a type of robot (e.g. `nao') as input and returns a robot-connection object specialised towards this type of robot. Each of the available capabilities is then implemented as a Common Lisp generic function, with methods specialising on the subtype of the robot-connection object. This means for instance that when a certain capability is called with a robot-connection of type `nao' as its first argument, the call will automatically be dispatched to the method that implements this capability specifically for the Nao robot. A didactic example of how such a capability can be implemented is shown in Listing \ref{speak}. The example shows how the general \textsc{speak} capability is implemented as a generic function, while a call to this function with as first argument a connection of type `nao' will automatically be routed to the method just below. This general architecture ensures that the robot interface is easily extensible, both in terms of adding additional functionality and in terms of extending the existing functionality to different robotic platforms. \begin{lstlisting}[caption=Didactic example of the implementation of the speaking capability on a Nao robot., label=speak, basicstyle=\scriptsize\tt] (defgeneric speak (robot-connection utterance) (:documentation ``The robot says the utterance.'')) (defmethod speak ((nao nao) (utterance string)) ``Sending the utterance to the Nao's speech endpoint, returning a boolean that indicates success or failure.'' (rest (assoc :success (nao-send-data nao :endpoint ``/speech/say'' :data `((speech . ,utterance)))))) \end{lstlisting} When setting up a grounded language game experiment like the one reported on in this paper, it suffices to create one robot-connection object per robot body, at the beginning of the experiment. At the start of each communicative interaction, the \textsc{embody} step (see Section \ref{sec:multi}) will then assure that the speaker and hearer agents sense and act through the right robot body during this game, by associating them to one of these robot-connection objects. This avoids opening and closing a connection for every interaction. \subsection{Using the Nao robot} The experiment described earlier in this paper used the robot interface to play grounded colour naming games using two humanoid robots of the Nao type\footnote{\url{https://www.softbankrobotics.com/emea/en/nao}}. Nao robots run a GNU/linux-based operating system, called \textit{NaoQi OS}, and can be controlled from an external computer using the \textit{NaoQi framework}, available either as a C++ or a Python library. On the computer that runs the Babel software system, we set up a Docker container running a Python (Flask) server. This server exposes a RESTful API that continuously listens to HTTP requests, transforming them into concrete instructions that are passed to the right Nao robot using the Python version of the NaoQi framework. When a function from the Babel robot-interface API is called during an experiment, an HTTP POST request containing the necessary information is sent to the Python server's endpoint that handles the capability associated to this function. Suppose for example that the function \textsc{speak} is called with as arguments a robot-connection object and an utterance. Babel's robot interface will then send an HTTP POST request containing a JSON object holding the IP address and port of the Nao associated to the robot-connection object, as well as the utterance to pronounce, to the \texttt{/speech/say} endpoint of the Python server running in the Docker container. The Python server will parse the request and call a function from the NaoQi framework that makes the robot say the utterance and will return a JSON object containing a key `success' with a boolean value. A visual depiction of this system architecture is shown in Figure~\ref{fig:nao-interface}. \begin{figure} \includegraphics[width=\columnwidth]{img/robot-interface} \caption{When a function of the Babel robot interface API is called during an experiment, an HTTP POST request is send to a Python server running in a Docker container. The Python server then uses the NaoQi framework to communicate the request to the Nao robot.} \label{fig:nao-interface} \end{figure} \section{CONCLUSION} \label{sec:conclusion} Grounded language game experiments form an excellent tool to study emergent communication and its underlying mechanisms. Setting up such experiments, in which a rich system for communicating about the real word emerges, requires implementing each process involved in the semiotic cycle, encompassing the sensori-motor, conceptual and language levels. This paper has introduced a high-level interface that allows making use of physical robots for operationalising the grounding processes on the sensori-motor level. This interface has been fully integrated into the Babel software system, which, as a result, now includes software modules that facilitate the implementation of all processes involved in the semiotic cycle. This paper has also presented a practical guide to using the Babel toolkit for setting up full-cycle experiments, taking the grounded colour naming game as didactic example. \section*{ACKNOWLEDGEMENTS} We would like to thank Remi van Trijp, Katie Mudd and Yannick Jadoul for their valuable comments on earlier versions of this paper. We are also grateful to the three anonymous reviewers of the AISB Symposium on Grounded Language Learning for Artificial Agents for their encouraging feedback and appreciation. This work was supported by the Research Foundation Flanders (FWO) through grants 1SB6219N and G0D6915N (CHIST-ERA ATLANTIS) and by the European Union's Horizon 2020 research and innovation programme under grant agreement No 732942 (ODYCCEUS).
{'timestamp': '2020-04-21T02:25:45', 'yymm': '2004', 'arxiv_id': '2004.09218', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09218'}
arxiv
\section{Introduction} Despite of many attempts \cite{Saxe,Choromanska, Kadmon,Advani, LinTegmarkRolnick, Bottleneck2} the effectiveness of deep learning has so far no clear explanation. This is rather surprising given that a neural network is a very simple and a well-defined mathematical object \cite{Galushkin, Schmidhuber, Haykin}. What makes it difficult to analyze is that the deep neural networks are typically described with a very large number of parameters, e.g. weight matrix, bias vector, training data, etc. For such systems most of the analytical techniques are not very useful and one must rely on numerics. The situation is very similar to what happens in physics. Physical systems (both classical and quantum) can often be solved exactly when the number of degrees of freedom is small, but the problem becomes intractable when the number of degrees of freedom is large. Fortunately, there is a set of ideas which proved very useful for analyzing physical systems with many degrees of freedom. It is statistical mechanics. The main point of the present paper is to apply the methods of statistical mechanics to machine learning. In the remainder of this section, we will summarize the main results as it might help the reader to navigate through the paper. In Sec. \ref{sec:septuple} we set the stage by defining a neural septuple (i.e. state vector, input/output projection operators, weight matrix, bias vector, activation map and loss function). The septuple is not equivalent to the standard neural architecture used in machine learning, but it does include such systems as a special limit. There are three main motivations to define these more general structures. First of all, we want to develop a unified treatment of different types of learning algorithms, i.e. supervised, unsupervised, etc. Secondly, we want the very structure of hidden layers to be a dynamical variable in addition to the weight matrices and bias vectors. And finally, we want to have a theoretical framework which is suitable for a statistical description. In Sec. \ref{sec:unsupervised} we address the main problem of unsupervised learning, namely, what should be an appropriate loss function if the training dataset contains only input, but no output data. We claim that an answer can be obtained by defining a local error and a local objective for hidden neurons (or in the bulk) instead of a more conventional error for output neurons (or on the boundary). The boundary loss is usually given by a sum over errors on the boundary (i.e. over input/output neurons), but the bulk loss could be a sum over both local errors and local objectives in the bulk (i.e. over hidden neurons). A simple example of a local objective for a neuron is a binary classification of an incoming signal, and then an outgoing signal with values closer to lower- and upper-bounds are rewarded and values in-between are penalized. In Sec. \ref{sec:ensemble} we consider two statistical ensembles over state vectors: a micro-canonical-type ensemble and a canonical-type ensemble. We expect that in the limit of a large number of neurons the two ensembles are equivalent, as is usually the case in statistical physics, but the latter ensemble (i.e. canonical ensemble) is a lot easier to handle analytically. Moreover, we show that the canonical ensemble can be derived from the Jaynes' maximum entropy principle \cite{Jaynes,Jaynes2}. The principle states that the probability distribution (in our case statistical ensemble) which best represents the current state of knowledge is the one with the largest Shannon entropy. In Sec. \ref{sec:partition} we define perhaps the most important object in statistical mechanics - a partition function. For a bulk loss with (or without) a quadratic local objective the canonical ensemble can be approximated by a Gaussian integral and then the (canonical) partition function can be calculated analytically. A minor complication is that the range of integration (which is set by the range of an activation function) is finite in contrast to the Gaussian integral whose range is infinite. Nevertheless, the problem can be solved by replacing the sharp cut-off on the boundaries of integration with a smooth Gaussian window function. In this section we also define an operator $\hat{G}$ whose spectrum determines the canonical partition function and plays a central role in everything that follows. In Sec. \ref{sec:equilibrium} we define a time-invariant state of equilibrium (or what we call a learning equilibrium) and show that in such state the partition function must factorize into product of two factors: a function of the temperature and a function of the bias vector and weight matrix. Among other things it implies that the total free energy is a difference of two terms: a familiar thermodynamic free energy and an unfamiliar product of the temperature and a complexity function. While the thermodynamic free energy is a function of only temperature and usually decreases, the total free energy is expected to increase with learning due to a decrease in the complexity function. This might sound odd, but, in fact, is a mare consequence of an openness of the learning system where the entropy is flowing out of the system. In Sec. \ref{sec:thermodynamics} we calculate the total entropy of the canonical ensemble and argue that in an equilibrium it must be a sum of a familiar thermodynamic entropy and of an unfamiliar complexity function which is directly related to a dynamical dimensional reduction of the state space. We then argue that the total entropy must decrease until the systems reaches an equilibrium (i.e. the second law of learning \eqref{eq:second_law}) and the increment in the loss function must be proportional to the increment in the thermodynamic entropy plus the increment in the complexity (i.e. the first law of learning \eqref{eq:first_law}). In Sec. \ref{sec:architecture} we calculate a non-equilibrium production of the Shannon entropy (of a probability distribution function over weight matrices and bias vectors) and argue that in an optimal neural architecture the entropy production must be maximized (or, more precisely, the entropy destruction should be minimized). This is in a complete agreement with the so-called stationary entropy production principle that was used in \cite{entropic} to derive an approximate Schr\"odinger equation from a highly constrained stochastic process and in \cite{emergentgravity} to derive an approximate Einstein equation from non-equilibrium thermodynamics of the metric tensor. We then show that the rate of the entropy production is proportional to the Laplacian of the free energy in the configuration space of the weight matrices and bias vectors. In Sec. \ref{sec:deep_shallow} we used the criteria of minimizing the entropy destruction (or minimizing the negative Laplacian of the free energy) to derive an expected dynamics of a spectrum of operator $\hat{G}$ in an optimal neural architecture. In particular, we show that most of the eigenvalues of the operator $\log \hat{G}$ should remain near zero, a small fraction of the largest eigenvalues should move to positive values $\gtrsim 0$ and a very small fraction of eigenvalues should move to very small values $\ll 0$. This implies that the effectiveness of a neural network can be translate into a skewness of the distribution of eigenvalues of $\log \hat{G}$, i.e. the larger the skewness the better a neural network is expected to perform. Then we show that the skewness in a deep architecture is much larger than in a shallow architecture which demonstrates why the deep architecture is preferred. In Sec. \ref{sec:numerics} we discuss the main results of numerical experiments conducted using the TensorFlow Python library \cite{TensorFlow} and MNIST database of handwritten images \cite{MNIST}. Two different neural networks (a deep network with two hidden layers and a shallow network with a single hidden layer) were trained using the method of stochastic gradient descent and then the numerical data were analyzed in context of the analytical calculations carried out in the paper. More specifically, the training evolution of the bulk and boundary loss functions progressed as expected, the predicted dynamics of the spectrum of operator $ \hat{G}$ was established, and the anticipated relaxation of the complexity function towards equilibrium was confirmed. And finally in Sec. \ref{sec:entropic} and Sec. \ref{sec:gravity} we discuss a possibility that the entire universe on its most fundamental level is a neural network. For such an ambitious proposal to actually work we claim that the three components: quantum mechanics, general relativity and macroscopic observers must all emerge from a microscopic neural network. For the time being, we leave aside the problem of observers (see, however, \cite{Tononi}) and study a possible emergence of quantum mechanics and general relativity. In particular, we show that approximate Schr\"odinger equation (see Sec. \ref{sec:entropic}) and Einstein equations (see Sec. \ref{sec:gravity}) can indeed emerge from a network with a large number of neurons not too far from a learning equilibrium. \section{Neural septuple}\label{sec:septuple} We start by introducing all of the essential ingredients of a neural network or, what we shall call, a neural septuple consisting of: (1) ${\bf x}$, a state vector which describes the state of all neurons, (2) $\hat{P}_{in}$, an input projection which describes a subspace spanned by input neurons, (3) $\hat{P}_{out}$, an output projection which describes a subspace spanned by output neurons, (4) $\hat{w}$, a weight matrix which describes directed connections between all pairs of neurons, (5) ${\bf b}$, a bias vector which describes biases in the inputs of all neurons, (6) ${\bf f}$ , an activation map which describes a non-linear transformation, and (7) ${H}$, a loss function which describes a learning objective of the entire network. \\ Consider a collection of $N$ neurons described by a column\footnote{We adopt the physicists' notations where the state vector is a column vector and not a row vector which is usually used in the machine learning literature.} {\it state vector}, ${\bf x} \in \mathbb{R}^N $, whose components are real numbers, $x_i \in \mathbb{R} $, but one can also generalize the construction to complex numbers or other fields. There are three types of neurons: input neurons, hidden neurons and output neurons, and so it is convenient to define three subspaces of the state space: input subspace ${\cal V}_{in}$, output subspace ${\cal V}_{out}$ and hidden subspace ${\cal V}_{hid}$. We shall also refer to the direct sum of the input and output subspaces, ${\cal V}_{in}\oplus {\cal V}_{out}$, as a boundary and to the hidden subspace, ${\cal V}_{hid}$, as a bulk. A neural network is trained by specifying the components of ${\bf x}$ in the boundary subspace which represent only the input and output neurons. The boundary components can be described with two projection operators (or matrices): an {\it input projection} $\hat{P}_{in}$ and an {\it output projection} $\hat{P}_{out}$. These operators can be used to project a state vector ${\bf x}$ to either input subspace, i.e. $\hat{P}_{in}{\bf x} \in {\cal V}_{in}$, output subspace, i.e. $\hat{P}_{out}{\bf x} \in {\cal V}_{out}$, boundary subspace, i.e. $( \hat{P}_{in}+\hat{P}_{out} ) {\bf x} \in {\cal V}_{in}\oplus {\cal V}_{out}$, or bulk subspace, i.e. $(\hat{I} - \hat{P}_{in}-\hat{P}_{out} ) {\bf x} \in {\cal V}_{hid}$. The neurons are connected into a neural network with connections described by a {\it weight matrix}, $\hat{w}$, which is also an adjacency matrix of a weighted directed graph with individual neurons representing the nodes of the graph. For the neural networks considered here the components of the weight matrix are assumed to be real numbers, $w_{ij} \in \mathbb{R}$, but one can also generalize the construction to complex numbers or other fields. In addition, for the so-called feedforward neural network with $L$ layers (i.e. one input layer, one output layer and $L-2$ hidden layers) the weight matrix is taken to be nilpotent, i.e. \begin{equation} \hat{w}^n = \left ( \hat{w}^T \right )^n = 0 \;\;\;\forall n \ge L, \label{eq:nilpotent} \end{equation} there are no incoming connections to the input neurons, i.e. \begin{equation} \hat{P}_{in} \hat{w}=0, \end{equation} and there are no outgoing connections from the output neurons, i.e. \begin{equation} \hat{P}_{out} \hat{w}^T=0. \end{equation} The state vector can only change when either a new training data $\hat{P}_{in} {\bf x}_\partial \in {\cal V}_{in}$ are entered, \begin{eqnarray} {\bf x}(0) =\hat{P}_{in} {\bf x}_\partial \label{eq:initial_conditions} \end{eqnarray} or the new data propagate through the network \begin{equation} {\bf x}({t+1}) = {\bf f} \left ( \hat{w} {\bf x}(t)+ {\bf b} \right) \label{eq:eom}. \end{equation} The vector ${\bf b} \in \mathbb{R}^N$ is a {\it bias vector} and ${\bf f}: \mathbb{R}^N \rightarrow \mathbb{R}^N$ is an {\it activation map} which acts separately on each component, i.e. \begin{equation} f_i( {\bf y}) = f_i\left (y_i \right ). \label{eq: activation} \end{equation} where $f_i(y)$'s are the activation functions (e.g. $f_i(y) = \tanh(y)$, $f_i(y) =\max(0,y)$). For the input neurons with no incoming connections to remain fixed, i.e. \begin{equation} \hat{P}_{in} {\bf x}({t}) = \hat{P}_{in} {\bf x}({0})= {\bf x}({0})=\hat{P}_{in} {\bf x}_\partial, \label{eq:input_constraint} \end{equation} an additional condition must also be imposed on the input bias, \begin{equation} {\bf f} \left (\hat{P}_{in} {\bf b} \right )= \hat{P}_{in} {\bf x}_\partial .\label{eq:bias_constraint} \end{equation} This condition is satisfied for a feedforward neural network, but need not be satisfied for more general learning systems. After a finite number of steps $t$ the state vector ${\bf x}(t)$ may converge to a fixed state ${\bf x}(t)=\bar{\bf x}$ defined by a fixed point equation \begin{equation} \bar{\bf x} = {\bf f} \left ( \hat{w} \bar{\bf x}+ {\bf b} \right). \label{eq:fixed_point} \end{equation} For example, in a deep feedforward neural network with $L$ layers the fixed state would be reached after $L-1$ steps, i.e. ${\bf x}({L-1})=\bar{\bf x}$, given that the condition on the input bias \eqref{eq:bias_constraint} is satisfied. For more general systems the state may or may not converge to a fixed point depending on the activation transformation \eqref{eq:eom} and initial conditions \eqref{eq:initial_conditions}. The final ingredient of a neural septuple is a loss function. In a feedforward neural network the loss function is usually defined by projecting the fixed state $\bar{\bf x}$ to the output subspace $\hat{P}_{out} \bar{\bf x} \in {\cal V}_{out}$ and then by comparing the result with a desired output state $\hat{P}_{out} {\bf x}_\partial \in {\cal V}_{out}$. For example, one can define a loss function as a squared error of the output neurons, \begin{eqnarray} H_{\partial}(\bar{\bf x}, {\bf b}, \hat{w}) & = & \left ( \hat{P}_{out} \bar{\bf x} - \hat{P}_{out} {\bf x}_\partial \right )^T \left ( \hat{P}_{out} \bar{\bf x} - \hat{P}_{out} {\bf x}_\partial \right ) \label{eq:square_error}\\ & = & \left ( \bar{\bf x} - {\bf x}_\partial \right )^T \hat{P}_{out}^T \hat{P}_{out} \left ( \bar{\bf x} - {\bf x}_\partial \right )\notag\\ & = & \left ( \bar{\bf x} - {\bf x}_\partial \right )^T \hat{P}_{out} \left ( \bar{\bf x} - {\bf x}_\partial \right ).\notag \end{eqnarray} Since there is no error on the input neurons \eqref{eq:input_constraint} we can also rewrite it as a squared error on all boundary (i.e. input and output) neurons \begin{equation} H_\partial(\bar{\bf x},{\bf b}, \hat{w}) = \frac{1}{2} \left ( \bar{\bf x} - {\bf x}_\partial \right )^T ( \hat{P}_{in}+ \hat{P}_{out} ) \left ( \bar{\bf x} - {\bf x}_\partial \right ). \label{eq:boundary_error} \end{equation} For this reason, we shall refer to $H_\partial$ as a boundary loss function. \section{Supervised vs. unsupervised}\label{sec:unsupervised} In the pervious section we defined a neural network as a neural septuple $\left ( {\bf x}, \hat{P}_{in}, \hat{P}_{out}, \hat{w} , {\bf b}, {\bf f}, H \right )$ where $ {\bf x}$ is a state vector of all (input, output and hidden) neurons, $ \hat{P}_{in}{\bf x}$ is a state of only input neurons, $ \hat{P}_{out}{\bf x}$ is a state of only output neurons, $ \hat{w}$ is a weight matrix between all pairs of neurons, ${\bf b}$ is a bias vector for all neurons, ${\bf f}({\bf y})$ is an activation map and $H({\bf x}, {\bf b}, \hat{w})$ is a loss function. A simple example of a loss function is the boundary loss \eqref{eq:boundary_error} which is known to work very well in a supervised learning. Unfortunately, the boundary loss cannot be used in unsupervised systems where the output subspace is empty, ${\cal V}_{out}= \emptyset$, and thus the boundary loss is always zero, $H=H_\partial=0$.\footnote{In our description an auto-encoder is viewed as a supervised system with periodic boundary conditions, i.e. the input and output states are set equal to each other.} For this reason, in unsupervised systems (beyond auto-encoders) we must consider other loss functions which are, perhaps, more general than the boundary loss. A key observation is that in equation \eqref{eq:boundary_error} the boundary loss was due to a mismatch in the output conditions or (together with input conditions) in the boundary conditions, i.e. $( \hat{P}_{in}+ \hat{P}_{out})\bar{\bf x} \neq {\bf x}_\partial$, but the fixed point equation \eqref{eq:fixed_point} was satisfied exactly. Alternatively, we can assume that the boundary conditions are satisfied exactly $ ( \hat{P}_{in}+ \hat{P}_{out} ) {\bf x} = {\bf x}_\partial$, but the fixed point equation is only approximate. Then we can define a bulk loss (as opposed to the boundary loss) as a sum of squares of errors in the fixed point equation, i.e. \begin{equation} H(\bar{\bf x}, {\bf b}, \hat{w}) = \frac{1}{2} \left ( \bar{\bf x} - {\bf f} \left ( \hat{w} \bar{\bf x}+ {\bf b} \right) \right )^T \left ( \bar{\bf x} - {\bf f} \left ( \hat{w} \bar{\bf x}+ {\bf b} \right) \right ), \label{eq:bulk_error} \end{equation} where $\bar{\bf x}$ is the value of $\bf x$ at a minimum of $H({\bf x}, {\bf b}, \hat{w})$ subject to boundary conditions $ ( \hat{P}_{in}+ \hat{P}_{out} ) {\bf x} = {\bf x}_\partial$, i.e. \begin{equation} H(\bar{\bf x}, {\bf b}, \hat{w}) = \min_{ ( \hat{P}_{in}+ \hat{P}_{out} ) {\bf x} = {\bf x}_\partial} H({\bf x}, {\bf b}, \hat{w}). \label{eq:minima} \end{equation} This is the simplest bulk loss\footnote{This bulk loss function is similar in spirit (but not the same) to the error calculated in the back-propagation algorithm where the error on the output neurons is back-propagated to the hidden neurons.} which is still zero for unsupervised feedforward neural networks, but can be easily generalized to functions which can be used in both supervised and unsupervised learning. The main idea is that, from the point of view of an individual neuron, a (more general) learning objective can be modeled as a minimization of a local error and at the same time a maximization of a local objective. It is convenient to think of the local error as a supervised quantity (e.g. $(\bar{x}_i - f_i ( \sum_{j} w_{ij} \bar{x}_j + b_i ))^2$ in the bulk loss function \eqref{eq:bulk_error}) and of the local objective as a (yet to be defined) unsupervised quantity. Then even if the local error is already at its minimum (as is always the case for unsupervised feedforward neural networks) there is still another quantity which needs to be extremized, i.e. the local objective. This does not mean that the inclusion of the local objective would only benefit an unsupervised learning. Once an appropriate local objective is identified it can be incorporated into a (bulk or boundary) loss function to improve the convergence of a learning algorithm. For example, the local objective might be a binary classification of an incoming signal $\sum_{j} w_{ij} \bar{x}_j + p_j$ and then the values of $\bar{x}_i$ closer to lower- and upper-bounds should be rewarded and values in-between should be penalized. Such a classification objective can always be modeled with an appropriately chosen ``potential'' term for each neuron. For example if \begin{equation} { V}(\bar{\bf x}) = \sum_i V_i(\bar{x}_i) = - \sum_i \frac{m}{2} \bar{x}_i^2 \label{eq:tachyon} \end{equation} then the bulk loss function can be defined as \begin{eqnarray} H(\bar{\bf x}, {\bf b}, \hat{w}) &=& \frac{1}{2} \left ( \bar{\bf x} - {\bf f} \left ( \hat{w} \bar{\bf x}+ {\bf b} \right) \right )^T \left ( \bar{\bf x} - {\bf f} \left ( \hat{w} \bar{\bf x}+ {\bf b} \right) \right ) + { V}(\bar{\bf x}) \label{eq:bulk_loss} \\ &=& \frac{1}{2} \sum_i \left[ \left (\bar{x}_i - f_i \left ( \sum_{j} w_{ij} \bar{x}_j + p_j \right ) \right )^2 - {m}\bar{x}_i^2 \right ].\notag \end{eqnarray} By minimizing this loss function we accomplish both tasks: the minimization of the local error and maximization of the local objective (in this case the binary classification objective). Note that the ``tachyonic potential'' \eqref{eq:tachyon} does not lead to any runaway solutions if the range of $\bar{x}_i$ is bounded by the range of the activation function. For example, if the activation function is $f(y)=\tanh(y)$ then $x_i \in (-1,1)$. More generally, any two (or more) neurons might have a common objective and then the potential term must also include ``interactions'', i.e. ${V} (\bar{\bf x}) =\sum_i V_i(\bar{x}_i)+ \sum_{ij} g^{ij} \bar{x}_i \bar{x}_j ...\;$. In either case, according to \eqref{eq:minima}, the corresponding learning objective remains the same, i.e. we must adjust $\hat{w}$ and ${\bf b}$ in such a way that for a given set of boundary condition $( \hat{P}_{in}+ \hat{P}_{out} ) \bar{\bf x}={\bf x}_\partial$ the bulk loss function is minimized. What is, however, different is that the bulk loss function $H({\bf x}, {\bf b}, \hat{w})$ is now given by \eqref{eq:bulk_loss} which contains both a local error (a supervised or a kinetic term) and a local objective (an unsupervised or a potential term). As a result, the corresponding bulk loss function is well-defined and (generically) non-zero for both supervised and unsupervised systems. Unfortunately, a solution of equation \eqref{eq:minima} is difficult to obtain exactly and so the statistical methods must be employed. \section{Statistical ensembles}\label{sec:ensemble} There are basically two ways to proceed: experimental (based on numerics) or theoretical (based on statistics). We will start with statistical approach as it might assist us in numerical searches. For starters, consider a statistical ensemble of boundary conditions or, more precisely, a probability distribution ${p}_\partial({\bf x}_\partial)$ over components of the state vector in the boundary subspace ${\bf x}_\partial=( \hat{P}_{in}+ \hat{P}_{out} ) {\bf x}$. Such a distribution can, for example, be extracted from a training dataset. Then, instead of minimizing a loss function for individual boundary data, the learning objective could be to minimize an ensemble-averaged loss function, i.e. \begin{equation} U_0({\bf b}, \hat{w}) \equiv \int d^{N_\partial} x_\partial \min_{( \hat{P}_{in}+ \hat{P}_{out} ) {\bf x} = {\bf x}_\partial} H({\bf x}, {\bf b}, \hat{w}){p}_\partial({\bf x}_\partial) \end{equation} where $N_\partial \le N$ is the dimensionality of the boundary subspace. If we now extend the probability distribution into the bulk by defining \begin{equation} {p}_0({\bf x}) = {p}_\partial(( \hat{P}_{in}+ \hat{P}_{out} ) {\bf x}) \delta\left (\bar{\bf x}-{\bf x}\right ),\label{eq:microcanonical} \end{equation} where $\bar{\bf x}$ is given by \eqref{eq:minima}, then the ensemble-averaged loss function is simply \begin{equation} U_0({\bf b}, \hat{w}) = \int d^{N} x H({\bf x}, {\bf b}, \hat{w}){p}_0({\bf x}). \label{eq:constraint0} \end{equation} Of course, all that we did is moved the difficulty of calculating $\bar{\bf x}$ into ${p}_0({\bf x})$, but that does not solve the main problem. It is still a computationally intensive task to calculate $ U_0({\bf b}, \hat{w})$ exactly and this is where statistical mechanics comes to rescue. The key idea is to replace the micro-canonical-type ensemble \eqref{eq:microcanonical} with a canonical-type ensemble \eqref{eq:canonical}. Note that for sufficiently large systems (in our case large neural networks) one can often show that the two ensembles are equivalent (i.e. predictions are identical) but the canonical ensemble is much easier to handle analytically. Consider a statistical ensemble of neural networks, or a probability distribution ${p}({\bf x})$, over state vectors ${\bf x}$. Let's say we do not know how the network was trained (i.e. which algorithm was used), but we do know that the ensemble-averaged bulk loss $H({\bf x}, {\bf b}, \hat{w})$ was reduced to some fixed value, \begin{equation} U({\bf b}, \hat{w}) = \int d^{N} x H({\bf x}, {\bf b}, \hat{w}){p}({\bf x}). \label{eq:constraint1} \end{equation} Then according to the principle of maximum entropy \cite{Jaynes, Jaynes2}, the most reasonable distribution ${p}({\bf x})$ is a distribution which has the largest Shannon entropy \begin{equation} S({p}) \equiv - \int d^{N} x \; {p}({\bf x}) \log {p}({\bf x}) = - \langle \log {p}({\bf x}) \rangle . \label{eq:entropy} \end{equation} subject to constraint \eqref{eq:constraint1}. The maximization problem can be solved using the method of Lagrange multipliers. If we define a ``Lagrangian'' \begin{eqnarray} {L}({p}, \beta, \nu) &=& S({p}) + \beta \left ( U({\bf b}, \hat{w}) - \int d^{N} x \; {p}({\bf x}) H ({\bf x}, {\bf b}, \hat{w}) \right ) +\nu \left (1- \int d^{N} x \; {p}({\bf x}) \right ),\notag\\ &=& \int d^{N} x \; {p}({\bf x}) \left ( - \log {p}({\bf x}) - \beta H({\bf x}, {\bf b}, \hat{w}) - \nu \right ) + \beta U({\bf b}, \hat{w}) +\nu\label{eq:Lagrangian} \end{eqnarray} then at a maximum of $ L({p}, \beta, \nu)$ the variations with respect to ${p}({\bf x}) $, $\beta$ and $\nu$ must vanish \begin{eqnarray} 0 &=& \frac{\delta {L}({p}, \beta, \nu)}{\delta {p}({\bf x}) } = - \beta H({\bf x}, {\bf b}, \hat{w}) - \log {p}({\bf x}) - 1 - \nu\\ 0 &=& \frac{\partial { L}({p}, \beta, \nu)}{ \partial \beta} = U({\bf b}, \hat{w}) - \int d^{N} x \;{p}({\bf x}) H({\bf x}, {\bf b}, \hat{w}) \label{eq:constraint2}\\ 0 &=& \frac{\partial { L}({p}, \beta, \nu)}{ \partial \nu} = 1 - \int d^{N} x \; {p}({\bf x}). \label{eq:constraint3} \end{eqnarray} Therefore, the maximum entropy distribution must be given by \begin{equation} {p}({\bf x}) = \exp\left (- \beta H({\bf x}, {\bf b}, \hat{w})-1-\nu \right ) \label{eq:canonical} \end{equation} with Lagrange multipliers $\beta$ and $\nu$ determined from the constraint \eqref{eq:constraint2} and normalization condition \eqref{eq:constraint3}. In what follows we shall refer to the distribution \eqref{eq:canonical} as a canonical ensemble. \section{Partition function}\label{sec:partition} The partition function for the canonical ensemble \eqref{eq:canonical} is defined as ${\cal Z}\equiv \exp(1+\nu)$ and can be expressed as an integral over the state space \begin{eqnarray} {\cal Z}(\beta, {\bf b}, \hat{w}, ...) &=& \int d^{N} x \;e^{- \beta H\left ( {\bf x}, {\bf b}, \hat{w} \right )} \label{eq:canonical_partition} \end{eqnarray} where $...$ should remind us of any additional variables (e.g. $m$) which could determine the functional form of $ H$. To calculate the partition function \eqref{eq:canonical_partition} for a bulk loss \eqref{eq:bulk_loss} we can approximate the integral with a Gaussian. This can be done by first expanding the activation function \begin{equation} {\bf f}\left ( \hat{w} {\bf x}+ {\bf b}\right ) = {\bf f} (\hat{w} \langle {\bf x} \rangle + {\bf b} ) + \hat{f}' \hat{w} ({\bf x} - \langle {\bf x}\rangle) + {\cal O}(({\bf x} - \langle {\bf x}\rangle)^2)\label{eq:expansion} \end{equation} where the ensemble-averaged state vector is \begin{equation} \langle {\bf x}\rangle \equiv \int d^{N} x \; {\bf x}\; {p}({\bf x}) \end{equation} and a diagonal matrix of first derivatives of the activation function is \begin{equation} f'_{ii} \equiv \left (\frac{d f(y_i)}{d y_i}\right )_{y_i = \sum_j w_{ij} \langle x_j \rangle + b_i}. \label{eq:F} \end{equation} Then to the first order in perturbation theory the bulk loss function is \begin{eqnarray} H({\bf x}, {\bf b}, \hat{w}) &\approx& \frac{1}{2} ({\bf x} - \langle {\bf x}\rangle) ^T\hat{G} ({\bf x} - \langle {\bf x}\rangle) - \frac{m}{2}{\bf x}^T {\bf x} \label{eq:approximation} \end{eqnarray} where \begin{equation} \hat{G} \equiv \left ( \hat{I} - \hat{f}' \hat{w}\right)^T \left ( \hat{I} - \hat{f}' \hat{w}\right). \end{equation} Next, we note that the domain of ${\bf x}$ is bounded by the range of the activation function. For example, if the activation function is $f(x)=\tanh(x) \in (-1,1)$, then the partition function is \begin{equation} {\cal Z}(\beta, {\bf b}, \hat{w}) = \int_{{\bf x} \in (-1,1)^N} d^{N} x\, e^{- \beta H({\bf x}, {\bf b}, \hat{w})}. \end{equation} The sharp boundaries can be approximated with a smooth Gaussian window function, i.e. \begin{equation} {\cal Z}(\beta, {\bf b}, \hat{w}) \approx \int_{{\bf x} \in (-\infty ,\infty)^N} d^{N} x\, e^{- \beta H({\bf x}, {\bf b}, \hat{w})} e^{ - \frac{1}{2}{\bf x}^T {\bf x} }. \end{equation} and then the overall partition function is a Gaussian and can be easily evaluated, \begin{eqnarray} {\cal Z}(\beta, {\bf b}, \hat{w}) &\approx & \int d^{N} x\, e^{- \beta H({\bf x}, {\bf b}, \hat{w}) - \frac{1}{2}{\bf x}^T {\bf x} } \approx \int d^{N} x\, e^{- \frac{\beta }{2} ({\bf x} - \langle {\bf x}\rangle) ^T\hat{G} ({\bf x} - \langle {\bf x}\rangle) - \frac{1- \beta m}{2}{\bf x}^T {\bf x} } \label{eq:R2} \\ &\approx& (2 \pi)^{N/2} \det \left ( \hat{I} (1-\beta m) + \beta\hat{G} \right )^{-1/2} \,\exp \left ( { -\frac{1}{2}\langle {\bf x}\rangle^T \left (\frac{(1-\beta m) \beta\hat{G} }{ \hat{I} (1-\beta m) + \beta \hat{G}} \right ) \langle {\bf x}\rangle}\right ). \notag \end{eqnarray} The spectrum of $\hat{G}$ is defined by an eigenvalue equation \begin{equation} \hat{G} {\bf v}_i = \hat{G}\lambda_i \end{equation} where $\lambda_i$ are the real eigenvalues and ${\bf v}_i$ are the respected eigenvectors. Then the log of partition function is \begin{eqnarray} \log {\cal Z}(\beta, {\bf b}, \hat{w}) &\approx& -\frac{1}{2} \sum_i \log \left ( 1-\beta m + \beta \lambda_i \right ) -\frac{1}{2} \sum_i \frac{(1-\beta m) \beta \lambda_i a_i^2}{1-\beta m+\beta \lambda_i} + \frac{N}{2} \log (2\pi) \;\;\;\;\; \label{eq:logZZ} \end{eqnarray} where \begin{equation} \langle {\bf x} \rangle = a_i {\bf v}_i. \end{equation} In the limit of a large number of neurons $N$, the average components are small $a_i^2 \ll 1$, the second term in \eqref{eq:logZZ} is subdominant in comparison to the first term and can be dropped. Then the partition function is given by \eqref{eq:R2} but without an exponential factor, i.e. \begin{equation} {\cal Z}(\beta, {\bf b}, \hat{w}) \approx (2 \pi)^{N/2} \det \left ( \hat{I} (1-\beta m) + \beta\hat{G} \right )^{-1/2} \label{eq:Z} \end{equation} and the log of the partition function is \begin{eqnarray} \log {\cal Z}(\beta, {\bf b}, \hat{w}) &\approx& -\frac{1}{2} \log \det \left ( \hat{I} (1-\beta m) + \beta\hat{G} \right ) + \frac{N}{2} \log (2\pi)\notag\\ &\approx& -\frac{1}{2} Tr \log \left ( \hat{I} (1-\beta m) + \beta\hat{G} \right ) + \frac{N}{2} \log (2\pi)\label{eq:logZ}\\ \notag &\approx& -\frac{1}{2} \sum_i \log \left ( 1 -\beta m + \beta \lambda_i \right ) + \frac{N}{2} \log (2\pi). \end{eqnarray} Note, however, that this is a very rough estimate of the true partition function borne out of our statistical description, but the hope is that this approximation is rich enough to explain at least some aspects of machine learning. \section{Learning equilibrium}\label{sec:equilibrium} Given the partition function \eqref{eq:canonical_partition} the average bulk loss can be calculated by simple differentiation, \begin{equation} U(\beta , {\bf b}, \hat{w}) = \int d^{N} x H({\bf x}, {\bf b}, \hat{w}){p}({\bf x}) = - \frac{\partial}{\partial \beta} \log({\cal Z}(\beta, {\bf b}, \hat{w})), \end{equation} where we have explicitly shown that $U(\beta , {\bf b}, \hat{w})$ depends on the Lagrange multiplier $\beta$ (or, what we shall call, an inverse temperature parameter). If the neural network was already trained for a very long time, then the weight matrix and the bias vector must be in a state which minimizes the average loss $U(\beta , {\bf b}, \hat{w})$ and then its variations with respect to $\hat{w}$ and ${\bf b}$ must vanish, \begin{eqnarray} \frac{\partial U(\beta , {\bf b}, \hat{w}) }{\partial w_{ij}} &=& \frac{\partial^2}{\partial w_{ij} \partial \beta} \log({\cal Z}(\beta, {\bf b}, \hat{w})) =0 \notag\\ \frac{\partial U(\beta , {\bf b}, \hat{w}) }{\partial b_{i}} &=& \frac{\partial^2}{\partial b_{i} \partial \beta} \log({\cal Z}(\beta, {\bf b}, \hat{w})) =0. \label{eq:equilibrium} \end{eqnarray} We shall call this state, a state of the learning equilibrium or just an equilibrium state. For a generic system, the degeneracy of an equilibrium state or the dimensionally of an equilibrium manifold (or the number of ``Goldstone'' modes) can be quite large, but is still much smaller than $N$. A very important property of an equilibrium, which follows from \eqref{eq:equilibrium}, is that the partition function must be a product of two terms \begin{equation} {\cal Z}(\beta, {\bf b}, \hat{w}) = \exp\left ( -\beta A (\beta) \right ) \times \exp\left (C({\bf b}, \hat{w}) \right ) \label{eq:factorization} \end{equation} or that the total free energy must decompose into a sum of two terms \begin{equation} F(\beta, {\bf b}, \hat{w}) \equiv - \frac{1}{\beta}\log {\cal Z}(\beta, {\bf b}, \hat{w}) = A (\beta) - \frac{1}{\beta}C({\bf b}, \hat{w}). \label{eq:decomposition} \end{equation} The first term is a familiar thermodynamic free energy and, as we shall argue in the following section, the second term is related to a complexity of the neural networks. However, the free energy obtained from \eqref{eq:logZ} (with the local objectives parameter $m$ set for simplicity to zero) is \begin{equation} F(\beta, {\bf b}, \hat{w}) = \frac{1}{2\beta} \sum_i \log \left ( 1 + \beta \lambda_i \right ) - \frac{N}{2 \beta} \log (2\pi) \end{equation} which does not in general decompose into a sum of two terms as in \eqref{eq:decomposition}. This suggest that in an equilibrium some additional restrictions must be imposed on the eigenvalues $\lambda_i$. One possibility (that we shall verify numerically) is that \begin{equation} \sum_{\lambda_i \gg \beta^{-1}} \log \left ( 1 + \beta \lambda_i \right ) \approx \sum_{\lambda_i \gg \beta^{-1}} \log(\lambda_i) + {N_>} \log (\beta) \gg \sum_{\lambda_i \lesssim \beta^{-1}} \beta \lambda_i \approx \sum_{\lambda_i \lesssim \beta^{-1}} \log \left ( 1 + \beta \lambda_i \right ) \notag \end{equation} where $N_>$ is the number of eigenvalues $\lambda_i$ that are much greater than $\beta^{-1}$. Then the free energy can indeed be decomposed as in equation \eqref{eq:decomposition}, \begin{eqnarray} F(\beta, {\bf b}, \hat{w}) &\approx& \frac{1}{2 \beta} \sum_{\lambda_i \gg \beta^{-1}} \log(\lambda_i) + \frac{N_>}{2\beta} \log (\beta) - \frac{N}{2\beta} \log (2\pi) \label{eq:free} \end{eqnarray} with \begin{eqnarray} C({\bf b}, \hat{w}) &\approx& - \frac{1}{2}\sum_{\lambda_i \gg \beta^{-1}} \log(\lambda_i) + \frac{N}{2} \log (2\pi) \label{eq:complexity} \end{eqnarray} and \begin{eqnarray} A(\beta) &\approx& \frac{N_>}{2 \beta } \log (\beta) \label{eq:A}. \end{eqnarray} Recall that $\lambda_i$'s are the eigenvectors of $\hat{G}= \left ( \hat{I} - \hat{f}' \hat{w}\right)^T \left ( \hat{I} - \hat{f}' \hat{w}\right)$ and, thus, $\lambda_i$'s are functions of ${\bf b}$ and $\hat{w}$. \section{Thermodynamics of learning}\label{sec:thermodynamics} The total Shannon entropy of the canonical ensemble can be obtained from the canonical partition function \eqref{eq:logZ}, \begin{eqnarray} S(\beta,{\bf b}, \hat{w} ) &=& - \langle \log {p} \rangle = - \beta \frac{\partial}{\partial \beta } {\cal Z}(\beta, {\bf b}, \hat{w}) + {\cal Z}(\beta, {\bf b}, \hat{w}) =\beta^2 \frac{\partial}{\partial \beta } F(\beta, {\bf b}, \hat{w}). \label{eq:total_entropy} \end{eqnarray} Just like the free energy, in a learning equilibrium \eqref{eq:equilibrium}, the entropy must also decompose into a sum of two terms, \begin{eqnarray} S(\beta,{\bf b}, \hat{w} ) &=& \beta^2 \frac{\partial}{\partial \beta } \left ( A (\beta) - \frac{1}{\beta}C({\bf b}, \hat{w}) \right ) = \beta^2 \frac{\partial A(\beta)}{\partial \beta} + C({\bf b}, \hat{w}). \label{eq:entropy_complexity} \end{eqnarray} The first term depends on only the inverse temperature parameter $\beta$ and we shall refer to it as a thermodynamic entropy \begin{equation} {S}_0(\beta) =\beta^2 \frac{\partial A(\beta)}{\partial \beta}= \beta (U (\beta) - A(\beta) ). \end{equation} For the total free energy \eqref{eq:free} it is given by \begin{eqnarray} {S}_0(\beta) &=& -\beta A (\beta) + \beta U(\beta)\approx - \frac{N_>}{2} \log (\beta) + \frac{N_>}{2} \notag\\ &\approx& \frac{N_>}{2} \log (U) + \frac{N_>}{2} \left ( 1 - \log \frac{N_>}{2} \right ) \label{eq:thermodynamic_entropy} \end{eqnarray} where \begin{equation} U(\beta) = -\frac{\partial}{\partial \beta} \log {\cal Z}(\beta, {\bf b}, \hat{w}) = \frac{\partial}{\partial \beta}\left ( \beta F(\beta, {\bf b}, \hat{w}) \right ) = \frac{\partial}{\partial \beta} \left (\beta A(\beta) \right ) \approx \frac{N_>}{2\beta}.\label{eq:U} \end{equation} As the learning progresses, the average loss, $ U(\beta) $, decreases, the temperature parameter, $\beta^{-1}$, decreases and, thus, according to \eqref{eq:thermodynamic_entropy} one might expect that the thermodynamic entropy, ${S}_0$, should also decrease. However, it is not the thermodynamic entropy, ${S}_0$, but the total Shannon entropy $S$ (whose exponent describes accessible volume of the configuration space for ${\bf x}$) should become smaller with learning. We shall call it the second law of learning (or perhaps the minus second law):\\ \\ {\bf Second Law of Learning:} {\it the total entropy of a learning system can never increase during learning and is constant in a learning equilibrium,} \begin{equation} \frac{d}{dt} S \le 0.\label{eq:second_law} \end{equation} \\ In the long run the system is expected to approach an equilibrium state with the smallest possible total entropy ${S}$ which corresponds to the lowest possible sum of the thermodynamic entropy, ${S}_0$, and of the complexity function $C({\bf b}, \hat{w})$ that we shall discuss next. In a feedforward neural network the weight matrix, $\hat{w}$, is nilpotent \eqref{eq:nilpotent} and, therefore, the eigenvalues of the operator $\hat{w}$ are all zeros. This also implies that the eigenvalues of operator $ \hat{I} - \hat{f}' \hat{w}$ are all ones, but that does not tell us much about the eigenvalues of $\hat{G}$. On the other hand, the determinant of $\hat{G}$ is simply related to the determinant of $ \hat{I} - \hat{f}' \hat{w}$, \begin{equation} \det \hat{G} = \det \left ( \hat{I} - \hat{f}' \hat{w}\right)^2 = 1, \end{equation} or \begin{equation} \sum_i \log(\lambda_i) = 0. \label{eq:eig_log} \end{equation} If we assume that near equilibrium $N_>$ does not change significantly, then a decrease in $C({\bf b}, \hat{w})$ implies that the largest eigenvalues $\sum_{\lambda_i \gg \beta^{-1}} \log(\lambda_i)$ of the operator $\hat{G}$ must increase and at the same time, according to \eqref{eq:eig_log}, the smallest eigenvalues $\sum_{\lambda_i \lesssim \beta^{-1}} \log(\lambda_i)$ must decrease. Therefore, as the learning progresses, the operator $\hat{G}$ becomes better and better approximated by eigenvectors ${\bf v}_i$ with only largest eigenvalues, i.e. \begin{equation} \hat{G} = \sum_{i} \lambda_i {\bf v}_i {\bf v}^T_i = \sum_{\lambda_i \gg \beta^{-1}} \lambda_i {\bf v}_i {\bf v}^T_i + \sum_{\lambda_i \lesssim \beta^{-1}} \lambda_i {\bf v}_i {\bf v}^T_i \approx \sum_{\lambda_i \gg \beta^{-1}} \lambda_i {\bf v}_i {\bf v}^T_i \label{eq:G_approx} \end{equation} This is what one might call a dynamical dimensional reduction of the state space (a subspace of dimension $N_> < N$ is sufficient to describe a state vector ${\bf x}$), or a reduction in the complexity of interconnections between neurons (a subspace of dimension $N_>^2 < N^2$ is sufficient to describe a weight matrix $\hat{w}$) or a complexity of computations that a given neural networks performs (a subspace of dimension $N_>^2 < N^2$ is sufficient to describe a linearized evolution operator $( \hat{I} - \hat{f}' \hat{w})$). For this reason we shall refer to $C({\bf b}, \hat{w})$ as a measure of complexity or just complexity. For a system transitioning between equilibrium states at constant temperature $T=1/\beta$, variations of the free energy must vanish, $d F=0$, and then equation \eqref{eq:decomposition} takes the from of the first law, \begin{equation} d A - T d C = dU - T d S_0 - T d C = 0. \label{eq:first} \end{equation} or what we shall call the first law of learning (or perhaps the minus first law): \\ \\ {\bf First Law of Learning:} {\it the increment in the loss function is proportional to the increment in the thermodynamic entropy plus the increment in the complexity} \begin{equation} dU = T d S_0 + T d C .\label{eq:first_law} \end{equation} \\ This law describes how the learning system behaves when transitioning between equilibrium states, but in order to understand which neural architectures would be the most optimal we must take one step further and consider a non-equilibrium dynamics of the learning system. \section{Optimal architecture}\label{sec:architecture} Consider a family of bias vectors ${\bf b}({\bf Q})$ and weight matrices $\hat{w}({\bf Q})$ parametrized by dynamical parameters $Q_{k}$'s where ${k} \in (1,...,K)$. Typically the number of parameters $K$ is much smaller than $N + N^2$ (i.e. the number of parameters required to describe a generic vector ${\bf b}$ and a generic matrix $\hat{w}$) and the art of designing a neural architecture is to come up with functions ${\bf b}({\bf Q})$ and $\hat{w}({\bf Q})$ which are most efficient in finding solutions. To make the statement more quantitative, consider an ensemble of neural networks described by a probability distribution ${p}(\beta, {\bf Q})$ which evolves with ``time'' $\beta$ according to continuity equation \begin{equation} \frac{\partial}{\partial \beta}{p}(\beta, {\bf Q}) = - \sum_{k} \frac{\partial}{\partial Q_{{k}}}\left ( \frac{d Q_k}{d \beta} { p}(\beta, {\bf Q}) \right) \label{eq:dP} \end{equation} where the parameters $Q_{k}$'s evolve in the direction of the gradient of the free energy \begin{equation} \frac{d Q_{{k}}}{d \beta} = \alpha \frac{\partial F}{\partial Q_{k}} = \alpha \sum_{i} \frac{\partial b_{i}}{\partial Q_{k}} \frac{\partial F }{\partial b_{i}} + \alpha\sum_{i,j} \frac{d w_{ij}}{d Q_{k}} \frac{\partial F}{\partial w_{ij}}. \label{eq:dQ} \end{equation} The Shannon entropy of the distribution ${p}(\beta, {\bf Q})$ with continuous variables ${\bf Q}$ (not to confuse with entropy $S(\beta,{\bf b}, \hat{w} )$ defined in the previous section) is, \begin{equation} {\mathscr S}(\beta) = - \int d^K Q \;\;{p}(\beta, {\bf Q}) \log \left ( {p}(\beta, {\bf Q}) \right ) \label{eq:entropy2} \end{equation} Larger the entropy ${\mathscr S}(\beta)$, larger the accessible volume of the configuration space $\exp ({\mathscr S}(\beta))$, and therefore larger the rate with which new solutions for ${\bf b}$ and $\hat{w}$ can be found. Then an optimal architecture (described by ${\bf b}({\bf Q})$ and $\hat{w}({\bf Q})$) is the one for which the entropy destruction is minimized or, equivalently, the entropy production is maximized. We shall call it the principle of the minimum entropy destruction: \\ \\ {\bf Principle of Minimum Entropy Destruction}: {\it The path taken by an optimal learning system is the one for which the entropy destruction is minimized (or the entropy production is maximized). }\\ \\ Note that the principle is the opposite of the minimum entropy production principle \cite{Prigogine,Klein} that is often used in context of non-equilibrium thermodynamics, but is consistent with the stationary entropy production principle that was recently used in context of emergent quantum mechanics \cite{entropic} and emergent gravity \cite{emergentgravity}. In context of the learning systems, a useful expression for the entropy production can be obtained from \eqref{eq:dP}, \eqref{eq:dQ} and \eqref{eq:entropy2}, \begin{eqnarray} \frac{\partial }{\partial \beta }{\mathscr S}(\beta) & = & - \frac{\partial }{\partial \beta } \int d^K Q \;\;{p} \log ({p}) = - \int d^K Q \;\; \log ({p}) \frac{\partial }{\partial \beta } {p} \label{eq:entropy_change}\\ & = & \int d^K Q \; \log ({p}) \sum_{k} \frac{\partial}{\partial Q_{{k}}}\left ( \frac{d Q_k}{d \beta} { p}\right) = - \int d^K Q \; \sum_{k} \frac{d Q_k}{d \beta} \frac{\partial {p}}{\partial Q_{{k}}} \notag\\ & = &- \alpha \int d^K Q \; \sum_{k} \frac{\partial F}{\partial Q_{k}} \frac{\partial {p}}{\partial Q_{{k}}} = \alpha \int d^K Q \; \sum_{k} \frac{\partial^2 F}{\partial Q^2_{k}} {p} \notag \\ & = & \alpha \int d^K Q \; {p}(\beta, {\bf Q}) \Delta F(\beta, {\bf Q}) \notag \end{eqnarray} where the Laplacian operator is defined as usual $\Delta \equiv \sum_{k} \frac{\partial^2 }{\partial Q^2_{k}}$. To better understand the optimization condition we can choose the parameters $Q_i$'s to be given by eigenvalues of the operator $\hat{G}$, i.e. $Q_i = \lambda_i$. Then the free energy \eqref{eq:logZ} (with $m$ set for simplicity to zero) can be approximated as \begin{eqnarray} F &\approx & \frac{1}{2 \beta} \log \det \left ( \hat{I} + \beta\hat{G} \right ) \notag\\ &\approx & \frac{1}{2 \beta} \sum_i \log \left ( 1 + \beta \lambda_i \right ) - \frac{N}{2\beta} \log (2\pi) \label{eq:free_eng} \end{eqnarray} and its Laplacian as \begin{eqnarray} \Delta F&\approx & \frac{1}{2 \beta} \Delta \log \det \left ( \hat{I} + \beta\hat{G} \right ) \notag\\ & \approx & \frac{1}{2 \beta} \sum_j \frac{\partial^2}{\partial \lambda_j^2} \sum_i \log \left ( 1 + \beta \lambda_i \right ) \notag \\ &\approx & -\frac{\beta}{2} \sum_i \left ( 1+\beta \lambda_i \right)^{-2}. \label{eq:DeltaF} \end{eqnarray} Evidently, the Laplacian is always negative and, thus, for the entropy \eqref{eq:entropy_change} to decrease with learning $\alpha$ must be positive or that the parameters $Q_{k}$'s evolve in the direction which maximizes the free energy \eqref{eq:dQ}. This may sound counterintuitive (since the main objective of learning is to minimize the loss function $U$), but it is a mere consequence of the decrease in the entropy $S$ which accompanies learning (i.e. the second law of learning). Anyways, it should be clear that to improve learning efficiency we must choose an architecture such that the Laplacian $\Delta F$ is as close to zero as possible and then the entropy destruction is minimized (i.e. the principle of minimum entropy destruction). If we, once again, split all of the eigenvalues into large and small, then the Laplacian is approximately given by the number $N_<$ of smallest eigenvalues $\lambda_i \ll \beta^{-1}$, i.e. \begin{equation} \Delta F \approx -\frac{\beta}{2} \sum_{\lambda_i \ll \beta^{-1}} \left ( 1+\beta \lambda_i \right)^{-2} \approx -\frac{\beta}{2} N_<. \end{equation} Note that while the largest eigenvalues $\lambda_i \gg \beta^{-1}$ are responsible for reducing complexity of the already obtained solutions \eqref{eq:complexity}, the smallest eigenvalues $\lambda_i \ll \beta^{-1}$ are responsible for searching for new solutions. \section{Deep vs. shallow} \label{sec:deep_shallow} We are now ready to tackle one of the biggest mysteries of machine learning. Why do deep neural networks perform so well? We believe the answer is hidden in the free energy $ F$. As we have argued in the previous section \eqref{eq:entropy_change} the Laplacian $\Delta F$ describes the rate with which the entropy ${\mathscr S}$ decays and by minimizing, \begin{equation} - \Delta F= \frac{\beta}{2} \sum_i \left ( 1+\beta \lambda_i \right)^{-2} = \frac{\beta}{2} Tr \left ( \hat{I} +\beta \hat{G} \right)^{-2} \label{eq:min}, \end{equation} we maximize the efficiently of a neural network to find solutions (i.e. the principle of minimum entropy destruction). To solve the minimization problem, we can consider a neural network with a small fraction $\gamma \ll 1$ of eigenvalues $\lambda_i \sim \lambda$ and a larger fraction $1-\gamma$ of large eigenvalues at $\lambda_i \sim \lambda^{\frac{\gamma}{\gamma-1}}$ so that \begin{equation} \det{\hat{G}} = \prod_i \lambda_i = \lambda^{\gamma N} \lambda^{\frac{\gamma}{\gamma-1} (1-\gamma) N} = 1. \end{equation} Then the negative of the Laplacian is \begin{eqnarray} - \Delta F\approx \frac{\beta}{2} Tr \left ( \hat{I} +\beta \hat{G} \right)^{-2} & = &\frac{N \beta}{2} \left (\frac{ \gamma}{\left ( 1+\beta \lambda \right )^{2}} + \frac{ 1 - \gamma }{ \left ( 1+\beta \lambda^{\frac{\gamma}{\gamma-1}} \right )^{2} }\right ). \end{eqnarray} On Fig. \ref{fig:fig0}\begin{figure}[] \begin{center} \includegraphics[width=1.0\textwidth]{fig0.png} \caption{$ -\Delta F(\log \lambda) $ for four different values of $\beta=0.25, 0.50, 0.73$ and $1.00$.} \label{fig:fig0} \end{center} \end{figure} we plotted $- \Delta F(\log \lambda)$ for four different values of the inverse temperature parameter $\beta=0.25, 0.50, 0.73, 1.00$, $\gamma=1/3$ and $N=854$. In the initial phase, $\beta < 1/2$, (e.g. blue line on Fig. \ref{fig:fig0}) there is a stable local minimum at $\log \lambda \approx 3 \log \left ( -\frac{1}{2} + \sqrt{\frac{1}{4}+ \frac{1}{\beta}} \right )$ and an unstable maximum at $ \log \lambda = 0$. In this phase, a small number, $N \gamma \ll N$, of eigenvalues is free to move away from a local maximum at $\log \lambda = 0$ to both smaller and larger values, but most of the eigenvalues $N (1-\gamma) \sim N$ should remain near $\log \lambda \sim 0$. In the intermediate phase, $1/2 < \beta < \sqrt{N} - 1 $, (e.g. green line on Fig. \ref{fig:fig0}) the two extreme points switch and there an unstable maximum at \begin{equation} \log \lambda = 3 \log \left ( -\frac{1}{2} + \sqrt{\frac{1}{4}+ \frac{1}{\beta}} \right ). \label{eq:unstable_max} \end{equation} In this phase only a decreasing fraction, $\gamma < (\beta + 1)^{-2}$, of the small eigenvalues, $\log \lambda < 3 \log \left ( -\frac{1}{2} + \sqrt{\frac{1}{4}+ \frac{1}{\beta}} \right )$, can still move to even smaller values, but the motion is terminated when the smallest values, $\log \lambda \ll 3 \log \left ( -\frac{1}{2} + \sqrt{\frac{1}{4}+ \frac{1}{\beta}} \right )$, reach the plateau. However, since $\det \hat{G} =1$, it is expected that the sum of the largest eigenvalues would continue to grow and according to \eqref{eq:complexity} the complexity of a network should continue to decrease. And finally, in the final phase, $ \beta > \sqrt{N} - 1 $, (e.g. red line on Fig. \ref{fig:fig0}) the global minimum is at $\log \lambda =0$, the individual eigenvalues can no longer move towards $\log \lambda = - \infty$ and the ability of the neural network to learn becomes exponentially suppressed. This is what happens in an optimal system, however, by enforcing an architecture on a neural network (e.g. deep or shallow) we impose additional constraints on the free energy (and on its Laplacian) which limits the ability of a network to explore the space of solutions. For example, in a feedforward neural network with many input neurons and few output/hidden neurons, most of the eigenvalues are set to $\log \lambda_i = 0$ and only a small fraction of eigenvalues is free to move to smaller and larger values. Clearly, the larger the number of the dynamical eigenvalues a neural architecture has, the better it is for learning. Therefore, in order to compare ``apples to apples'' we must first fix the number of the dynamical eigenvalues, and then look for an architecture which is flexible enough to support a skewed distribution of $\log \lambda_i$'s. As we have argued in the previous paragraph, want we want is to be able to start with a single peak with all eigenvalues at $\log \lambda_i \sim 0$ and then to gradually grow a second peak with the largest eigenvalues $\log \lambda_i \gtrsim 0 > - \log \beta$ which is to be balanced by the smallest eigenvalues $\log \lambda_i < - \log \beta$ that are dragged to smaller and smaller values. With this respect, a better architecture is the one which supports a larger variance \begin{equation} \mu_2 \equiv Tr \left ( \log \hat{G} \right )^2 \label{eq:varience} \end{equation} and a more skewed distribution or a more negative \begin{equation} \mu_3 \equiv Tr \left ( \log \hat{G} \right )^3. \label{eq:skew} \end{equation} In a feedforward neural network the weight matrix is nilpotent \eqref{eq:nilpotent} as well as a product of the weight matrix, $\hat{w}$ and a diagonal matrix of first derivatives, $ \hat{f}'$, i.e. \begin{equation} \left( \hat{f}'\hat{w} \right )^n = \left ( \hat{w}^T \hat{f}'\right )^n = 0 \;\;\;\forall n \ge L \label{eq:powers} \end{equation} where $L$ is the number of layers. For starters, consider a vary shallow network with no hidden layers (i.e. $L=2$) and thus $ \left ( \hat{w}^T \hat{f}'\right )^2 = \left( \hat{f}'\hat{w} \right )^2=0$. Then there must exist functions $F_1(x)$ and $F_2(x)$ such that \begin{equation} \log \hat{G} = F_1(\hat{f}'\hat{w} \hat{w}^T \hat{f}')\,\hat{f}'\hat{w} + F_2( \hat{w}^T \hat{f}' \hat{f}'\hat{w}) \hat{w}^T \hat{f}' . \end{equation} and, therefore, \begin{eqnarray} Tr \left [ \log \hat{G} \right ] &=& 0\\ Tr \left [ \left ( \log \hat{G} \right )^2 \right ] &=& Tr \left [ F_2( \hat{w}^T \hat{f}' \hat{f}'\hat{w}) \hat{w}^T \hat{f}' F_1(\hat{f}'\hat{w} \hat{w}^T \hat{f}')\,\hat{f}'\hat{w} + F_1(\hat{f}'\hat{w} \hat{w}^T \hat{f}')\,\hat{f}'\hat{w}F_2( \hat{w}^T \hat{f}' \hat{f}'\hat{w}) \hat{w}^T \hat{f}' \right ] \notag \end{eqnarray} and \begin{equation} \mu_3 = Tr \left [ \left ( \log \hat{G} \right )^3 \right ] = 0. \end{equation} In fact the traces of all odd powers must also be zero \begin{equation} Tr \left [ \left ( \log \hat{G} \right )^{2n+1} \right ]= 0 \end{equation} since every term in $ \left ( \log \hat{G} \right )^{2n+1}$ would have a product of unequal number of $F_1(\hat{f}'\hat{w} \hat{w}^T \hat{f}')\,\hat{f}'\hat{w}$ and $F_2( \hat{w}^T \hat{f}' \hat{f}'\hat{w}) \hat{w}^T \hat{f}' $ terms which must be traceless. As we shall see in the next section, even with a single hidden layer (i.e. $L=3$) the second powers of operators $ \hat{f}' \hat{w}$ and $\hat{w}^T \hat{f}'$ are very small and the skewness is still very small $\mu_3 \approx 0$. What this means is that the effective number of dynamical eigenvalues is half of what it would have been if all eigenvalues were free to move without having to respect the symmetry of the distribution. However, as we keep adding more hidden layers the skewness of distribution grows larger, the eigenvalues become less constrained and the efficiency of learning is greatly improved. This might be why the deep learning is so efficient: hidden layers are essential for larger skewness $\mu_3$ and, as a result, for less negative Laplacian $\Delta F$ (and a slower decay of the entropy ${\mathscr S}$) which we claim is necessary for efficient learning. \section{Numerical experiments}\label{sec:numerics} A direct numerical calculation of the distribution ${p}({\bf x}) $ is a computationally intensive task, but the main advantage of our statistical description is that the canonical ensemble \eqref{eq:canonical} can be viewed as purely phenomenological object. Then the main problem should be to come up with a model of the bulk loss function, $H({\bf x}, {\bf b}, \hat{w})$, which best describes the canonical ensemble and, consequently, the canonical partition function, ${\cal Z}(\beta, {\bf b}, \hat{w})$, and other thermodynamic quantities. On the other hand, the analysis of the preceding sections already suggests certain forms of the bulk loss function and of the partition function which we can easily verify numerically. In this section, we will check to what extent a feedforward neural network can be modeled by the bulk loss function without local objectives (i.e. \eqref{eq:bulk_loss} with $m=0$) or with the corresponding thermodynamic quantities: (a) average bulk loss (estimated in \eqref{eq:U}), \begin{equation} U(\beta) = \frac{N_>}{2 \beta} \label{eq:U_num}, \end{equation} (b) complexity function (estimated in \eqref{eq:complexity}), \begin{equation} C({\bf b}, \hat{w}) = -\frac{1}{2} \sum_{\lambda_i \gg \beta^{-1}} \log(\lambda_i) + \frac{N}{2} \log (2\pi) + \text{const} \label{eq:C_num}, \end{equation} (c) thermodynamic entropy (estimated in \eqref{eq:thermodynamic_entropy}), \begin{eqnarray} {S}_0(\beta) = - \frac{N_>}{2} \log (\beta) + \text{const} = \frac{N_>}{2} \log (U) - \frac{N_>}{2} \log \left ( \frac{N_>}{2}\right ) + \text{const}\label{eq:ent_num}, \end{eqnarray} where $N_>$ is the number of eigenvalues $\lambda_i$'s much larger than $\beta^{-1}$. In addition, we will verify the expected dynamics of the eigenvalues and the anticipated dependence of the variance \eqref{eq:varience} and skewness \eqref{eq:skew} parameters on the performance of the neural networks obtained in the previous sections. All of the numerical experiments were carried out using the TensorFlow Python library \cite{TensorFlow} and MNIST database of handwritten images \cite{MNIST}. Unfortunately, in the TensorFlow library the hidden layers are not dynamical and must be set prior to training. Nevertheless, we were able to obtain the desired results by running two different programs: the first one with two hidden layers (or what we shall call a ``deep'' neural network) and one with a single hidden layer (or what we shall call a ``shallow'' neural network). In the deep network we used an input layer with $784$ neurons, the first hidden layer with $40$ neurons, the second hidden layer with $20$ neurons and the output layer with $10$ neurons; and in the shallow network we used the same number of neurons on the input and output layers (i.e. $784$ and $10$), but only a single hidden layer with $60$ neurons. Altogether there are $N=784+40+20+10=784+60+10=854$ neurons in each neural network and so the state vectors $\bf x$ and the bias vectors $\bf b$ are $854$-dimensional vectors. The weight matrix $\hat{w}$ has $854\times854$ components $w_{ij}$, but most of them are zero due to the predetermined architecture of hidden layers. The input layers represent a handwritten image of a number from $0$ to $9$ which is passed to $28\times28=784$ input neurons. One of the $10$ output neurons is to be activated only if the corresponding number is on the image. The activation function on all neurons is $f(y)=\tanh(y)$ and so the diagonal matrix $\hat{f}'$ has diagonal elements given by \begin{equation} f'_{ii}(y_i) =\frac{df(y_i)}{d y_i}=\frac{d\tanh(y_i)}{d y_i}= \sech(y_i)^2 = 4 (\exp(y_i)+\exp(-y_i))^{-2}. \end{equation} The training was carried out using the method of stochastic gradient descent for $30,000$ epochs with $6,000$ samples in the training dataset. On Fig. \ref{fig:fig1}\begin{figure}[] \begin{center} \includegraphics[width=0.8\textwidth]{fig1.png} \caption{Bulk loss (blue line) and boundary loss (red line) for $30,000$ training epochs.} \label{fig:fig1} \end{center} \end{figure} we plot (log of the ensemble-averaged) bulk loss $U= \langle H \rangle $ (blue line) and (log of the ensemble-averaged) boundary loss $U_\partial = \langle H_\partial \rangle $ from the deep neural network. As expected, the bulk loss remains few orders in magnitude smaller than the boundary loss, but both functions decrease with time. For training the neural network we used the (more familiar, but less general) boundary loss function $H_\partial$, but a similar result is expected even if the (less familiar, but more general) bulk loss function $H$ would have been used instead. On Fig. \ref{fig:fig2}\begin{figure}[] \begin{center} \includegraphics[width=0.8\textwidth]{fig2.png} \caption{Bulk loss vs. boundary loss for $30,000$ training epochs.} \label{fig:fig2} \end{center} \end{figure} we plot the bulk loss $\log U $ vs. the boundary loss $\log U_\partial $ from the same deep network. Note that at late times the bulk loss keeps decreasing while the boundary loss remains almost constant (inside of red oval on Fig. \ref{fig:fig2}). This behaviors continue for about $10,000$ (!) training epochs until the network finally finds a better solution and the boundary loss jumps to a smaller value (inside of green oval on Fig. \ref{fig:fig2}). And then essentially the same behavior continues, i.e. bulk loss decreases monotonically, but boundary loss makes sudden jumps. There is a simple explanation of the phenomena. The boundary loss is stuck in a saddle point with a large number of nearly flat directions for a very long time before it finds a way out. As the learning progress the system keeps moving along the flat directions and that does not reduce the boundary loss considerably, but the bulk loss and, as we shall see shortly, complexity keep decreasing with roughly the same pace. This shows that the bulk loss function has a lot fewer flat directions and with this respect a much better loss function. In addition, as we have argued in Sec. \ref{sec:unsupervised}, it can be defined beyond supervised systems, e.g. for unsupervised learning. \begin{figure}[] \begin{center} \includegraphics[width=0.75\textwidth]{fig3.png} \caption{ Histogram of eigenvalues of operator $\log \hat{G}$ from a shallow network.} \label{fig:fig3} \includegraphics[width=0.75\textwidth]{fig4.png} \caption{ Histogram of eigenvalues of operator $\log \hat{G}$ from a deep network.} \label{fig:fig4} \end{center} \end{figure} On Figs. \ref{fig:fig3} and \ref{fig:fig4} we plot histograms of the dynamical eigenvalues of operator $\log \hat{G}$ from the, respectively, shallow and deep networks. As expected, most of the eigenvalues remain near origin and only a fraction of eigenvalues is displaced significantly from $\log \lambda_i \sim 0$. The distribution of the eigenvalues in the shallow network is almost completely symmetric, the skewness after $10000$ epochs is $\mu_3 \approx - 2.7 \times 10^{-10}$, the learning efficiency is suppressed and, as a result, the variance remains small $\mu_2\approx 1.84$. In contrast, the distribution of eigenvalues in the deep network is not symmetric, the skewness after $10000$ epochs is more negative $\mu_3 \approx -1.7$, the learning efficiency is enhanced and the variance grows larger $\mu_2\approx 2.44$. There is a clear gap between the smallest and larger eigenvalues (marked by red arrows on Fig. \ref{fig:fig4}) which can be seen after $10000$ epochs at $\log \lambda \approx -3.0$, after $1000$ epochs at $\log \lambda \approx -2.5$ and may be even after $100$ epochs at $\log \lambda \approx -2.3$. This gap is expected to be at unstable maximum defined by equation \eqref{eq:unstable_max} which implies that after $100$ epochs $\beta \approx 1.37$, after $1000$ epochs $\beta \approx 1.40$ and after $10000$ epochs $\beta \approx 1.47$. In the shallow network the gap cannot be clearly identified since it is closer to the origin and the inverse temperature parameter $\beta$ is smaller. Also note that while the smallest eigenvalues move to smaller values, to satisfy \eqref{eq:eig_log} the largest eigenvalues must move to larger values. Recall, that the largest eigenvalues describe the complexity of the network \eqref{eq:C_num} and the increase of the largest eigenvalues represents a decrease in the complexity of the network. In the previous paragraph, we estimated the values of $\beta$ by identifying a gap (marked by red arrows on Figs. \ref{fig:fig4}) between the smallest eigenvalues and the rest. However, as one can see from Fig. \ref{fig:fig4} the smallest eigenvalues $\log \lambda_i < -\log \beta$ keep moving to smaller values together with $-\log \beta$. This suggests that (instead of using equation \eqref{eq:C_num}) we can try to define an approximate complexity by a sum of a fixed number of the largest eigenvalues, \begin{equation} C_{n}({\bf b}, \hat{w}) = -\frac{1}{2} \sum_{i = 1}^n \log(\lambda_i) + \frac{N}{2} \log (2\pi), \end{equation} where it is assumed that the eigenvalues are ordered $\lambda_1 \ge \lambda_2 \ge ... \ge \lambda_N$. On Fig. \ref{fig:fig5}\begin{figure}[] \begin{center} \includegraphics[width=0.81\textwidth]{fig5.png} \caption{ Complexity $C({\bf b}, \hat{w})$ of a deep neural network as a function of the number of training epochs.} \label{fig:fig5} \includegraphics[width=0.81\textwidth]{fig6.png} \caption{ Complexity $C({\bf b}, \hat{w})$ of a deep neural network as a function of the bulk loss $\log U$.} \label{fig:fig6} \end{center} \end{figure} we plot two (limiting) complexities by summing over twenty largest eigenvalues, $C_{20}({\bf b}, \hat{w})$, (blue line) and by summing over all but twenty smallest eigenvalues, $C_{834}({\bf b}, \hat{w})$, (red line). Evidently, up to an additive constant, the behavior of both curves is similar and so either one (or anyone in-between) can be used to study a relaxation of the system towards equilibrium. On Fig. \ref{fig:fig6} we plot the same complexities, but as a function of the bulk loss $\log U$. Both functions are nearly linear with slopes of order one: $C_{20}({\bf b}, \hat{w}) \approx 769+ 1.25 \log U$ for the blue line and $C_{834}({\bf b}, \hat{w}) \approx 772 + 1.41 \log U$ for the red line. In fact the linear dependance is in agreement with the second law of learning \eqref{eq:second_law} which states that the total entropy must decay with learning. Recall the total entropy is a sum of the complexity \eqref{eq:C_num} and thermodynamic entropy \eqref{eq:ent_num} (which scales linearly with $\log U$ whenever $N_>$ remains constant) and so it is expected that both quantities would decay with roughly the same rate. There are certainly many other numerical experiments that we could have done, but it should already be evident that the statistical description developed in the paper might actually shed light on what is happening behind scenes in machine learning. We now switch to the most speculative part of the paper by asking if the entire universe on its most fundamental level could be described by a neural network. \section{Entropic mechanics}\label{sec:entropic} Quantum mechanics is a remarkably successful paradigm for modeling physical phenomena observed on a wide range of scales ranging from $10^{-19}$ meters (i.e. high-energy experiments) to $10^{+26}$ meters (i.e. cosmological observations.) The paradigm is so successful that it is widely believed that on the most fundamental level the entire universe is governed by the rules of quantum mechanics and even gravity should somehow emerge from it. This is known as the problem of quantum gravity that so far has not been solved, but some progress has been made in context of AdS/CFT correspondence \cite{Maldacena, Witten, Susskind}, emergent gravity \cite{Jacobson, Verlinde, emergentgravity}, quantum entanglement \cite{Ryu, Swingle,Almheiri} and holographic complexity \cite{Complexity, Complexity1, Complexity2}.\footnote{There seems to be an interesting connection between thermodynamics of learning systems (see Sec. \ref{sec:thermodynamics}) and thermodynamics of holographic complexity. In Ref. \cite{Complexity1} the authors showed that the quantum computational complexity of a holographic states on the anti-de Sitter boundary is dual to an action over a Wheeler-de Witt patch in the bulk. In the learning systems, the complexity function $C({\bf b}, \hat{w})$ is the quantity which best describes the complexity of a boundary state (for example, in a feedforward network $C({\bf b}, \hat{w})$ is the complexity of a neural network which maps the input boundary data to output boundary data with the smallest error) and a thermodynamic free energy $A(\beta)$ is the quantity which best describes the state of the local degrees of freedom in the bulk. According to the First Law of learning \eqref{eq:first_law} the two quantities are in fact related if not in an absolute sense, then at least in a relative sense, i.e. \begin{equation} d A = dU - T d S_0 = T d C. \end{equation} Also note that even the Second Law of learning \eqref{eq:second_law} is somewhat related to the recently proposed Second Law of complexity of quantum states \cite{Complexity2} with the main difference that during learning the complexity $C$ decreases not on its own, but together with the thermodynamic entropy $S_0$. This suggests that there might be a deep connection between learning systems and holographic systems that we still have not figured out.} Although extremely important, the problem of quantum gravity is not the only problem with quantum mechanics. The quantum framework also starts to fall apart with introduction of observers. Everything seems to work very well when observers are kept outside of a quantum system, but it is far less clear how to described macroscopic observers in a quantum system such as the universe itself. The realization of the problem triggered an ongoing debate on the interpretations of quantum mechanics, which remains unsettled to this day. On one side of the debate, there is an increasing number of proponents of the many-worlds interpretation claiming that everything in the universe (including observers) must be governed by the Schr\"odinger equation \cite{Everett}, but then it is not clear how classical probabilities would emerge. One the other side of the debate, there are proponents of the hidden variables theories \cite{Bohm}, but there it is also unclear what is the role of the wave-function in a purely statistical system. It is important to emphasize that a working definition of observers is necessary not only for settling some philosophical debates, but for understanding the results of real physical experiments and cosmological observations. In particular, a self-content, paradoxes-free definition of observers would allow us to understand the significance of Bell's inequalities \cite{Bell} and to make probabilistic prediction in cosmology \cite{Measure}. To resolve the apparent inconsistency (or incompleteness) in our description of the physical world, we shall entertain a (not so new) idea of having a more fundamental theory than quantum mechanics. A working hypothesis is that on the most fundamental level the dynamics of the entire universe is described by a microscopic neural network. If correct, then not only macroscopic observers should emerge from the microscopic neural network (see, for example, \cite{Tononi}), but, more importantly, the equations of quantum mechanics and general relativity should correctly describe an emergent dynamics of the corresponding learning system. Our main goal in this section is to show that quantum mechanics (or, more precisely, Schr\"odinger equation) indeed provides a good description of an optimal neural network not too far from an equilibrium and we postpone the discussion of general relativity until the next section. Note that most of the results in the remainder of this section were originally obtained in Ref. \cite{entropic}, but in a slightly different context and with slightly different assumptions. Recall that equation \eqref{eq:dP} describes evolution of a probability distribution ${p}(\beta, {\bf Q})$ where $Q_{k}$'s (for ${k} \in (1,...,K)$) parametrize the weight matrix $\hat{w}({\bf Q})$ and the bias vector ${\bf b}({\bf Q})$. The equation works well away from an equilibrium, but at an equilibrium the first derivatives of the free energy remain small \begin{equation} \frac{d Q_{{k}}}{d \beta} = \alpha \frac{\partial F}{\partial Q_{k}} \end{equation} and the dominant contribution to the entropy production comes from ``diffusion''. Then we can study evolution of the system along the equilibrium manifold of dimension $K - \tilde{K} \ll K $ (i.e. the number of ``Goldstone'' modes is $K - \tilde{K}$) defined by a (degenerate) maximum of the free energy $F( {\bf Q})$. More precisely, the equilibrium manifold can be described by \begin{eqnarray} \frac{d F(t, {\bf Q})}{dt} = \frac{\partial F(t, {\bf Q})}{\partial t} + \sum _k \frac{d Q_{{k}}}{d t} \frac{\partial F(t, {\bf Q})}{\partial Q_k} \notag\\ = \frac{\partial F(t, {\bf Q})}{\partial t} +\alpha \sum _k \left ( \frac{\partial F(t, {\bf Q})}{\partial Q_k} \right )^2 = 0 \label{eq:F_const} \end{eqnarray} where the first term represents the change of the free energy due to dynamics of $x_i$'s and the second term represents the change in the free energy due to dynamics of $Q_k$'s. Note that instead of studying the dynamics in $\beta$ we switched to a new parameter $t$ (e.g. the number of training epochs) for which the dynamics on small time scales can be approximated by a Fokker-Planck equation \begin{equation} \frac{\partial p(t, {\bf Q})}{\partial t}\approx \frac{D}{2} \sum_{{{k}}} \frac{\partial^2 p(t, {\bf Q})}{\partial {Q}^2_{{{k}}}} = \frac{D}{2} \Delta {p}(t, {\bf Q}) \label{eq:dP3} \end{equation} with a time-independent diffusions coefficient $D$. However, on longer time scales the diffusion must be constrained to satisfy \eqref{eq:F_const}, but in our statistical description we shall only demand that it is satisfied on average, i.e. \begin{equation} \int d^K Q\; {p}(t, {\bf Q}) \left ( \frac{\partial F(t, {\bf Q})}{\partial t} +\alpha \sum _k \left ( \frac{\partial F(t, {\bf Q})}{\partial Q_k} \right )^2\right ) = 0. \label{eq:constraint} \end{equation} For simplicity, we also assume that the diffusion coefficient $D$ does not depend on $\bf Q$ and so no factor ordering problems arise. Then the main problem is to solve for ${p}(t, {\bf Q})$ subject to constraint \eqref{eq:constraint} which is exactly the type of problems considered in Ref. \cite{entropic}. There it was shown that a constrained dynamics can often be described by an approximate Schr\"odinger equation if the so-called principle of stationary entropy production is satisfied: \\ \\ {\bf Principle of Stationary Entropy Production}: {\it The path taken by the system is the one for which the entropy production is stationary. }\\ \\ However, in Sec. \ref{sec:architecture} we argued that in an optimal architecture a closely related principle (of minimum entropy destruction) should be satisfied and, therefore, all that we need to assume is that the microscopic neural network has an optimal architecture. The optimization problem can then be solved by combining into a single functional ${\cal S}(p, F) $ two terms: the total entropy production from time $t=0$ to time $t=T$ and constraint \eqref{eq:constraint} imposed by on the time-dependent free energy, i.e. \begin{eqnarray} {\cal S}(p, F)&=& - \int_0^T dt \frac{d }{d t} \int d^K Q \;\;{p} \log ( {p}) + \int_0^T dt \int d^K Q \, {p} \left ( \frac{\partial F}{\partial t} +\alpha \sum _k \left ( \frac{\partial F}{\partial Q_k} \right )^2\right ) \notag\\ &=& \int_0^T dt \int d^K Q \;\; \left ( - \log ( {p}) \frac{D}{2} \sum_{{{k}}} \frac{\partial^2 p}{\partial {Q}^2_{{{k}}}} + {p} \left ( \frac{\partial F}{\partial t} +\alpha \sum _k \left ( \frac{\partial F}{\partial Q_k} \right )^2\right ) \right ).\label{eq:entropy_production} \end{eqnarray} After integrating by parts and ignoring the boundary terms (assuming that $p$ vanishes at the boundaries of integration) we obtain \begin{eqnarray} {\cal S}(p, F)&=& \int_0^T dt \int d^K Q \;\; \left ( 2 D \sum_{{{k}}} \left ( \frac{\partial \sqrt{p} }{\partial {Q}_{{{k}}}} \right )^2 + {p} \left ( \frac{\partial F}{\partial t} +\alpha \sum _k \left ( \frac{\partial F}{\partial Q_k} \right )^2\right ) \right ) \notag\\ &=& \int_0^T dt \int d^K Q \;\; \sqrt{p} \left ( - 2 D \sum_{{{k}}} \frac{\partial^2 }{\partial {Q}^2_{{{k}}}} +\alpha \sum _k \left ( \frac{\partial F}{\partial Q_k} \right )^2 + \frac{\partial F}{\partial t} \right ) \sqrt{p} \notag\\ &=& \int_0^T dt \int d^K Q \;\; \Psi^* \left ( - 2 D\Delta - i \sqrt{\frac{2D}{\alpha}} \frac{d}{d t} \right ) \Psi \label{eq:Lagrangian} \end{eqnarray} where the wave-function is defined as \begin{equation} \Psi (t, {\bf Q}) \equiv \sqrt{p (t, {\bf Q})} \exp \left (i \sqrt{\frac{\alpha}{2 D}} F(t, {\bf Q}) \right ). \end{equation} Evidently, upon varying \eqref{eq:Lagrangian} we arrive at a Schr\"odinger equation \begin{equation} - i \frac{d}{dt } \Psi (t, {\bf Q}) = \sqrt{ 2D \alpha}\; \Delta \Psi (t, {\bf Q}) \end{equation} whose solutions extremize the functional ${\cal S}(p, F)$ or, in other words, describe a trajectory in the configuration space which minimizes entropy destruction. (See Ref. \cite{entropic} for details). Therefore, we conclude that quantum mechanics (or at least Schr\"odinger equation) can in fact emerge from a microscopic neural network with an optimal architecture near equilibrium. \section{Emergent gravity}\label{sec:gravity} Now we turn to gravity.\footnote{As far as we know the only attempt to describe gravity in terms of quantum neural networks was made in Ref. \cite{Dvali}. However, the main difference with our approach is that the microscopic neural network considered here is not quantum, but statistical. On the other hand, as we have argued in Sec. \ref{sec:entropic}, the quantum behavior of the microscopic neural network is expected and so it is possible that the two systems are equivalent.} If the microscopic neural network has an optimal architecture then it is still the case that the principle of minimum entropy destruction (or, the more general, principle of stationary entropy production) should be satisfied and so the relevant quantity to extremize is still \eqref{eq:entropy_production}, which contains both entropy production (first term) and constraints (second term). What is, however, different is that we must allow for the larger system to be further away from a learning equilibrium and so the number of constraints can be much smaller than the number of parameters $K$. In other words, the dimensionality of the equilibrium manifold (or, if you wish, the number of symmetries) remains very high. This implies that the probability distribution $p(t, {\bf Q})$ should have a higher degree of symmetry and thus can be parametrized $p(\hat{g}, {\bf Q})$ with a (relatively) small number of auxiliary parameters $\hat{g}(t)$. For example, if the probability distribution is parametrized by Gaussian distributions, $p(\hat{g}(t), {\bf Q}) \propto \exp\left (- {\sum_{k,k'} g_{k k'}(t) Q_k Q_{k'} } \right )$, then the optimization problem is to find $\hat{g}(t)$ and ${\bf \Phi}(t, {\bf Q})$ which extremize \eqref{eq:entropy_production}, \begin{equation} {\cal S}(\hat{g}, {\bf \Phi})= \int_0^T dt \sum_k \left \langle - \frac{D}{2} \frac{\partial^2 \log p(\hat{g}(t), {\bf Q})}{\partial {Q}^2_{{{k}}}} \right \rangle + \int_0^T dt \left \langle {\cal L}(\hat{g}(t), {\bf \Phi}(t, {\bf Q}) \right \rangle.\label{eq:Lagrangian2} \end{equation} The first term represents the entropy production and depends only on $\hat{g}$ and the second term represents constraints and depends on both $\hat{g}$ and some parameters ${\bf \Phi}(t, {\bf Q})$ which enforce the constraints. (For example, in the previous section ${\bf \Phi}(t, {\bf Q})$ was given by free energy $F(t, {\bf Q})$ which is to be extremized in an equilibrium). This is what might be happening on a microscopic level, but our task in this section is to only develop a phenomenological model of gravity based on what we already know about general relativity. In gravitational theories the dynamical degrees of freedom are described by a metric tensor $g_{\mu\nu}(x)$ and other fields $\varPhi(x)$ all of which are functions of four space-time coordinates $x = (x^0, x^1, x^2, x^3)$. From that perspective a better parametrization of the probability distribution is given by $g_{\mu\nu}(x)$ and of the constraints by $\varPhi(x)$. Then \eqref{eq:Lagrangian2} can be expressed phenomenologically as \begin{equation} {\cal S}(g_{\mu\nu}, \varPhi) = \int d^{D+1} x\;\sqrt{|g|} \; \left ( - \frac{1}{2\kappa}{R}({g}_{\mu\nu}(x)) + \Lambda \right ) + \int d^{D+1} x\;\sqrt{|g|} \; {\cal L}(g_{\mu\nu}(x), \varPhi(x)) \label{eq:full_action} \end{equation} where, as before, the first term represents the entropy production and the second term represents the constraints. Several comments are in order. First of all, in equation \eqref{eq:Lagrangian2} the parameter $\hat{g}$ was a finite dimensional matrix, but in equation \eqref{eq:full_action} the parameter $g_{\mu\nu}(x)$ is a continuous function and so at best it is an approximate mapping which should break down at some UV scale (e.g. Planck scale). Secondly, even if the metric tensor $g_{\mu\nu}(x)$ is defined only on some very fine-grained lattice, there is a sense of distance between gravitational degrees of freedom which is not present in a neural network. This would be true for a general learning system, but we expect that for a clever choice of local objectives the weight matrix $\hat{w}$ (which is also an adjacency matrix describing the strength of connections between neurons) could be attracted towards a three-dimensional lattice (see \cite{graphflow} for a possible mechanism) and then the space-time locality would emerge. Thirdly, any lattice-like structure would break a general covariance which is known to be a very precise symmetry of nature. Therefore, we must also assume that the local objectives of neurons are such that the general covariance would emerge on large scales (see \cite{spacetime} for a possible mechanism), but exactly how this might work is presently unknown. In the remainder of this section we shall follow closely a phenomenological procedure outline in Ref. \cite{emergentgravity}. We first expand the entropy production term in \eqref{eq:full_action} around equilibrium, i.e. \begin{equation} \frac{1}{2\kappa}{R} = g_{\alpha\beta, \mu} J^{\mu\alpha\beta} \end{equation} where the fluxes are denoted by $J^{{k}\alpha\beta}$ and the generalized forces are taken to be\footnote{Summations over repeated indices are implied everywhere in this section.} \begin{equation} g_{\alpha\beta, \mu } \equiv \frac{\partial g_{\alpha\beta} }{\partial x^{\mu }}. \end{equation} Then we can expand fluxes around local equilibrium to the linear order in generalized forces \begin{equation} J^{\mu\alpha\beta} = L^{\mu\nu\;\alpha\beta\;\gamma\delta} g_{\gamma\delta, \nu} . \end{equation} to obtain \begin{equation} \frac{1}{2\kappa}{R} = L^{\mu\nu\;\alpha\beta\;\gamma\delta} g_{\alpha\beta, \mu} g_{\gamma\delta, \nu } \label{eq:Onsager2}. \end{equation} One can think of \eqref{eq:Onsager2} as a defining equation for the Onsager tensor, but then we are forced to only consider Onsager tensors $ L^{\mu\nu\;\alpha\beta\;\gamma\delta}$ that are symmetric under interchanges $(\mu, \alpha,\beta) \leftrightarrow (\nu, \gamma, \delta)$, i.e. \begin{equation} L^{\mu\nu\;\alpha\beta\;\gamma\delta} = L^{\nu\mu \;\beta\alpha\;\delta\gamma}. \label{eq:onsager_relation} \end{equation} These are the Onsager reciprocity relations \cite{Onsager} for our learning system, but there are also other (trivial) symmetries that one should impose $(\alpha) \leftrightarrow (\beta)$, $(\gamma) \leftrightarrow (\delta)$, due to symmetries of the metric, i.e. \begin{equation} L^{\mu\nu\;\alpha\beta\;\gamma\delta} = L^{\mu\nu\;(\alpha\beta)\;(\gamma\delta)}. \label{eq:correct_choice} \end{equation} The overall space of such tensors is still pretty large, but it turns out that a very simple choice leads to general relativity: \begin{equation} L^{\mu\nu\;\alpha\beta\;\gamma\delta} = \frac{1}{8\kappa} \left ( g^{\alpha\nu} g^{\beta\delta} g^{\mu\gamma} + g^{\alpha\gamma} g^{\beta\nu}g^{\mu\delta} - g^{\alpha\gamma} g^{\beta\delta} g^{\mu\nu} - g^{\alpha\beta} g^{\gamma\delta} g^{\mu\nu} \right ) .\label{eq:Onsager} \end{equation} After integrating by parts, neglecting boundary terms and collecting all other terms we get \begin{eqnarray} \int d^{D+1} x &\sqrt{|g|} &\frac{1}{2\kappa}{R} = \int d^{D+1} x \sqrt{|g|} g^{\mu\nu} \;\; \frac{1}{\kappa} \left (\Gamma^{\alpha}_{\phantom{\alpha}\nu[\mu, \alpha]} + \Gamma^{\beta}_{\phantom{\beta}\nu[\mu} \Gamma^\alpha_{\phantom{\alpha}\alpha]\beta}\right )=\\\notag &=&\int d^{D+1} x \sqrt{|g|} \;\; \frac{1}{8\kappa} \left ( g^{\alpha\nu} g^{\beta\delta} g^{\mu\gamma} +g^{\alpha\gamma} g^{\beta\nu} g^{\mu\delta} -g^{\alpha\gamma} g^{\beta\delta} g^{\mu\nu} -g^{\alpha\beta} g^{\gamma\delta} g^{\mu\nu} \right ) g_{\alpha\beta,\mu} g_{\gamma\delta,\nu}\; \end{eqnarray} where \begin{eqnarray} \Gamma^{\mu}_{\phantom{\mu}\gamma\delta} \equiv \frac{1}{2} g^{\mu\nu} \left ( g_{\nu\gamma,\delta} + g_{\nu\delta,\gamma} - g_{\gamma\delta, \nu} \right ) \;\;\;\;\;\;\;\;\;\;\text{and}\;\;\;\;\;\;\;\; \Gamma^\alpha_{\phantom{\alpha}\mu\nu, \beta} \equiv \frac{\partial}{\partial x^\beta} \Gamma^\alpha_{\phantom{\alpha}\mu\nu}. \end{eqnarray} Therefore, upon varying \eqref{eq:full_action} with respect to the metric $g^{\mu\nu}$ we get the Einstein equations \begin{equation} R_{\mu\nu} - \frac{1}{2} Rg_{\mu\nu} + \Lambda g_{\mu\nu} = \kappa T_{\mu\nu} \end{equation} where the Ricci tensor is \begin{equation} R_{\mu\nu} \equiv 2 \left (\Gamma^{\alpha}_{\phantom{\alpha}\nu[\mu, \alpha]} + \Gamma^{\beta}_{\phantom{\beta}\nu[\mu} \Gamma^\alpha_{\phantom{\alpha}\alpha]\beta}\right ) \end{equation} and the energy-momentum tensor is \begin{equation} T_{\mu\nu} \equiv -\frac{2}{\sqrt{|g|}} \frac{\delta (\sqrt{|g|} {\cal L})}{\delta g^{\mu\nu}}. \end{equation} (See Ref. \cite{emergentgravity} for details). Of course, the expectations are that this result would only hold near equilibrium, and there should be deviations from general relativity when some of the symmetries in the Onsager tensor \eqref{eq:Onsager} are broken. \\ {\it Acknowledgments.} I would like to express my sincere gratitude to my former teacher, Walter Johnson, who introduced me to the subject of artificial neural networks. This work was supported in part by the Foundational Questions Institute (FQXi).
{'timestamp': '2020-06-05T02:19:42', 'yymm': '2004', 'arxiv_id': '2004.09280', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09280'}
arxiv
\section{Introduction} Multiple sclerosis (MS) is a chronic disease of the central nervous system where the insulating covers of nerve cells are damaged, often causing disability. Disease progression can be monitored in the brain using magnetic resonance imaging (MRI) with fluid attenuated inversion recovery (FLAIR) sequences \cite{rovira2015evidence}. Here, MS causes lesions which appear as high-intensity spots. Lesion activity, the appearance of new and enlarging lesions, is the most important biomarker for disease progression \cite{patti2015lesion}. Quantitative lesion parameters, such as volume and amount, require lesion segmentation which is still performed manually \cite{garcia2013review} although it is time-consuming and associated with a high interobserver variability \cite{egger2017mri}. For conventional single-scan lesion segmentation, automated approaches using conventional \cite{roura2015toolbox} and deep learning methods have been proposed \cite{danelakis2018survey}. Lesion activity is derived from two scans from two different time points. Thus, one approach is derive lesion activity from individual segmentation maps. Since this approach is associated with large inconsistencies \cite{garcia2013review}, automated methods have used image differences \cite{ganiler2014subtraction} or deformation fields \cite{salem2018supervised}. Recently, a deep learning approach used a two-path 3D CNN for jointly processing the two volumes and predicting lesion activity maps \cite{krueger2019ms}. Processing two 3D volumes from two time points can be considered a 4D spatio-temporal learning problem. We hypothesize that extending the 4D context by adding a temporal history could improve lesion activity segmentation. MRI scans from the more distant past can be seen as an extended baseline providing additional information on the development of lesions and enable more consistent estimates. For this purpose, we design a new multi-encoder-decoder architecture using convolutional-recurrent units for temporal aggregation. We evaluate whether adding an additional time point from the past improves performance and compare our approach to models based on previous approaches. \section{Methods} \textbf{The dataset} we use is part of observational MS study at the University Hospital of Zurich, Switzerland. In total, we consider $44$ MS cases where each case comes with a follow-up (FU), baseline (BL) and history (HS) FLAIR image. HS was acquired before BL. All scans are resampled to $\SI{1 x 1 x 1}{\milli\metre}$ and we rigidly register BL and HS to FU. Three independent raters labeled new and enlarging lesions using a tool showing both FU and BL. Thus, the task at hand is to predict a 3D lesion activity map $y \in \mathbb{R}^{H\times W\times D}$ which shows the lesion activity between BL and FU using a spatio-temporal tensor $x \in \mathbb{R}^{T\times H\times W\times D}$ consisting of FLAIR images. $H$, $W$ and $D$ are the spatial image dimensions and $T$ is the temporal dimension. Previous approaches used FU and BL ($T=2$) while we investigate using FU, BL and HS ($T\geq 3$). \begin{figure}[htbp] \floatconts {fig:model} {\caption{The deep learning model we propose. In each block we show the number of time points, spatial size and number of feature maps. The model receives FLAIR image volumes as the input.}} {\includegraphics[angle=90,width=1.0\linewidth]{model_convgru.pdf}} \end{figure} \textbf{The deep learning model} we propose is a ResNet-based \cite{he2016deep} multi-encoder-decoder 3D CNN architecture using convolutional gated recurrent units (convGRUs) for temporal aggregation, see \figureref{fig:model}. The encoder processes all $T$ volumes individually and in parallel which can be interpreted as a $T$-path encoder where all paths share weights. Thus, the encoder path consists of 3D convolutional layers that process each volume in parallel. Then, all time points are aggregated using convGRU units. Finally, the decoder processes the aggregated 3D representation for predicting the lesion activity map. We also employ our convolutional-recurrent aggregation strategy for the long-range connections spanning from encoder to decoder. Note that there are previous recurrent models with similar naming to ours \cite{alom2019recurrent,chen2016combining}. Our problem, approach and model are fundamentally different as we use the recurrent units for temporal aggregation between encoder and decoder while previous methods used recurrence for spatial aggregation everywhere in the network. We compare our strategy to the previous approach of simply concatenating the volumes along the feature map dimension for processing in the decoder. The individual volume input size is $128\times 128\times 128$ with a batch size of $1$. Due to the small batch size we use instance normalization \cite{ulyanov2016instance}. Before training, we split off a validation set of $5$ cases for hyperparameter tuning and a test set with $10$ cases for evaluation. During training, we randomly crop subvolumes from the differently-sized scans. We train for $300$ epochs using a learning rate of $\alpha = \num{e-4}$ and exponential learning rate decay. For evaluation, we use multiple, overlapping crops to form an entire lesion activity map for each case. Overlapping regions are averaged. \section{Results and Discussion} \begin{table}[htbp] \floatconts {tab:res}% {\caption{Results for all experiments. We show the mean dice score, lesion-wise false positive rate (LFPR), false-positives (FPs) and lesion-wise true positive rate (LTPR). Lesions are defined as 27-connected components and any positive overlap between prediction and ground-truth is treated as a true positive.}}% {\begin{tabular}{l l l l l} \bfseries Model & \bfseries Dice & \bfseries LFPR & \bfseries FPs & \bfseries LTPR \\ \hline Enc-Dec $T=2$ \cite{krueger2019ms} & $0.62$ & $0.30$ & $1.1$ & $0.81$ \\ Enc-Dec $T=3$ & $0.59$ & $0.35$ & $1.3$ & $0.83$ \\ Enc-convGRU-Dec $T=2$ & $0.63$ & $0.21$ & $0.71$ & $0.81$\\ Enc-convGRU-Dec $T=3$ & $\pmb{0.64}$ & $\pmb{0.19}$ & $\pmb{0.63}$ & $\pmb{0.84}$\\ \hline \end{tabular}} \end{table} Our results are shown in \tableref{tab:res}. Our proposed model (Enc-convGRU-Dec) outperforms the previous approach (Enc-Dec) in terms of all metrics. Even for the conventional case with $T=2$ \cite{krueger2019ms}, our method improves performance. This suggests that recurrent aggregation might be preferable to time point concatenation. Using $T=3$ instead of $T=2$ also improves performance for our model which is not the case for Enc-Dec. Thus, when using a single additional scan, we already observe a slight performance improvement. This might indicate that an additional history is indeed beneficial and provides a more consistent baseline than a single scan. Furthermore, our architecture comes with the advantage that arbitrary numbers of time points can be processed without changing the number of trainable model parameters. Therefore, future work could investigate the potential advantage of a longer history with a larger dataset containing more time points. Furthermore, our approach could be applied with other 4D segmentation problems. \midlacknowledgments{This work was partially supported by AiF grant number ZF4268403TS9 and ZF4026303TS9.}
{'timestamp': '2020-06-02T02:01:36', 'yymm': '2004', 'arxiv_id': '2004.09216', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09216'}
arxiv
\section{Introduction} Supporting human creativity has been considered as one of the grand challenges of Human-Com\-put\-er Interaction (HCI)~\cite{Shneiderman2009}. Crowdsourcing~\cite{howe2006} is a powerful approach for tapping into the collective insights of a diverse crowd of people. The combination of crowdsourcing and creativity support is a promising area of research~\cite{p22-kittur.pdf,Shneiderman2009}. and builds on a long line of work on augmenting human creativity and intellect \cite{Doug_Engelbart-AugmentingHumanIntellect.pdf,GuilfordPresidentialAddress}. More recently, research on supporting creativity has been sparking interest in the field of Human-Computer Interaction \cite{2019_chi-paper.pdf,dc2s22019} and design \cite{cc19workshop}. \begin{marginfigure \begin{minipage}{\marginparwidth}% \centering% \includegraphics[trim={14cm 13cm 45cm 16cm},clip, width=\marginparwidth]{figures/comparison-answerbot.png} \caption{ArticleBot user interface for faceted filtering of ideas.}~\label{fig:articlebot}% \vspace{1em}% \end{minipage}% \end{marginfigure}% \begin{marginfigure \begin{minipage}{\marginparwidth}% \centering% \includegraphics[trim={3.5cm 10.5cm 16cm 4.5cm},clip, width=\marginparwidth]{figures/phase2.jpg}% \caption{CrowdUI user interface to provide justifications for manipulations of the website layout.}~\label{fig:crowdui}% \vspace{1em} \end{minipage}% \end{marginfigure}% \begin{marginfigure \begin{minipage}{\marginparwidth}% \centering% \includegraphics[width=\textwidth]{figures/DUPLEX-v5.png}% \caption{High-level architecture of the situated feedback system.}~\label{fig:concept}% \end{minipage}% \end{marginfigure}% \textit{Crowd feedback systems}~\cite{luther-crowdcrit-cscw2015.pdf,p1433-xu.pdf} are computer-mediated systems that enable creative individuals to collect feedback from a large number of people online. These systems provide an opportunity for asynchronously sourcing feedback, decision support and critique from a crowd with a diverse background. Researchers have investigated ways of increasing the perceived value of crowdsourced feedback~\cite{crowdInnovationCourse-hcomp2015.pdf,a063-krishna-kumaran.pdf}, for instance by using rubrics to structure the feedback \cite{Posts_paper_3.pdf,luther-crowdcrit-cscw2015.pdf} and interactive guidance to scaffold the feedback process \cite{paper55.pdf,mg_critiki_CaC2015_CameraReady.pdf}. Using techniques such as the above, crowdsourcing distributed critique from novice crowds may yield feedback in comparable quality to expert critique \cite{luther-crowdcrit-cscw2015.pdf,Posts_paper_3.pdf}. In the past year, we explored the design space and limitations of crowd feedback systems with three feedback systems that support different types of creative work: \begin{inparaenum \item[] writing, \item[] web design, \item[] and art critique. \end{inparaenum} In the following sections, we give a brief overview of each system. For each system, we provide one idea for future research. \section{ArticleBot: Supporting Exploratory Writing} We designed and tested an intervention to support writers in finding and exploring different ideas and topics~\cite{ArticleBotINTERACT19}. The lightweight system was adapted from Hosio~et~al.~\cite{Hosio:2016:LWC:3056355.3056393}. The system provides decision support in form of short textual ideas that can be sorted according to different criteria (see Figure~\ref{fig:articlebot}). Both the ideas, the criteria, and the rating of each idea across all criteria are provided by the crowd. Currently, the system collects all data up-front in a serendipitous fashion from visitors of a website or in a controlled fashion from crowd workers. While this database of ideas, criteria, and ratings holds value, it is expensive to create in terms of time taken and/or money spent and it is scoped to only one topic. Future work could support writers with data collected from the crowd in real-time. To this end, instead of serendipitously collecting data organically from website visitors, the system could actively crowdsource information in real-time from online labour marketplaces, such as Mechanical Turk. \section{CrowdUI: Supporting Web Design} CrowdUI~\cite{CrowdUI} is a system that allows the community of a website to visually provide their feedback, using the website itself as a canvas. Website visitors can directly manipulate (move, delete, resize) the elements of the webpage. CrowdUI's multi-step process includes a tutorial to familiarise the user with the affordances of the system and a peer review of other users' creations. The system allows designers to inspect the individual adaptations of the user interface. It also provides further decision support by visually aggregating user modifications of the website's user interface in heatmaps. The system was evaluated in a remotely-administered user study with 48 users with promising results. \begin{marginfigure \begin{minipage}{\marginparwidth}% \centering% \includegraphics[width=\marginparwidth]{figures/proto1-cut.png}% \caption{Prototype of the situated feedback elicitation system. Artwork credit: Stéphan Valentin.}~\label{fig:simplex}% \vspace{1em} \end{minipage}% \end{marginfigure}% \begin{marginfigure \begin{minipage}{\marginparwidth}% \centering% \includegraphics[width=0.8\marginparwidth]{figures/Visual.png}% \caption{Example of a type of feedback in the situated feedback system. Artwork credit: Aman Ravi.}~\label{fig:simplexfeedback}% \end{minipage}% \end{marginfigure}% Web designers and developers are faced with many decisions during the website design process. One idea for future work involves crowdsourcing preference judgements from the crowd in a web-based game with a purpose (GWAP) to help the developer in making informed decisions and to explore the space of possible design alternatives. The game would automatically tweak variables in the design space (\textit{e.g.} changing the font style of a headline to bold). It would then elicit a pairwise comparison of the design alternatives from its players, resulting in a ranking of individual attributes. Similar web-based games, for instance \textit{Can't Unsee} (\href{https://cantunsee.space}{https://cantunsee.space}), have been found to be very engaging. \section{SIMPLEX: Eliciting Art Critique} In our third system~\cite{Simplex}, we explored situated crowdsourcing and public displays for supporting artists with summative feedback. The system enables the situated crowd to provide feedback to artists via an installation that consists of two public displays (see Figures~\ref{fig:concept} and \ref{fig:simplex}). A digital artwork is displayed on the main screen of the installation. Feedback is given on the smaller touch screen positioned in front of the main screen. Once feedback is given, a new artwork is displayed on the main screen. In a needfinding study with two artists and a user study with 12 participants, we evaluated eight different types of feedback (see the example in Figure~\ref{fig:simplexfeedback}). Future work will evaluate the ecological feasibility of the SIMPLEX crowd feedback system in a longitudinal field study. The system will be evaluated using a mixed-method approach, combining the quantitative analysis of interaction data with qualitative insights from semi-structured interviews. Further evaluation could also include the application of the system in a specific use case, \textit{e.g.} in the context of a design-oriented University course to evaluate architectural designs from different perspectives. \section{Conclusion} In this position paper, we presented three crowd feedback systems that support creative work. Our exploration of different modes and types of feedback highlighted that there are many opportunities to support creative work with crowd feedback, beyond mere text-based feedback. Our ongoing work in the form of a structured literature review will guide the development of a taxonomy of activities that creative individuals engage in when they evaluate feedback from the crowd. This work will culminate in a conceptual framework to highlight critical processes that affect the sensemaking of crowdsourced feedback. We envision this design framework to create a basis for discussing challenges and issues related to the design of interactive feedback elicitation systems. \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2020-04-21T02:25:08', 'yymm': '2004', 'arxiv_id': '2004.09204', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09204'}
arxiv
\section{Introduction} Reinforcement Learning (RL) has demonstrated its effectiveness in a variety of tasks~\cite{mnih2015human,openai2018openaifive,jaderberg2018human}. However, a common challenge for RL methods is their severe dependency on a well-designed reward signal. Fortunately, the reward signals will be unnecessary if we consider to Learn from Demonstrations (LfD), or commonly known as Imitation Learning (IL)~\cite{hussein2017imitation}. In this paper, we focus on the common setting of IL, where agents learn their policies from the samples of trajectories from the expert, without any further access to the expert or explicit rewards. Classic solutions for IL such as behavior cloning (BC)~\cite{pomerleau1991efficient} aim to minimize 1-step deviation error along the provided expert trajectories with supervised learning, which suffers seriously from an extensive collection of expert data and compounding error caused by covariate shift ~\cite{ross2010efficient,ross2011reduction}. As an alternative, Inverse Reinforcement Learning (IRL)~\cite{ng2000algorithms,abbeel2004apprenticeship,fu2017learning} tries to recover a reward function from the expert and subsequently train an RL policy under that, yet such a bi-level optimization scheme can result in high computational cost. The recent solution as GAIL~\cite{ho2016generative} derived from Max-Entropy IRL (MaxEnt IRL) formulates the IL problem as occupancy measure matching. GAIL takes advantage of GAN~\cite{goodfellow2014generative} to minimize the Jensen-Shannon divergence between the agent's occupancy measures and the expert's while it also inherits the notorious defects of GAN, including training instability and mode dropping~\cite{brock2018large}. Analogous to IL, learning statistical models from given data and generating similar samples has been an important topic in the generative model community. Among them, recent energy-based models (EBMs) have gained much attention because of the simplicity and flexibility in likelihood estimation~\cite{du2019implicit,song2019sliced}. In this paper, we propose to leverage the advantages of EBMs to solve IL with a novel framework called Energy-Based Imitation Learning (EBIL), which addresses the problem via expert energy estimation in a two-step fashion: first estimates an unnormalized probability density (\textit{a.k.a.} energy) of expert's occupancy measure through score matching, and then takes the energy to construct a surrogate reward function as a guidance for the agent to learn the desired policy. In experiments, we first verify our idea in a simple one-dimensional environment by visualizing the estimated reward and the induced policy; then we evaluate our algorithm on extensive high-dimensional continuous control benchmarks, showing that EBIL can always achieve comparable or better performance than SoTA methods. In addition to the stability and flexibility of EBMs, EBIL also enjoys more efficiency thanks to the two-step training fashion that overcomes the undesired slow alternate training process as in IRL and GAIL. Though the underlying intuition behind our proposed methodology was to match the expert's occupancy measure through EBM, we surprisingly find that there indeed exists a non-trivial connection between our method and previous MaxEnt IRL methods. Thus we further provide a theoretical illustration of the relation between EBIL and MaxEnt IRL, showing that EBIL is a dual problem of MaxEnt IRL but simpler and more efficient. Compared with MaxEnt IRL, EBIL can provide more flexibility on the choice to train the expert's EBM and enable us to avoid the intractable estimation of the partition function. The analysis, along with past works provides a holistic view of the role of EBM in imitation learning. \section{Preliminaries} In this section, we present the definition of reinforcement learning problem, imitation learning and energy-based models along with the notations. \subsection{Maximum Entropy Reinforcement Learning} Reinforcement Learning (RL) problems can be seen as Markov Decision Process (MDP), which is represented as a tuple $\caM = \langle \caS, \caA, P, \rho_0, r, \gamma \rangle$, where $\caS$ is the set of states, $\caA$ represents the action space of the agent, $P: \caS \times \caA \times \caS \rightarrow \mathbb{R}$ is the state transition probability distribution, $\rho_0: \caS\rightarrow\mathbb{R}$ is the distribution of the initial state $s^0$, and $\gamma\in [0,1]$ is the discounted factor. The agent holds its policy $\pi(a|s): \caS \times \caA \rightarrow [0, 1]$ to make decisions and receive rewards defined as $r: \caS \times \caA \rightarrow \mathbb{R}$. For an arbitrary function $f: \langle s, a \rangle \rightarrow \mathbb{R}$, it is easy to show that $\bbE_\pi[f(s,a)]=\bbE_{s\sim P, a\sim \pi}[f(s,a)]\triangleq \bbE \left [\sum_{t=0}^\infty \gamma^t f(s_t,a_t) \right ]$, where $s_{0}\sim \rho_0$, $a_t\sim\pi(\cdot|s_t)$, $s_{t+1}\sim P(\cdot|a_t,s_t)$. The normal objective of RL is to get an optimal policy such that it can maximize its own total expected return $R \triangleq \bbE_\pi[r(s,a)] = \bbE \left [\sum_{t=0}^\infty \gamma^t r(s_t, a_t) \right ]$, while Maximum Entropy Reinforcement Learning (MaxEnt RL) augments the objective with an entropy term to find a stochastic policy that can also maximize its entropy at each visited state~\cite{ho2016generative,haarnoja2017reinforcement} as: \begin{equation}\label{eq:maxent-rl} \pi^* = \argmax_{\pi} \bbE_\pi\left [r(s,a)\right ]+\alpha H(\pi)~, \end{equation} where $H(\pi) \triangleq E_{\pi}[- \log \pi(a|s)]$ is the $\gamma$-discounted causal entropy~\cite{bloem2014infinite} and the temperature hyperparameter $\alpha$ is used to determine the relative importance of entropy as a reward, we will let $\alpha=1$ by default in the following part of this paper. \iffalse \begin{equation}\label{eq:rl} \pi^* = \argmax_{\pi} \bbE_\pi \left [r(s,a) \right ]~. \end{equation} \fi \textbf{Occupancy Measure.} The agent generates trajectories, \textit{i.e.}, state-action $(s,a)$ pairs when they interact with the environment with policy $\pi$ lead to the definition of occupancy measure $\rho_\pi^{s,a}(s,a)$ or $\rho_\pi^{s}(s)$ as the density of occurrence of states or state-action pairs: \begin{equation} \begin{aligned} \rho_{\pi}^{s,a}(s,a) &= \sum_{t=0}^{\infty}\gamma^t P(s_t=s, a_t=s|\pi)\\ &= \pi(a|s)\sum_{t=0}^{\infty}\gamma^t P(s_t=s|\pi) = \pi(a|s)\rho_{\pi}^{s}(s)~, \end{aligned} \end{equation} which allows us to write that: $\bbE_{\pi}[\boldsymbol{\cdot}]=\sum_{s,a}\rho_{\pi}^{s,a}(s,a)[\boldsymbol{\cdot} ]=\bbE_{(s,a)\sim \rho_{\pi}^{s,a}}[\boldsymbol{\cdot}]$. For simplicity, we will denote $\rho_\pi^{s,a}$ as $\rho_\pi$ without further explanation in the following sections, and we have $\rho_\pi \in \caD\triangleq\{ \rho_\pi: \pi\in\Pi \}$. \subsection{Imitation Learning} Imitation learning (IL) \cite{hussein2017imitation} studies the task of Learning from Demonstrations (LfD), which aims to learn a policy from expert demonstrations which typically consists the expert trajectories interacted with environments without receiving reward signals from environments. General IL objective tries to minimize the distance between the actions taken by policy $\pi$ and expert policy $\pi_E$: \begin{equation}\label{eq:il} \pi^* = \argmin_\pi \mathbb{E}_{s \sim \rho_{\pi}^{s}}\left [\ell \left ({\pi_E}(\cdot | s), \pi(\cdot | s)\right )\right ]~, \end{equation} where $\ell$ denotes some distance metric. However, as we do not ask the expert agent for further demonstrations, it is always hard to optimize \eq{eq:il} with only expert trajectories accessible. Thus, Behavior Cloning (BC)~\cite{pomerleau1991efficient} provides a straightforward method by learning the policy in a supervised way, where the objective is represented as a Maximum Likelihood Estimation (MLE): \begin{equation} \hat{\pi}^* = \argmin_\pi \mathbb{E}_{s \sim \rho_{\pi_E}^s}\left [\ell \left ({\pi_E}(\cdot | s), \pi(\cdot | s)\right )\right ]~, \end{equation} which suffers from covariate shift problem for the i.i.d. state assumption. Another branch of methods are under the basic idea of Inverse Reinforcement Learning (IRL) \cite{ng2000algorithms} that tries to recover the reward function $r^*$ in the environments. An underlying assumption of IRL is that the reward function $r^*$ will evaluate the expert policy as the optimal policy in the environment. Formally, \begin{equation}\label{irl} \pi^* = \argmax_\pi \mathbb{E}_{(s,a) \sim \rho_{\pi}}\left [r^*(s,a)\right ]~, \end{equation} which suffers typically from a high complexity for its bi-level optimization and can cause ambiguity resulting in different reward functions. Derived from Max-Entropy IRL (MaxEntIRL) which solves the ambiguity of normal IRL methods, generative Adversarial Imitation Learning (GAIL) \cite{ho2016generative} shows that the objective of MaxEntIRL is a dual problem of occupancy measure matching, and thus can be solved through generative models such as GAN. Specifically, it shows that the policy learned by RL on the reward recovered by IRL can be characterized by \begin{equation}\label{eq:rl-irl} \begin{aligned} {\textnormal{l}} \circ \irl_\psi(\pi_E) = \argmin_\pi - H(\pi) + \psi^*(\rho_\pi - \rho_{\pi_E})~, \end{aligned} \end{equation} where $\psi$ is the regularizer, and $f^*:\bbR^{\caS\times\caA}\rightarrow\overline{\bbR}$ is the convex conjugate for an arbitrary function $f:\bbR^{\caS\times\caA}\rightarrow \overline{\bbR}$ given by $f^*(x)=\sup_{y\in\bbR^{\caS\times\caA}}x^Ty - f(y)$. \eq{eq:rl-irl} shows that various settings of $\psi$ can be seen as a distance metric leading to various solutions of imitation learning. \subsection{Energy-Based Models} \label{subsec:ebm} For a random variable $X\sim p(x)$, energy-based model (EBM) \cite{lecun2006tutorial} builds the density of data by estimating the energy function $E(x)$ with sample $x$ as \begin{equation} \begin{aligned} p(x) = \frac{1}{Z}\exp(-E(x))~, \end{aligned} \end{equation} where $Z=\int\exp(-E(x))dx$ is the partition function, which is normally intractable to compute exactly for high-dimensional $x$. The energy function $E$ can be seen as the unnormalized log-density of data which is always optimized to maximize the likelihood of the data. Typically, the estimation of the partition function $Z$ is computationally expensive, which requires sampling from the Boltzmann distribution $p(x)$ within the inner loop of learning. \section{Imitation Learning via Expert Energy Estimation} \label{sec:ebil} In this section, we provide an energy-based perspective of IL and propose to learn the agent's policy via estimating the energy of the expert demonstrations. \subsection{Energy-Based Imitation Learning} \label{subsec:EBIL} IL requires to recover expert policy $\pi_E$ from static demonstrations which consists of expert trajectories and cannot be further expanded by interacting with the expert agent. Instead of minimizing the distance between every action taken by agent policy and expert's based on expert trajectories as shown in \eq{eq:il}, or find the policy which is optimal that achieves the maximum accumulated reward under unknown reward function, \eq{eq:rl-irl} prescribes that we are able to formulate the problem of recovering expert policy based on its occupancy measure. Formally, denoting the set of policies as $\Pi$ and the set of valid occupancy as measures $\caD \triangleq \{ \rho_\pi>0 : \pi \in \Pi \}$, \lm{lm:occupancy} shows the one-to-one correspondence between $\Pi$ and $\caD$: \begin{lemma}[Theorem 2 of \cite{syed2008apprenticeship}]\label{lm:occupancy} If $\rho \in \caD$, then $\rho$ is the occupancy measure for $\pi_\rho(a|s) \triangleq \frac{\rho(s,a)}{\sum_{a'}\rho(s,a')}$, and $\pi_\rho$ is the only policy whose occupancy measure is $\rho$. \end{lemma} \vspace{-2pt} Thus, the occupancy measure can be used as an alternative in the general IL objective shown in \eq{eq:il}. Applying KL divergence as the distance metric, we could construct the IL objective as minimizing the reverse KL divergence $\kld$ of between the agent's occupancy measure and expert's: \begin{equation}\label{eq:kl-il} \pi^* = \argmin_{\pi} \kld ( \rho_\pi \| \rho_{{\pi_E}})~. \end{equation} \begin{proposition}\label{prop:kl-il} The optimal solution for the reverse KL divergence objective of IL shown in \eq{eq:kl-il} is that $\pi^*={\pi_E}$. \end{proposition} \vspace{-6pt} \begin{proof} It is obvious that the solution of \eq{eq:kl-il} is unique since $\kld$ is convex for $\rho_\pi$, which achieves the optimal value iff $\rho_\pi = \rho_{{\pi_E}}$. According to \lm{lm:occupancy}, we can recover policy ${\pi_E}$ if we can recover the occupancy measure of expert policy. Thus the optimal solution is that $\pi^* = {\pi_E}$. \end{proof} Considering to model the normalized occupancy measure with Boltzmann distribution, the density can be represented by an EBM as \begin{equation}\label{eq:ebm} (1-\gamma)\rho_\pi(s,a) = \frac{1}{Z}\exp(-E(s,a))~, \end{equation} where leads to the following proposition. \begin{proposition}\label{prop:eb-il} The reverse KL divergence objective of IL \eq{eq:kl-il} is equivalent to the following of Energy-Based Imitation Learning (EBIL) objective \eq{eq:eb-il}: \iffalse Thus we take \eq{eq:ebm} into \eq{eq:kl-il} for both policy $\pi$ and ${\pi_E}$, we get that: \begin{equation}\label{eq:kl-induce} \begin{aligned} \kld ( \rho_\pi \| \rho_{{\pi_E}}) &= \sum_{s,a} \rho_\pi(s,a) \log \frac{\rho_\pi(s,a)}{\rho_{\pi_E}(s,a)}\\ &= \sum_{s,a}\rho_\pi\left( \log{\rho_\pi(s,a)} - \log{\frac{e^{-E_{\pi_E}(s,a)}}{Z'}} \right )\\ &= \sum_{s,a}\rho_\pi\left(E_{\pi_E}(s,a)+\log{\rho_\pi(s,a)} + \log{Z'}\right )\\ &= \bbE_\pi \left[E_{\pi_E}(s,a)\right ]+\sum_{s,a}\rho_\pi\log{\rho_\pi(s,a)} + \text{const}\\ &= \bbE_\pi \left[E_{\pi_E}(s,a)\right ]+\sum_{s,a}\rho_\pi\log{\rho_\pi(s,a)} -\log{\sum_{s,a'}\rho(s,a')}+ \text{const}\\ &= \bbE_\pi \left[E_{\pi_E}(s,a)\right ]+\sum_{s,a}\rho_\pi\log{\left [ \rho_\pi(s,a)/\sum_{a'}\rho(s,a')\right ]}+ \text{const}\\ &= \bbE_\pi \left[E_{\pi_E}(s,a)\right ] - \overline{H}\left (\rho_\pi(s,a) \right ) + \text{const} ~, \end{aligned} \end{equation} where $\overline{H}=-\sum_{s,a}\rho_\pi\log{\rho_\pi(s,a)/\sum_{a'}\rho(s,a')}$ is the entropy of the occupancy measure, $E_{\pi_E}$ is the EBM of policy ${\pi_E}$ and $Z'$ is its partition function. \begin{lemma}[Lemma 3 of \cite{ho2016generative}] $\overline{H}$ is strictly concave, and for all $\pi \in \Pi$ and $\rho \in \caD$, we have $H(\pi) = \overline{H}(\rho_\pi)$ and $\overline{H}(\rho)=H(\pi_\rho)$. \end{lemma} Thus, \eq{eq:kl-il} in the end lead to the objective function of Energy-Based Imitation Learning (EBIL) as: \fi \begin{equation}\label{eq:eb-il} \pi^* = \argmax_{\pi} \bbE_\pi \left[-E_{\pi_E}(s,a)\right ] + H(\pi)~. \end{equation} \end{proposition} \vspace{-6pt} The proof of \prop{prop:eb-il} is in \ap{ap:eb-il}. A key observation is that \eq{eq:eb-il} provides exactly the same form as the objective of MaxEnt RL shown in \eq{eq:maxent-rl}, and thus we can just estimate the energy of expert data as a surrogate reward function without involving the intractable partition function $Z$\footnote{One may notice that according to \lm{lm:occupancy}, we can simply recover the expert policy directly through $\pi^*=\exp(-E(s,a))/\sum_{a'}{\exp{(-E(s,a'))}}$. However, this may be hard to generalize to continuous or high-dimensional action space in practice. For more discussions one can refer to \se{ap:ebil-sac}.}. Generally, we can choose the reward function as $r(s,a)=h(-E_{\pi_E}(s,a))$ where $h$ is a monotonically increasing linear function to keep the objective of \eq{eq:eb-il} still true. Therefore, EBIL that learns with MaxEnt RL using the expert energy function as the reward function aims to minimize the reverse KL divergence between the agent's occupancy measure and the expert's. It is worth noting that if we remove the entropy term to construct a standard RL objective, then it will collapse into minimizing the cross entropy of the occupancy measure rather than the KL divergence. \subsection{Expert Energy Estimation with Demonstrations} As described above, our reward function is determined by $E_{{\pi_E}}(s,a)$, a learned energy function of the occupancy measure. In this section, we elaborate on how to estimate $E_{{\pi_E}}(s,a)$ from expert demonstrations. Specifically, in this paper, we leverage Deep Energy Estimator Networks (DEEN)~\cite{saremi2018deep}, a scalable and efficient algorithm to directly estimate the energy of expert's occupancy measure of policy via a differentiable framework without involving the intractable estimation of the normalizing constant. Then we can take the estimated energy as the surrogate reward to train the agent policy. Formally, let the random variable $X=g(s,a)\sim g(\rho_{\pi_E}(s,a))$. Let the random variable $Y$ be the noisy observation of $X$ that $y\sim x+N(0, \sigma^2I)$, \textit{e.g.}, $y$ is derived from samples $x$ by adding with white Gaussian noise $\xi\sim N(0, \sigma^2I)$. The empirical Bayes least square estimator, \textit{i.e.}, the optimal denoising function $g(y)$ for the white Gaussian noise, is solved as \begin{equation} \begin{aligned}\label{eq:denoise} g(y) = y + \sigma^2\nabla_y\log{p(y)}~. \end{aligned} \end{equation} Such a function can be trained with a feedforward neural network $\hat{g}$ by denoising each sample $y_i \in Y$ to recover $x_i \in X$, which can be implemented with a Denoising Autoencoder (DAE)~\cite{vincent2008extracting}. Then we can use the DAE $\hat{g}$ to approximate the score function $\nabla_y \log p(y)$ of the corrupted distribution by $\nabla_y \log p(y) \propto \hat{g}(y) - y$~\cite{robbins1955empirical,miyasawa1961empirical,raphan2011least}. However, one should note that the DAE does not provide the energy function but instead approximates the score function -- the gradient of $\log \rho_\pi(s,a)$, which cannot be adopted as the vital reward function. Thus, in order to estimate the EBM of expert's state-action pairs provided through demonstration data, we consider to parameterize the energy function $E_\theta(y)$ with a neural network explicitly. As shown in \cite{saremi2018deep}, such a network called DEEN can be trained by minimizing the following objective: \begin{equation}\label{eq:deen} \argmin_{\theta} \sum_{x_i\in X, y_i\in Y} \left \| x_i - y_i + \sigma^2\frac{\partial E_\theta(y=y_i)}{\partial y} \right \|^2~, \end{equation} which ensures the relation of score function $\partial E_\theta(y)/\partial y$ shown in \eq{eq:denoise}. It is worth noting that the EBM estimates the energy of the noisy samples. This can be seen as a Parzen window estimation of $p(x)$ with variance $\sigma^2$ as the smoothing parameter~\cite{saremi2019neural,vincent2011connection}. A trivial problem here is that \eq{eq:deen} requires the samples (state-action pairs) to be continuous so that the gradient can be accurately computed. Actually, EBIL can be easily expanded to discrete space by using other energy estimation methods, \textit{e.g.}, Noise Contrastive Estimation~\cite{gutmann2010noise}. In this work, we concentrate on the continuous space and leave the discrete version in the future. In practice, we learn the EBM of expert data from off-line demonstrations and construct the reward function, which will be fixed until the end to help agent learn its policy with a normal RL procedure. Specifically, we construct the surrogate reward function $\hat{r}(s,a)$ as follows: \begin{equation}\label{eq:reward} \hat{r}(s,a) = h(-E_{{\pi_E}}(s,a))~, \end{equation} where $h(x)$ is a monotonically increasing linear function, which can be specified for different environments. Formally, the overall EBIL algorithm is presented in \alg{alg:EBIL} of \ap{ap:algo} . \section{Discussions} \label{sec:discussion} In this paper, we propose to estimate the energy function from expert demonstrations directly, then regard it as the surrogate reward function to force the agent to learn a good policy that can match the occupancy measure of the expert. Interestingly, MaxEnt IRL can be seen as a special implementation of EBM, which constructs the expert demonstrations as a Boltzmann distribution of the cost / reward function, and tries to extract optimal policy from it. In this section, we theoretically clarify the relation between EBIL and MaxEnt IRL, and show that EBIL actually can be seen as a simplified and efficient solution for MaxEnt IRL. IRL aims to recover a cost or reward, under which the set of demonstrations are near-optimal. However, the optimal solution is still underdefined. To that end, MaxEnt IRL resolves the reward ambiguity problem in normal IRL by employing the principle of maximum entropy~\cite{ziebart2008maximum,ziebart2010modeling,bloem2014infinite}, which introduces probabilistic models to explain suboptimal behaviors as noise. More specifically, MaxEnt IRL models the paths in demonstrations using a Boltzmann distribution, where the energy is given by the unknown reward function $\hat{r}^*$: \begin{equation} \label{eq:maxent-irl} p_{\hat{r}^*}(\tau) = \frac{1}{Z}\exp{(\hat{r}^*(\tau))}~, \end{equation} where $\tau=\{ s_0, a_0, \cdots, s_T, a_T \}$ is a trajectory of state-action pairs and $T$ is its length; $\hat{r}^*(\tau)=\sum_{t}\hat{r}^*(s_t,a_t)$ is the reward function, under which the expert demonstrations are optimal; $Z$ is the partition function.\footnote{Note that \eq{eq:maxent-irl} is formulated under the deterministic MDP setting. A general form for stochastic MDP is derived in \cite{ziebart2008maximum,ziebart2010modeling} yet owns similar analysis: the probability of a trajectory is decomposed as the product of conditional probabilities of the states $s_t$, which can factor out of all likelihood ratios since they are not affected by the reward function.} Similar to other EBMs, the parameters of the reward function is optimized to maximize the likelihood of expert trajectories. Under this model, ultimately we hope that our policy can generate any trajectories with the probability increases exponentially as the return gets higher, and we can obtain the desired optimal trajectories with the highest likelihood. Following previous work, we focus on the maximum casual entropy IRL \cite{ziebart2008maximum,ziebart2010modeling}, which aims to maximize the entropy of the distribution over paths under the constraints of feature matching that can be regarded as the matching of the reward. Formally, maximum causal entropy IRL can be represented as the following optimization problem~\cite{ho2016generative}: \begin{equation}\label{eq:irl-cas} \begin{aligned} \hat{r}^* &= \argmax_{\hat{r}} \bbE_{{\pi_E}}\left [\hat{r}(s,a) \right ] - \left ( \max_{\pi\in\Pi} \bbE_{\pi}\left [\hat{r}(s,a)\right ] + H(\pi) \right ) ~, \end{aligned} \end{equation} where $H(\pi) := \mathbb{E}_\pi [-\log \pi (a|s)]$ is the causal entropy~\cite{bloem2014infinite} of the policy $\pi$. \subsection{EBIL is a Dual Problem of MaxEnt IRL} Now we first illustrate that EBIL (\eq{eq:kl-il}) is a dual of the above MaxEnt IRL problem. The proof sketch is to show that EBIL is an instance of occupancy measure matching problem which has been proven to be a dual problem of MaxEnt IRL. \begin{lemma}\label{lm:dual} IRL is a dual of the following occupancy measure matching problem and the induced optimal policy is the primal optimum which matches the expert’s occupancy measure $\rho_{\pi_E}$: \begin{equation}\label{eq:irl-dual} \min_{\rho_\pi\in\caD} \overline{H}(\rho_\pi) \text{ subject to } \rho_\pi(s,a) = \rho_{\pi_E}(s,a) \text{ } \forall s \in \caS, a \in \caA~. \end{equation} \end{lemma} \begin{proposition}\label{prop:ebil-dual} The EBIL objective \eq{eq:kl-il} is an instance of the occupancy measure matching problem \eq{eq:irl-dual}. \end{proposition} The proof of \lm{lm:dual} can be refered to the Section 3 of \cite{ho2016generative}, and the proof of \prop{prop:ebil-dual} is shown in \ap{ap:ebil-dual}. Combining \lm{lm:dual} and \prop{prop:ebil-dual}, we have that EBIL is a dual problem of MaxEnt IRL. \subsection{EBIL is More Efficient than IRL} Now we are going to illustrate why EBIL is a more efficient solution. Recall that the intuition of MaxEnt IRL is to regard the demonstrations as a Boltzmann distribution of the reward function, and then induce the optimal policy. Suppose that we have already recovered the optimal reward function $\hat{r}^*$, then the optimal policy is induced by the following practical forward MaxEnt RL procedure: \begin{equation}\label{eq:rl-hr} \pi^* = \argmax_{\pi} \bbE_\pi\left [\hat{r}^*(s,a)\right ]+ H(\pi)~. \end{equation} Now we further demonstrate that EBIL aims to seek the same policy, while through a simplified and more efficient training procedure. \begin{proposition}\label{prop:tau-kl} Denote $\tau$ and $\tau_E$ are trajectories sampled by the agent and the expert respectively, and suppose we have the optimal reward function $\hat{r}^*$, then the policy $\pi^*$ induced by $\hat{r}^*$ is the optimal solution to the following optimization problem: \begin{equation}\label{eq:tau-kl} \begin{aligned} \min_\pi \kld(p(\tau)\|p(\tau_E))~. \end{aligned} \end{equation} \end{proposition} \begin{proposition}\label{prop:kl-kl} The optimization problem \eq{eq:tau-kl} is equivalent to the KL divergence IL objective \eq{eq:kl-il} and the EBIL objective \eq{eq:eb-il}. \end{proposition} The proof for these two propositions are in \ap{ap:tau-kl} and \ap{ap:kl-kl} separately. These two propositions together reveal the optimal policy obtained from EBIL is the same as the one from MaxEnt IRL when the optimal reward function is recovered. However, the latter one is indirect and much more computationally expensive. Primitively, as shown in \eq{eq:irl-cas}, IRL methods are in fact aimed to recover the optimal reward function (served as an EBM) by maximum likelihood on the expert trajectories instead of directly learning the policy and cannot avoid estimating the non-trivial partition function $Z$, which is always hard, especially in high-dimensional spaces. The SoTA IRL method, AIRL\cite{fu2017learning}, as we shown in \se{sec:one-domain} and \ap{ap:airl}, actually does not recover the energy. By contrast, EBIL is essentially a fixed-reward-based method that seeks to learn the policy guided by the pre-estimated energy of expert's occupancy measure, which shows much more efficiency and provides more flexible and general choices on training the expert's EBM. As a supplementary statement, \cite{finn2016connection} reveals the close relationship among Guided Cost Learning~\cite{finn2016guided} (a sample-based algorithm of MaxEnt IRL), GAIL and EBMs. Besides, \cite{ghasemipour2019divergence} also presents a unified perspective among previous IL algorithms and discuss in a divergence minimization view similar as ours shown in \se{subsec:EBIL}. Therefore, all of these methods show connections among each other. \section{Related Work} Instead of seeking to alternatively update the policy and the reward function as in IRL and GAIL, many recent works of IL aim to learn a fixed reward function directly from expert demonstrations and then apply a normal reinforcement learning procedure with that reward function. Although this idea can be found inherently in previous GMMIL work~\cite{kim2018imitation} that utilizes the maximum mean discrepancy as the distance metric to guide training, it is recently proposed by Random Expert Distillation (RED) \cite{wang2019red}, which employs the idea of Random Network Distillation \cite{burda2018rnd} to estimate the support of expert policy, and compute the reward function by the loss of fitting a random neural network. In addition, Disagreement-Regularized Imitation Learning \cite{brantley2020disagreementregularized} constructs the reward function using the disagreement in their predictions of an ensemble of policies trained on the demonstration data, which is optimized together with a supervised behavioral cloning cost. Instead of using a learned reward function, the fixed reward of Soft-Q Imitation Learning \cite{reddy2019softqil} applies constant rewards by setting positive rewards for the expert state-actions and zero rewards for other ones, which is optimized with the off-policy SQL algorithm~\cite{haarnoja2018soft}. Our EBIL relies highly on EBMs, which have played an important role in a wide range of tasks including image modeling, trajectory modeling and continual online learning \cite{Du2019generalization}. Thanks to the appealing features, EBMs have been introduced into many RL literature, for instance, parameterized as value function~\cite{sallans2004valueEBM}, employed in the actor-critic framework~\cite{heess2012acEBMs}, applied to MaxEnt RL~\cite{haarnoja2017reinforcement} and model-based RL regularization~\cite{boney2019regularizing}. However, EBMs are always difficult to train due to the partition function \cite{finn2016connection}. Nevertheless, recent works have tackled the problem of training large-scale EBMs on high-dimensional data, such as DEEN~\cite{saremi2018deep} which is applied in our implementation. Except for DEEN, there still leaves plenty of choices for efficiently training EBMs \cite{gutmann2012noise,Du2019generalization,nijkamp2019learn}. \section{Experiments} \subsection{Synthetic Task} \label{sec:one-domain} \begin{wrapfigure}{r}{0.4\textwidth} \vspace{-7pt} \includegraphics[width=1\linewidth]{figs/KL-crop.pdf} \vspace{-2pt} \caption{The KL divergence between the agent trajectories and the expert during the learning procedure, which indicates that EBIL is much more stable than the other methods. The blue dash line represents the converged result of EBIL.} \vspace{-14pt} \label{fig:kl-div} \end{wrapfigure} In the synthetic task, we want to evaluate the qualitative performance of different IL methods by displaying the heat map of the learned reward and sampled trajectories. As analyzed in Section~\ref{sec:ebil} and \ref{sec:discussion}, EBIL is capable of guiding the agent to recover the expert policy and correspondingly generate the high-quality trajectories. To demonstrate this point, we evaluate EBIL along with its counterparts (GAIL~\cite{ho2016generative}, AIRL~\cite{fu2017learning} and RED~\cite{wang2019red}) on a synthetic environment where the agent tries to move in a one-dimensional space. Specifically, the state space is $[ -0.5, 10.5 ]$ and the action space is $[-1, 1]$. The environment initializes the state at $0$, and we set the expert policy as static rule policies $\pi_E = {\mathcal{N}}(0.25, 0.06)$ when the state $s\in [ -0.5, 5 )$, and $\pi_E = {\mathcal{N}}(0.75, 0.06)$ when $s\in [ 5, 10.5 ]$. The sampled expert demonstration contains $40$ trajectories with up to $30$ timesteps in each one. For all methods, we choose SAC \cite{haarnoja2018soft} as the learning algorithm. We plot the KL divergence between the agent's and the expert's trajectories during the training procedure in \fig{fig:kl-div} and visualize the final estimated rewards with corresponding induced trajectories in \fig{fig:heat_maps}. As illustrated in \fig{fig:ebil_heat} and \fig{fig:kl-div}, the reward estimated by EBIL successfully captures the likelihood of the expert trajectories, and the induced policy quickly converge to the expert policy. By contrast, GAIL requires a noisy adversarial process to correct the policy. As a result, although GAIL achieves compatible final performance against EBIL~(\fig{fig:gail_heat}), it suffers a slow, unstable training as shown in \fig{fig:kl-div} and assigns arbitrary reward for some regions of the state-action space. In addition, as suggested in \fig{fig:airl_heat} and \fig{fig:red_heat} respectively, under this simple one-dimensional domain, AIRL does not in fact recover the energy as meaningful rewards, and RED suffers from the diverged reward and fail to imitate the expert. \begin{figure*}[!t] \centering \subfigure[Expert Trajectories]{ \begin{minipage}[b]{0.28\linewidth} \label{fig:expert_heat} \includegraphics[width=1\linewidth]{figs/heat-crop/expert-crop.pdf} \vspace{-0.8pt} \end{minipage} } \hspace{-10pt} \subfigure[EBIL]{ \begin{minipage}[b]{0.155\linewidth} \label{fig:ebil_heat} \includegraphics[width=1\linewidth]{figs/heat-crop/ebil_reward_heat_40-crop.pdf} \includegraphics[width=1\linewidth]{figs/heat-crop/ebil_agent_heat_40_667-crop.pdf} \end{minipage} } \subfigure[GAIL]{ \begin{minipage}[b]{0.155\linewidth} \label{fig:gail_heat} \includegraphics[width=1\linewidth]{figs/heat-crop/gail_heat_40_19890-crop.pdf} \includegraphics[width=1\linewidth]{figs/heat-crop/gail_agent_heat_40_15000-crop.pdf} \end{minipage} } \subfigure[AIRL]{ \begin{minipage}[b]{0.155\linewidth} \label{fig:airl_heat} \includegraphics[width=1\linewidth]{figs/heat-crop/airl_heat_40_16000_1-crop.pdf} \includegraphics[width=1\linewidth]{figs/heat-crop/airl_agent_heat_40_16000-crop.pdf} \end{minipage} } \subfigure[RED]{ \begin{minipage}[b]{0.155\linewidth} \label{fig:red_heat} \includegraphics[width=1\linewidth]{figs/heat-crop/rnd_heat_40_499-crop.pdf} \includegraphics[width=1\linewidth]{figs/heat-crop/rnd_agent_heat_40_19999-crop.pdf} \end{minipage} } \vspace{-7pt} \caption{Heat maps of the expert trajectories (leftmost), the (final) \textit{estimated rewards} recovered by different methods (top) and the corresponding \textit{induced policy} (bottom). The horizontal and the vertical axis denote the \textit{state space} and the \textit{action space} respectively. The red dotted line represents the position where the agent should change its policy. It is worth noting that EBIL and RED both learn fixed reward functions, while GAIL and AIRL iteratively update the reward signals. We do not compare BC since it learns the policy via supervised learning without recovering any reward signals.} \vspace{-20pt} \label{fig:heat_maps} \end{figure*} \subsection{Mujoco Tasks} We further test our method on five continuous control benchmarking Mujoco environments: Humanoid, Hopper, Walker2d and Swimmer and InvertedDoublePendulum. In this experiments, we still compare EBIL against GAIL, AIRL, GMMIL and RED, where we employ Trust Region Policy Optimization (TRPO)~\cite{schulman2015trust} as the learning algorithm in the implementation for all evaluated methods. Expert agents are trained with OpenAI baselines version~\cite{dhariwal2016openai} of Proximal Policy Optimization (PPO)~\cite{schulman2017proximal}. Furthermore, we consider to sample 4 trajectories by the trained expert policy, as \cite{ho2016generative,wang2019red} do. The training curves along with more experiments are in \ap{ap:exp}, showing the training stability of the algorithm. As shown in \tb{tab:mujoco}, EBIL achieves the best or comparable performance among all environments, indicating that the energy is able to become an excellent fixed reward function and is efficient to guide the agent to do imitation learning. It is worth noting that we do not apply BC initialization for all tasks. We surprisingly find that we are unsuccessful with AIRL on several environments even after extensive tuning, similar to the results in \cite{liu2019state}. \begin{table*}[t] \vskip 0.15in \caption{Comparison for different methods of the episodic true rewards on 5 continuous control benchmarks. The means and the standard deviations are evaluated over 50 runs.} \vspace{-5pt} \begin{center} \begin{scriptsize} \begin{tabular}{cccccc} \toprule & Humanoid & Hopper & Walker2d & Swimmer & InvertedDoublePendulum\\ \midrule Random & 100.38 $\pm$ 28.25 & 14.21 $\pm$ 11.20 & 0.18 $\pm$ 4.35 & 0.89 $\pm$ 10.96 & 49.57 $\pm$ 16.88 \\ \hline BC & 178.74 $\pm$ 55.88 & 28.04 $\pm$ 2.73 & 312.04 $\pm$ 83.83 & 5.93 $\pm$ 16.77 & 138.81 $\pm$ 39.99\\ GAIL & 145.84 $\pm$ 7.01 & 459.33 $\pm$ 216.79 & 278.93 $\pm$ 36.82 & 23.79 $\pm$ 21.84 & 122.71 $\pm$ 71.36 \\ AIRL & 286.63 $\pm$ 6.05 & 126.92 $\pm$ 62.39 & 215.79 $\pm$ 23.04 & -13.44 $\pm$ 2.69 & 76.78 $\pm$ 19.63 \\ GMMIL & 416.83 $\pm$ 59.46 & 1000.87 $\pm$ 0.87 & 1585.91 $\pm$ 575.72 & -0.73 $\pm$ 3.28 & 4244.63 $\pm$ 3228.14\\ RED & 140.23 $\pm$ 19.10 & 641.08 $\pm$ 2.24 & 641.13 $\pm$ 2.75 & -3.55 $\pm$ 5.05 & 6400.19 $\pm$ 4302.03 \\ \textbf{EBIL (Ours)} & \textbf{472.22 $\pm$ 107.72} & \textbf{1040.99 $\pm$ 0.53} & \textbf{2334.55 $\pm$ 633.91} & \textbf{58.09 $\pm$ 2.03} & \textbf{8988.37$\pm$ 1812.76}\\ \hline Expert (PPO) & 1515.36 $\pm$ 683.59 & 1407.36 $\pm$ 176.91 & 2637.27 $\pm$ 1757.72 & 122.09 $\pm$ 2.60 & 6129.10 $\pm$ 3491.47 \\ \bottomrule \end{tabular} \label{tab:mujoco} \end{scriptsize} \end{center} \vspace{-15pt} \end{table*} \section{Conclusion} In this paper, we propose Energy-Based Imitation Learning (EBIL), which shows that it is feasible to compute a fixed reward function via directly estimating the expert's energy to help agents learn from the demonstrations. We further theoretically discuss the connections of our method with Maximum Entropy Inverse Reinforcement Learning (MaxEnt IRL) and reveal that EBIL is a dual problem of MaxEnt IRL which provides a simplified and efficient solution. We empirically show the comparable or better performance of EBIL against SoTA Imitation Learning (IL) algorithms in multiple tasks. Future work can focus on different energy estimation methods for expert demonstrations and exploring more properties of EBM in IL. \clearpage \section{Broader Impact} For potential positive impacts, EBIL simplifies the learning procedure and increases the efficiency of IL, which can be applied into practical decision-making problems where agents are required to imitate demonstrated behaviors such as robotics and autonomous driving in the future work. However, negative consequences also exist since advances in automation led by IL may bring about workers who are engaged in repetitive tasks being displaced by robots. After all, teaching machines with amounts of expert demonstrations must be much cheaper than hiring hundreds of teachers and skillful employees. \section{Algorithm} \label{ap:algo} \begin{algorithm}[!h] \caption{Energy-Based Imitation Learning} \label{alg:EBIL} \begin{algorithmic}[1] \STATE {\bfseries Input:} Expert demonstration data $\tau_E=\{ (s_i, a_i) \}_{i=1}^{N}$, parameterized energy-based model $E_{\phi}$, parameterized policy $\pi_{\theta}$; \FOR{$k = 0, 1, 2, \dotsc$} \STATE Optimize $\phi$ with the objective in \eq{eq:deen}. \ENDFOR Compute the surrogate reward function $\hat{r}$ via \eq{eq:reward}. \FOR{$k = 0, 1, 2, \dotsc$} \STATE Update $\theta$ with a normal RL procedure using the surrogate reward function $\hat{r}$. \ENDFOR \RETURN {$\pi$} \end{algorithmic} \end{algorithm} \section{Proofs} \subsection{Proof of \protect\prop{prop:eb-il}} \label{ap:eb-il} Before showing the equivalence between the reverse KL divergence objective and the EBIL objective, we first present the following lemma. \begin{lemma}[Lemma 3 of \cite{ho2016generative}] $\overline{H}$ is strictly concave, and for all $\pi \in \Pi$ and $\rho \in \caD$, we have $H(\pi) = \overline{H}(\rho_\pi)$ and $\overline{H}(\rho)=H(\pi_\rho)$~, where $\overline{H}\left (\rho \right )=-\sum_{s,a}\rho_\pi\log{\rho_\pi(s,a)/\sum_{a'}\rho_\pi(s,a')}$ is the entropy of the occupancy measure. \end{lemma} \begin{proof}[Proof of \protect\prop{prop:eb-il}] Take \eq{eq:ebm} into \eq{eq:kl-il} for both policy ${\pi_E}$, one can obtain that: \begin{equation}\label{eq:kl-induce} \begin{aligned} \kld ( \rho_\pi \| \rho_{{\pi_E}}) &= \sum_{s,a} \rho_\pi(s,a) \log \frac{\rho_\pi(s,a)}{\rho_{\pi_E}(s,a)}\\ &= \sum_{s,a}\rho_\pi\left( \log{\rho_\pi(s,a)} - \log{\frac{e^{-E_{\pi_E}(s,a)}}{(1-\gamma)Z'}} \right )\\ &= \sum_{s,a}\rho_\pi\left(E_{\pi_E}(s,a)+\log{\rho_\pi(s,a)} + \log{(1-\gamma)Z'}\right )\\ &= \bbE_\pi \left[E_{\pi_E}(s,a)\right ]+\sum_{s,a}\rho_\pi\log{\rho_\pi(s,a)} + \text{const}\\ &= \bbE_\pi \left[E_{\pi_E}(s,a)\right ]+\sum_{s,a}\rho_\pi\log{\rho_\pi(s,a)} -\log{\sum_{s,a'}\rho_\pi(s,a')} + \log{\sum_{s,a'}\rho_\pi(s,a')} + \text{const}\\ &= \bbE_\pi \left[E_{\pi_E}(s,a)\right ]+\sum_{s,a}\rho_\pi\log{\left [ \rho_\pi(s,a)/\sum_{a'}\rho_\pi(s,a')\right ]}+ \text{const}\\ &= \bbE_\pi \left[E_{\pi_E}(s,a)\right ] - \overline{H}\left (\rho_\pi \right ) + \text{const} \\ &= \bbE_\pi \left[E_{\pi_E}(s,a)\right ] - H(\pi) + \text{const} ~, \end{aligned} \end{equation} where $E_{\pi_E}$ is the EBM of policy ${\pi_E}$ and $Z'$ is its partition function. Therefore \eq{eq:kl-il} in the end leads to the objective function of EBIL \eq{eq:eb-il}: \begin{equation}\label{eq:kl-eq-ebil} \begin{aligned} \argmin_{\pi} \kld ( \rho_\pi \| \rho_{{\pi_E}}) = \argmax_{\pi} \bbE_\pi \left[-E_{\pi_E}(s,a)\right ] + H(\pi) \end{aligned} \end{equation} \end{proof} \subsection{Proof of \protect\prop{prop:ebil-dual}} \label{ap:ebil-dual} \begin{proof}[Proof of \protect\prop{prop:ebil-dual}] Similarly as in \cite{ho2016generative}, we would like to relax \eq{eq:irl-dual} into the following form with the motivation from \eq{eq:rl-irl}: \begin{equation} \min_{\pi} d_\psi(\rho_\pi,\rho_{\pi_E})- H(\pi)~, \end{equation} where we modify the IRL regularizer $\psi$ so that $d_\psi(\rho_\pi,\rho_{\pi_E}) \triangleq \psi^*(\rho_\pi - \rho_{\pi_E})$ is a smooth distance metric that penalizes violations in the difference between the occupancy measures. By choosing $\psi= \bbE_{\pi_E} [-1-\log(r(s, a))+r(s, a)]$, we obtain $d_\psi(\rho_\pi,\rho_{\pi_E})=D_{\text{KL}}(\rho_\pi\|\rho_{\pi_E})$\footnote{Full derivations can be found in Appendix D of \protect\cite{ghasemipour2019divergence} and we replace $c(s,a)$ with $-r(s,a)$.}. Thus we have: \begin{equation}\label{eq:kl-h} \min_{\pi} D_{\text{KL}}(\rho_\pi\|\rho_{\pi_E})- H(\pi)~. \end{equation} Refer to \eq{eq:kl-induce}, we have: \begin{equation} D_{\text{KL}}(\rho_\pi\|\rho_{\pi_E}) = \bbE_\pi\left[E_{\pi_E}(s,a)\right ] - H(\pi) + \text{const}~. \end{equation} Thus, we can rewrite \eq{eq:kl-h} as the following optimization problem: \begin{equation}\label{eq:eb-il-2} \pi^* = \argmax_{\pi} \bbE_\pi \left[-E_{\pi_E}(s,a)\right ] + 2H(\pi)~, \end{equation} which leads to the EBIL objective \eq{eq:eb-il} with the temperature hyperparameter $\alpha=2$. This indicates that EBIL is a dual problem of the MaxEnt IRL problem. \end{proof} \subsection{Proof of \protect\prop{prop:tau-kl}} \label{ap:tau-kl} \begin{proof}[Proof of \protect\prop{prop:tau-kl}] Suppose we have recovered the optimal reward function $\hat{r}$, then we can derive the objective of the KL divergence between the two trajectories into the forward MaxEnt RL procedure. With chain rule, the induced trajectory distribution $p(\tau)$ is given by \begin{equation} p(\tau) = p(s_0)\prod_{t=0}^{T}P(s_{t+1}|s_t,a_t)\pi(a_t|s_t)~. \end{equation} Suppose the desired expert trajectory distribution $p(\tau_E)$ is given by \begin{equation} \begin{aligned} p(\tau) &\propto p(s_0)\prod_{t=0}^{T}P(s_{t+1}|s_t,a_t) \exp(\hat{r}^*(\tau))\\ &= p(s_0)\prod_{t=0}^{T}P(s_{t+1}|s_t,a_t) \exp(\sum_{t=0}^{T}\hat{r}^*(s_t, a_t))~, \end{aligned} \end{equation} now we will show that the following optimization problem is equivalent to a forward MaxEnt RL procedure given the optimal reward $\hat{r}^*$: \begin{equation}\label{eq:tau-kl-induce-1} \begin{aligned} \kld(p(\tau)\|p(\tau_E))&= \sum_{\tau\sim\pi} p(\tau) \log \frac{p(\tau)}{p(\tau_E)}\\ &= \sum_{\tau\sim\pi}p(\tau)\left( \log{p(\tau)} - \log{p(\tau_E)} \right )\\ &= \bbE_{\tau\sim\pi} \left[ \log p(s_0) + \sum_{t=0}^T \left (\log P(s_{t+1}|s_t,a_t) + \hat{r}^*(s_t, a_t)\right ) - \right. \\ &~~~~~\left. \log p(s_0) - \sum_{t=0}^T \left (\log P(s_{t+1}|s_t,a_t) + \log \pi(a_t|s_t)\right ) \right] + \text{const}\\ &= \bbE_{\tau \sim p(\tau)} \left[ \sum_{t=0}^T \hat{r}^*(s_t, a_t) - \pi(a_t|s_t)) \right] + \text{const} \\ &= \sum_{t=0}^T \bbE_{(s_t, a_t) \sim \rho(s_t, a_t)} [\hat{r}^*(s_t,a_t) - \log \pi(a_t|s_t)] + \text{const}~. \end{aligned} \end{equation} Without loss of generality, we approximate the finite term $\sum_{t=0}^T \bbE_{(s_t, a_t)}$ with an infinite term $\bbE_{\pi}$ by the definition, and then we have \begin{equation}\label{eq:tau-kl-induce-2} \begin{aligned} \kld(p(\tau)\|p(\tau_E)) &\approx \bbE_{(s, a) \sim \rho(s, a)} [\hat{r}^*(s,a) - \log \pi(a_t|s_t)] + \text{const}\\ &= \bbE_{\pi} [\hat{r}^*(s,a) - \log \pi(a|s)] + \text{const}\\ &= \bbE_{\pi} [\hat{r}^*(s,a)] - \bbE_{\pi}[\log \pi(a|s)] + \text{const}\\ &= \bbE_{\pi} [\hat{r}^*(s,a)] - H(\pi) + \text{const}~. \end{aligned} \end{equation} Thus the objective \eq{eq:tau-kl} is equivalent to the following optimization problem: \begin{equation} \max_{\pi} \bbE_\pi\left [\hat{r}^*(s,a)\right ]+ H(\pi)~, \end{equation} which is exactly the objective of a forward MaxEnt RL procedure (\eq{eq:rl-hr}). This indicates that when MaxEnt IRL recovers the optimal reward function, a forward RL learning which leads to the optimal (expert) policy is equivalent to minimize the reverse KL divergence between the trajectories sampled by the agent and by the expert. \end{proof} \subsection{Proof of \protect\prop{prop:kl-kl}} \label{ap:kl-kl} \begin{proof}[Proof of \protect\prop{prop:kl-kl}] From the deviation \eq{eq:tau-kl-induce-2}, we know that the optimization problem \eq{eq:tau-kl} is equivalent to a forward MaxEnt RL problem \eq{eq:rl-hr}. Let $r^*(s,a)=-E(s,a)$, and we will exactly get the EBIL objective \eq{eq:eb-il}. Note that the reverse KL divergence IL objective \eq{eq:kl-il} can also be derived into the EBIL objective \eq{eq:eb-il} followed \eq{eq:kl-induce}. Thus \eq{eq:tau-kl} is equivalent to both the reverse KL divergence IL objective \eq{eq:kl-il} and the EBIL objective \eq{eq:eb-il}. \end{proof} \section{Experiments} \label{ap:exp} \subsection{Hyperparameters} We show the hyperparameters for both DEEN training and policy training on different tasks in \tb{tab:hyperparameters}. Specifically, we use MLPs as the networks for training DEEN and the policy network. \begin{table*}[htbp] \caption{Important hyperparameters used in our experiments} \label{tab:hyperparameters} \centering \resizebox{0.7\textwidth}{!}{ \begin{tabular}{llcccccc} \toprule & Hyperparameter & One-D. & Human. & Hop. & Walk. & Swim. & Invert. \\ \midrule \multirow{4}{*}{Policy} & Hidden layers & 3 & 3 & 3 & 3 & 3 & 3 \\ & Hidden Size & 200 & 200 & 200 & 200 & 200 & 200 \\ & Iterations & 6000 & 6000 & 6000 & 6000 & 6000 & 6000 \\ & Batch Size & 32 & 32 & 32 & 32 & 32 & 32 \\ \midrule \multirow{6}{*}{DEEN} & Hidden layers & 3 & 3 & 3 & 4 & 3 & 3 \\ & Hidden size & 200 & 200 & 200 & 200 & 200 & 200 \\ & Epochs & 3000 & 3000 & 6000 & 500 & 1900 & 500 \\ & Batch Size & 32 & 32 & 32 & 32 & 32 & 32 \\ & Noise Scale $\sigma$ & 0.1 & 0.1 & 0.1 & 0.1 & 0.1 & 0.1 \\ & Reward Scale $\alpha$ & 1 & 1 & 5 & 1 & 1 & 1000 \\ \bottomrule \end{tabular}} \end{table*} \subsection{Synthetic Task Training Procedure} We demonstrate more training slices of the synthetic task in this section. We analyze the learned behaviors during the training procedure of the synthetic task, as illustrated by visitation heatmaps in \fig{fig:train-heat}. For each method, we choose to show four training stages from different training iterations. These figures provide more evidence that although GAIL can finally achieve good results, EBIL provides fast and stable training. By contrast, GMMIL and RED fail to achieve effective results during the whole training time.\footnote{For better understanding how these methods learn reward signals, we also visualize the changes of estimated rewards during the training procedures. Videos can be seen at \url{https://www.dropbox.com/s/0mrsoqyu040crdo/video.zip?dl=0}.} \begin{figure*}[htb] \centering \includegraphics[width=0.90\linewidth]{figs/policy-iter.pdf} \caption{The induced policy during policy training procedures. In each figure the horizontal axis denotes the \textit{state space}, and the vertical axis represents the \textit{action space}. Methods from top to bottom are separately EBIL, GAIL, AIRL and RED and each one contains four training stages shown in one line. The color bar is the same as \fig{fig:heat_maps}. The brighter the yellow color, the higher the visitation frequency.} \vspace{-15pt} \label{fig:train-heat} \end{figure*} \subsection{Training Curves} \label{ap:curves-mujoco} We plot the episodes averaged return during the training procedure in \fig{fig:curves-mujoco}, where EBIL shows effective guidance to help agent learn good policies while owns stability on all environments in comparison to the other methods. In our experiments, we find that the training procedure of GAIL suffers from instability. \begin{figure*}[h!] \centering \includegraphics[width=1\linewidth]{./figs/curves-mujoco.pdf} \vspace{-3pt} \caption{Training curves of GAIL, GMMIL, RED and EBIL on different continuous control benchmarking tasks, where the solid curves depict the mean and the shaded areas indicate the standard deviation. Each iterations contains 1024 timesteps.} \vspace{-15pt} \label{fig:curves-mujoco} \end{figure*} \subsection{Energy Evaluation} \label{curves-energy} Since the loss function of DEEN cannot be directly used as an indicator to evaluate the quality of the learned energy network, we propose to evaluate the averaged energy value for expert trajectories and the random trajectories on different tasks. As shown in \fig{fig:curves-energy}, DEEN finally converges in all experiments by differentiating the expert data. It is worth noting that in our experiments, we find that a well-trained energy network may be hard for agents to learn the expert policies on some environments. We regard it as the ``sparse reward signals'' problem, as discussed in \se{sec:one-domain}. By contrast, sometimes a ``half-trained'' model may provide smoother rewards, and can help the agent to learn more efficiently. Similar phenomenon also occurs when training the discriminator in GAN. We will further analyze the training performance with energy models of different epochs in ablation study \se{sec:abl-study}. \begin{figure*}[h!] \centering \includegraphics[width=1\linewidth]{./figs/curves-energy.pdf} \vspace{-33pt} \caption{Energy evaluation curves on different mujoco tasks, where the red line represents for the average energy estimation on expert data and the blue is for random trajectories, which contain 100 trajectories separately. Note that lower energy values correspond to higher rewards. The min value is -1, and the max is 1 since we use \textit{tanh} for the last layer of the DEEN network.} \vspace{-15pt} \label{fig:curves-energy} \end{figure*} \subsection{Ablation Study} \label{sec:abl-study} To further understand what the better energy model for learning a good policy is, we conduct ablation study on energy models trained from different epochs. The results are illustrated in \fig{fig:ablation-energy}, which verify our intuition that a ``half-trained'' model can provide smoother rewards that solve the "sparse reward`` problem, which is better for imitating the expert policy. \begin{figure*}[h!] \centering \includegraphics[width=0.45\linewidth]{./figs/ablation-energy-hopper} \includegraphics[width=0.45\linewidth]{./figs/ablation-energy-walker} \vspace{-4pt} \caption{The average episode rewards evaluated on Hopper-v2 and Walker2d-v2 by agents that are learned with energy models from different training epochs.} \vspace{-15pt} \label{fig:ablation-energy} \end{figure*} \section{Further Discussions} \subsection{Surrogate Reward Functions} As discussed in \cite{kostrikov2018discriminator}, the reward function is highly related to the property of the task. Positive rewards may achieve better performance in the ``surviving'' style environment, and negative ones may take advantage in the ``per-step-penalty'' style environment. The different choices are common in those imitation learning works based on GAIL, which can use either $\log(D)$ or $-\log(1-D)$, where $D\in [0,1]$ is the output of the discriminator, determined by the final ``\textit{sigmoid}'' layer. In our work, we choose ``\textit{tanh}'' as the final layer of the energy network, which in result leads the energy into a range of $[-1,1]$. In order to adapt to different environments while holding the good property of the energy, we can apply a monotonically increasing linear function $h$ as the surrogate reward function, which makes translation or scaling transformation on the energy outputs. It appears that in all of our tasks, the original energy signal does not show much ascendancy, and thus we choose different $h$ for these tasks. In the one-dimension domain experiment, we choose to use the following surrogate reward function: \begin{equation} \hat{r}(s,a)=h(x)=x+1~, \end{equation} where $\hat{r} \in [0, 2]$ and $x=-E(s,a)$ is the energy function. Thus, the experts' state-action pair will get close-to-zero rewards at each step. In mujoco tasks, we choose the surrogate reward function as: \begin{equation} \hat{r}(s,a)=h(x)=(x+1)/2~, \end{equation} where $x=-E(s,a)$ is the energy function. Note that we construct this reward function to make a normalized reward $\hat{r} \in [0, 1]$ so that the non-expert's state-action pairs will gain near-zero rewards while the experts' get close-to-one rewards at each step regarding the output range of the energy is $[-1,1]$. In our experiments, similar rewards as the one-dimensional synthetic environment can also work well. \subsection{AIRL Does Not Recover the Energy} \label{ap:airl} Adversarial Inverse Reinforcement Learning (AIRL)\cite{fu2017learning}, is a SoTA IRL method that apply an adversarial architecture similar as GAIL to solve the IRL problem. Formally, AIRL constructs the discriminator as \begin{equation}\label{eq:airl-dis} D(s,a) = \frac{\exp(f(s,a))}{\exp(f(s,a)) + \pi(a|s)}~. \end{equation} This is motivated by the former GCL-GAN work~\cite{finn2016connection}, which proposes that one can apply GAN to train GCL that formulate the discriminator as \begin{equation}\label{eq:airl-dis} D(\tau) = \frac{\frac{1}{Z}\exp(c(\tau))}{\frac{1}{Z}\exp(c(\tau)) + \pi(\tau)}~, \end{equation} where $\tau$ denotes the trajectory. AIRL uses a surrogate reward \begin{equation}\label{eq:airl-reward} \begin{aligned} r(s,a) &= \log D(s,a) - \log(1-D(s,a))\\ &= f(s,a)-\log{\pi(a|s)}~, \end{aligned} \end{equation} which can be seen as an entropy-regularized reward function. However, the difference between \eq{eq:airl-dis} and \eq{eq:airl-reward} indicates that AIRL does not actually recover the expert's energy since they omit the partition function $Z$ which is important for estimating the energy. Also, the learning signal that drives the agent to learn a good policy is not a pure reward term but contains an entropy term itself. We visualize the different reward choice ($f(s,a)$ or $f(s,a)-\log{\pi(a|s)}$) in \fig{fig:airlreward} as comparison, which verify our intuition that AIRL in fact does not recover the expert's energy as EBIL does. \begin{figure*}[!t] \centering \subfigure[Reward as $f(s,a)-\log{\pi(a|s)}$]{ \begin{minipage}[b]{0.33\linewidth} \label{fig:logreward} \includegraphics[width=1\linewidth]{figs/heat-crop/airl_heat_40_16000_1-crop.pdf} \end{minipage} } \subfigure[Reward as $f(s,a)$]{ \begin{minipage}[b]{0.393\linewidth} \label{fig:freward} \includegraphics[width=1\linewidth]{figs/heat-crop/airl_heat_40_16000_0_bar-crop.pdf} \end{minipage} } \vspace{-7pt} \caption{Heat maps of the different estimated rewards recovered by AIRL.} \label{fig:airlreward} \end{figure*} \subsection{Discussions with MaxEnt RL Methods} \label{ap:ebil-sac} Soft-Q Learning (SQL)~\cite{haarnoja2017reinforcement} and Soft Actor-Critic (SAC)~\cite{haarnoja2018soft} are two main approaches of MaxEnt RL, particularly, they propose to use a general energy-based form policy as: \begin{equation}\label{eq:softq} \pi(a_t|s_t) \propto \exp{(-E(s_t, a_t))}~. \end{equation} To connect the policy with soft versions of value functions and Q functions, they set the energy model $E(s_t,a_t) = -\frac{1}{\alpha}Q_{\text{soft}}(s_t,a_t)$ where $\alpha$ is the temperature parameter, such that the policy can be represented with the Q function which holds the highest probability at the action with the highest Q value, which essentially provides a soft version of the greedy policy. Thus, one can choose to optimize the soft Q function to obtain the optimal policy by minimizing the expected KL-divergence: \begin{equation}\label{eq:softac} J(\pi) = \bbE_{s\sim \rho^s_{\caD}}\left[\kld\left( \pi(\cdot|s) \big \| \frac{\exp{(Q(s,\cdot))}}{Z(s)} \right) \right ]~, \end{equation} where $\rho^s_{\caD}$ is the distribution of previously sampled states and actions, or a replay buffer. Therefore, the second term in the KL-divergence in fact can be regarded as the target or the reference for the policy. Consider to use the KL-divergence as the distance metric in the general objective of IL shown in \eq{eq:il}, then we get: \begin{equation} \begin{aligned} \pi^* &= \argmin_\pi \mathbb{E}_{\pi} \left [\kld \left( \pi(\cdot|s) \big \| {\pi_E}(\cdot|s) \right) \right ]~. \end{aligned} \end{equation} If we choose to model the expert policy using the energy form of \eq{eq:softq} then we get: \begin{equation} \begin{aligned}\label{eq:softil} \pi^* &= \argmin_\pi \mathbb{E}_{\pi}\left [\kld \left( \pi(\cdot|s) \big \| \frac{\exp{(-E_{\pi_E}(s,a)})}{Z} \right) \right ]~. \end{aligned} \end{equation} \begin{proposition} \label{prop:ebil-sac} The IL objective shown in \eq{eq:softil} is equivalent to the EBIL objective shown in \eq{eq:eb-il}. \end{proposition} \begin{proof} Since \eq{eq:eb-il} is equivalent to \eq{eq:kl-il}, it holds the optimal solution such that $\pi^*={\pi_E}$ according to \prop{prop:kl-il}. Also, it is easy to see that \eq{eq:softil} has the same optimal solution such that $\pi^*={\pi_E}$. \end{proof} Thus, \prop{prop:ebil-sac} reveals the relation between MaxEnt RL and EBIL. Specifically, EBIL employs the energy model learned from expert demonstrations as the target policy. The difference is that MaxEnt RL methods use the Q function to play the role of the energy function, construct it as the target policy, and iteratively update the Q function and the policy, while EBIL directly utilizes the energy function to model the expert occupancy measure and constructs the target policy. As a result, it makes sense to directly optimize the policy by taking the energy model as the target policy instead of the reward function, which leads to the optimal solution as: \begin{equation} \begin{aligned} \pi^*(a|s)&= \frac{\rho_{{\pi_E}}(s,a)}{\sum_{a'}\rho_{{\pi_E}}(s,a')}\\ &=\frac{\frac{1}{Z}\exp(-E_{{\pi_E}}(s,a))}{\frac{1}{Z}\sum_{a'}\exp{(-E_{{\pi_E}}(s,a'))}}\\ &=\frac{\exp(-E(s,a))}{\sum_{a'}\exp{(-E(s,a'))}}~. \end{aligned} \end{equation} Therefore, the optimal solution can also be obtained through estimating the energy function and summing it over the action space, which may be intractable for high-dimensional or continuous action space. Nevertheless, this can be solved in simple scenarios.
{'timestamp': '2020-06-03T02:20:33', 'yymm': '2004', 'arxiv_id': '2004.09395', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09395'}
arxiv
\section{Introduction} Deep neural networks (DNNs) are built of layers that primarily perform dot product operations between activations and weights. These basic operations are at the core of DNNs that achieve state-of-the-art results in different domains \cite{hannun2014deep, girshick2014rich, silver2016mastering}. Yet, DNNs comprise abundant computations; for example, state-of-the-art convolutional neural networks (CNNs) may require billions of multiply-and-accumulate (MAC) operations to classify a single image \cite{hannun2014deep, sze2017efficient}. Their great potential and computational burden have been a fertile ground for research and development of efficient DNN hardware accelerators over the last decade \cite{reuther2019survey, jouppi2017datacenter, chen2014dadiannao}. The control flow of DNNs is mostly predictable, yet computations are still executed inefficiently on underlying hardware. For example, DNNs may consist of many zero-valued activations and weights \cite{albericio2016cnvlutin}. During inference, a layer output is usually followed by a ReLU activation function, which clamps negative activation values to zero \cite{nair2010rectified}. In addition, static pruning techniques push the limits of model sparsity by zeroing out insignificant weights \cite{han2015learning, li2016pruning}. Zeros can be also found in finer granularities \cite{lascorz2019shapeshifter}; a quantized 8-bit DNN has many values that can be effectively represented only by the 4-bit least-significant bits (LSBs). This unstructured sparsity can be leveraged to increase efficiency, thereby improving performance and reducing energy. Until now, DNN accelerators have handled such inefficiencies with compressed encodings \cite{gondimalla2019sparten, parashar2017scnn, han2016eie}, output zero-value prediction \cite{akhlaghi2018snapea, song2018prediction, shomron2019thanks}, input zero-value skipping \cite{sharify2019laconic, kim2017zena, zhang2016cambricon, albericio2016cnvlutin}, and working with bit-serial schemes \cite{sharify2019laconic, judd2016stripes}. In this paper, we introduce \emph{non-blocking simultaneous multithreading} (NB-SMT{}), a new approach to tackle sparsity and increase hardware efficiency. Conceptually, NB-SMT{} is based on the well-known SMT used to concurrently execute multiple instruction flows on shared resources \cite{yamamoto1994performance, yamamoto1995increasing, tullsen1995simultaneous, eggers1997simultaneous}. In the same manner that SMT keeps several hardware threads to increase utilization of hardware resources, we propose maintaining a number of ``DNN threads'' that run in parallel so as to increase utilization of DNN hardware resources. Conventional SMT dispatches instructions to an execution unit in an opportunistic manner. That is, if instruction dependencies are met and its needed resources are available, it will be executed; otherwise, the instruction will wait in a reservation station. NB-SMT{} avoids this online scheduling by ``squeezing'' two (or more) threads together to the shared resource (e.g., execution unit) by temporarily reducing their numerical precision. By doing so, we (1) leverage DNN tolerance to reduced numerical precision, thereby enabling a non-blocking operation; (2) do not break the systematic operation of DNNs, thereby enabling implementation of SMT in dataflow architectures, which are popular as DNN accelerators; and (3) achieve a speedup that is directly proportional to the number of threads. NB-SMT{} may be implemented in different DNN accelerator architectures. In this paper, we demonstrate 2-threaded and 4-threaded NB-SMT{} as an extension to an 8-bit output-stationary (OS) systolic array (SA) for matrix multiplication \cite{kung1979systolic, shomron2019smt, gupta2015deep}, which we named SySMT{}. Compared with the conventional OS-SA, a 2-threaded SySMT{} achieves a 2$\times$ speedup with 33\% energy reduction and less than 1\% accuracy degradation of state-of-the-art DNNs with a 1.4$\times$ area increase. As for 4-threads, we observe that some layers contribute more errors to inference than others when executed with NB-SMT{}. Therefore, we trade speedup for accuracy by decreasing the number of running threads in selective layers. Given a 1\% accuracy degradation cap, a 4-threaded SySMT{} delivers, for example, 3.4$\times$ speedup with 37\% energy reduction and 2.5$\times$ area increase with 40\%-pruned ResNet-18, compared with the conventional OS-SA. Our contributions in this paper are as follows: \begin{itemize} \item We introduce the concept of non-blocking simultaneous multithreading (NB-SMT{}), which increases DNN hardware utilization by exploiting DNN tolerance to reduced numerical precision, data-width variability, and unstructured sparsity. By not blocking any thread, NB-SMT{} achieves a speedup that is directly proportional to the number of threads. \item We demonstrate NB-SMT{} applicability using SySMT{}, which is an NB-SMT{}-enabled output-stationary systolic array. We describe different resource sharing strategies in which SySMT{} employs both MAC unit and output register sharing. \item We evaluate a 2-threaded and a 4-threaded SySMT{} in terms of speedup, area, power, energy, and model accuracy with various state-of-the-art CNN models and the ImageNet dataset. \end{itemize} The rest of this paper is organized as follows: Section~\ref{sec:motivation} describes the rationale behind NB-SMT{}, Section~\ref{sec:the_idea} presents the basic principals of NB-SMT{}, Section~\ref{sec:sa} demonstrates NB-SMT{} as an extension to an output-stationary systolic array (SySMT{}), Section~\ref{sec:eval} evaluates the impact of NB-SMT{} on SySMT{} implementation as well as on model accuracy, Section~\ref{sec:related_work} discusses the applicability of NB-SMT{} in other accelerators and reviews related work, and Section~\ref{sec:conclusions} concludes. \section{Motivation} \label{sec:motivation} The CPU instruction pipeline faces many challenges in achieving efficient execution. These inefficiencies, also known as hazards, originate from the application's dynamic execution flow and from the generality of the architecture (i.e., general-purpose). DNNs, on the other hand, work in a systematic, layer-by-layer fashion, with mostly MAC operations taking place during inference, making their control and data flow deterministic; which and how many computations will be conducted, what is the model's memory footprint, where are weights stored, and where will activations be stored during execution, can all be deduced prior to execution (neglecting special cases of conditional DNNs, for example). Yet, DNNs still exhibit inefficiencies when considering the actual values that propagate through the layers. \textbf{Sparsity.} DNNs comprise zero-valued activations and weights \cite{nikolic2019characterizing}. Zero-valued activations are produced dynamically during inference, due, among other things, to the popular use of the ReLU activation function, which clamps negative values to zero \cite{nair2010rectified}. On the other hand, weights are static during inference, and in most cases, not many of them are zero-valued when trained only with a loss function. However, training the network with L1 regularization or pruning the network, for example, can substantially reduce the number of parameters (i.e., increase the number of zero-valued weights) with negligible decrease in model accuracy \cite{li2016pruning}. For example, 60\% of ResNet-50 parameters can be discarded \cite{liu2018rethinking} by iteratively trimming small weights and retraining the model in an unstructured manner \cite{han2015learning}. \textbf{Partial sparsity.} Zeros can be also observed when looking within the numerical representation. DNN tensors usually follow a bell-shaped distribution, such as Gaussian or Laplace \cite{banner2019post}. Therefore, when considering a quantized DNN, some values will only be represented by a portion of the LSBs, leaving the most-significant bits (MSBs) to be equal to zero \cite{lascorz2019shapeshifter}. Throughout this paper we use 8-bit model representations, so by ``partial sparsity'' we refer to those numbers that can be represented solely by 4 bits. \textbf{Unstructured sparsity.} Activation sparsity is unstructured by nature, as the zero-valued activations may be scattered without any confined structure. Moreover, the values themselves are input-dependent, and thereby dynamic. Weights, on the other hand, are static during inference and therefore can be pruned either in an unstructured or structured manner. A general rule of thumb is that unstructured pruning techniques achieve a better parameter reduction to accuracy reduction ratio than do structured techniques. Indeed, with unstructured pruning, the algorithm has the freedom to cancel parameters in weight granularity, whereas structured pruning algorithms are constrained to remove parameters in larger granularity, such as channels or filters \cite{wen2016learning}. The downside of unstructured pruning is, however, that it is not easily exploited by hardware \cite{liu2018rethinking}. The unstructured sparse inputs cause spontaneous underutilization of the MAC units. From an hardware perspective, a MAC unit with one of its inputs equals to zero is practically idle; and an 8b-8b MAC unit with an effective input data-width of 4 bits is only partially utilized. Figure~\ref{fig:mac_util} presents the average MAC utilization of five popular CNN models. We observe that, on average, 60\% of MAC operations result in idle MAC units, since one of their inputs is zero-valued; 20\% of MAC operations partially utilize the MAC units, since one of their inputs, or both, are effectively represented with 4 bits; and in a mere 10\% of the time, the MAC operations fully utilize the MAC units. To increase hardware utilization, we propose non-blocking simultaneous multithreading (NB-SMT{}) that exploits both the unstructured sparsities of the activations and weights, as well as DNN tolerance to numerical precision reduction. \begin{figure}[t] \centering \begin{tikzpicture} \begin{axis}[ ybar stacked, bar width=15pt, width=8.5cm, height=5cm, enlarge x limits=0.1, enlarge y limits=0, xlabel near ticks, ylabel near ticks, legend style={at={(0.5,-0.20)}, anchor=north,legend columns=-1}, ylabel={\%}, ymin={0}, ymax={100}, symbolic x coords={AlexNet, ResNet18, ResNet50, GoogLeNet, DenseNet121}, xtick=data, x tick label style = {font=\footnotesize, rotate=20}, y tick label style = {font=\footnotesize}, legend style={font=\scriptsize, legend columns=4, legend cell align=left, at={(0.5, 1.01)}, anchor=south, draw=none}, tick style={draw=none}, xmajorgrids, ymajorgrids, major grid style={dashed}, set layers=Bowpark ] \addplot[fill=black!60] plot coordinates {(AlexNet,13.4) (ResNet18,18.1) (ResNet50,18.3) (GoogLeNet,21.0) (DenseNet121,17.7)}; \addplot[fill=black!40] plot coordinates {(AlexNet,27.5) (ResNet18,21.1) (ResNet50,23.4) (GoogLeNet,22.6) (DenseNet121,25.0)}; \addplot[fill=black!20] plot coordinates {(AlexNet,59.1) (ResNet18,60.8) (ResNet50,58.3) (GoogLeNet,56.4) (DenseNet121,57.3)}; \legend{Utilized (8b-8b), Partially Utilized (4b-8b/8b-4b/4b-4b), Idle} \end{axis} \end{tikzpicture} \caption{Utilization of 8-bit MAC units during CNN inference, as simulated given the entire ILSVRC-2012 dataset \cite{russakovsky2015imagenet}. On average, only 20\% of the MAC units are fully utilized.} \label{fig:mac_util} \end{figure} \textbf{Algorithmic resiliency.} DNNs are fault-tolerant \cite{reagen2018ares, li2017understanding}; they can absorb connection removals \cite{han2015learning, shomron2019thanks} and numerical precision reduction \cite{kravchik2019low, shkolnik2020robust} with only a ``graceful degradation'' in performance \cite{kerlirzin1993robustness}. For example, DNNs can be quantized from FP32 to INT8 in a straight-forward post-training min-max uniform quantization with no significant loss in accuracy \cite{krishnamoorthi2018quantizing}. DNN tolerance can be harnessed in order to ease design constraints. Specifically, NB-SMT{} builds upon DNN resiliency to handle structural hazards without stalling any thread, as opposed to conventional SMT. Avoiding stalls coalesces with the way DNNs operate during inference. \textbf{Systematic operation.} Inference with DNNs is a compute-intensive task that requires minor control. For example, ResNet-50 \cite{he2016deep} requires 4 billion MAC operations to classify a single 224$\times$224 colored image from the ImageNet dataset \cite{russakovsky2015imagenet}. During these 4 billion computations, there is not a single control branch --- the entire control flow is predictable. These application characteristics have driven computer architects to design highly parallel DNN architectures with almost no control logic \cite{jouppi2017datacenter, chen2014dadiannao}. The lack of control capabilities, which is a consequence of the systematic operation of DNNs, stands in contrast to the conventional SMT way of operation, which may stall threads as a function of the current state of microarchitecture. By completely avoiding stalls, we enable an SMT implementation in DNN hardware architectures. \section{NB-SMT{}: The Basic Idea} \label{sec:the_idea} Conventional SMT is based on the observation that a single thread might not fully utilize the execution resources. SMT tries to increase utilization by exploiting thread-level parallelism, that is, dispatching instructions from different threads to the same resources. Inspired by SMT, we propose NB-SMT{}, a special ``SMT'' designated for the environment of DNNs. NB-SMT{} is conceptually similar to traditional SMT, in the sense that the context of more than one thread is kept on hardware in parallel. In all other aspects, however, NB-SMT{} differs from traditional SMT: first, it compensates for underutilization caused by particular data \emph{values}; and second, it is non-blocking. Instead of keeping operations waiting in reservation stations on structural hazards, it ``squeezes'' operations to the same hardware by momentarily reducing their precision, considering DNN tolerance to reduction in numerical precision. \subsection{Hiding Inefficiencies} MAC unit operation is value-dependent. For example, let $(X,W)$ be an input pair that consists of two vectors of length $K$ that are to be multiplied. The process of achieving the result includes $K$ MAC operations of the corresponding elements of $X$ and $W$, that is, $O = \sum_{i=0}^{K-1} x_i w_i$. Now, assume $X$ comprises 50\% zero-valued elements. In this case, 50\% of MAC operations are effectively redundant, as $0\times x = 0$ and $0 + x = x$. NB-SMT{} increases utilization with additional threads that exploit the idle MAC units. For example, a 2-threaded (2T) NB-SMT{} will include two independent input pairs $(X,W)_1$ and $(X,W)_2$, each of which will produce a result of its own, $O_1$ and $O_2$, respectively. Thus, if the first pair does not require the MAC unit, there is a chance that the second thread will, thereby utilizing it. To support NB-SMT{}, the hardware should include additional data path and registers. The hardware should also be capable of handling thread collisions, i.e., cases in which the threads' computation demands are higher than the MAC unit capabilities. \subsection{Thread Collisions} Thread collisions can be handled with queues and backpressure to support congestions \cite{shomron2019smt}. However, NB-SMT{} takes another path, exploiting DNNs' resiliency and temporarily reducing the threads' numerical precision so that execution units are still able to accommodate all thread computations in that same cycle. Thread collision incurs reduction in precision which contributes some error to the overall computation, for example, the case of a single 8b-8b MAC unit and two threads with 8b-8b and 8b-8b input pairs. On the other hand, for example, threads that are represented solely by their 4-bit LSBs can share the underlying MAC unit without affecting the original computation. We demonstrate these scenarios next. \subsection{Squeezing Them In} \begin{figure}[t] \begin{subfigure}[b]{\columnwidth} \centering \includegraphics[width=\linewidth]{./imgs/smt_example1.pdf} \caption{\textbf{Precision reduction:} Both input pairs require the multiplier. Therefore, without loss of generality, $X$ inputs are approximated by their 4-bit MSBs (rounded first) to achieve two 4b-8b multiplications.} \label{fig:smt_example:1} \end{subfigure} \par\medskip \begin{subfigure}[b]{\columnwidth} \centering \includegraphics[width=\linewidth]{./imgs/smt_example2.pdf} \caption{\textbf{8-bit sparsity}: First thread has a zero-valued operand. The second thread can, therefore, use the entire 8b-8b multiplier.} \label{fig:smt_example:2} \end{subfigure} \par\medskip \begin{subfigure}{\columnwidth} \centering \includegraphics[width=\linewidth]{./imgs/smt_example3.pdf} \caption{\textbf{Activations' 4-bit sparsity:} $X$ inputs may be effectively represented by their 4-bit LSBs. Two 4b-8b multiplications, therefore, take place with no computation error.} \label{fig:smt_example:3} \end{subfigure} \par\medskip \begin{subfigure}{\columnwidth} \centering \includegraphics[width=\linewidth]{./imgs/smt_example4.pdf} \caption{\textbf{Activation and weight 4-bit sparsity:} Considering data-width of both inputs to avoid precision reduction.} \label{fig:smt_example:4} \end{subfigure} \par\medskip \begin{subfigure}{\columnwidth} \centering \includegraphics[width=\linewidth]{./imgs/smt_example5.pdf} \caption{\textbf{Activations' 4-bit sparsity with reduced precision:} A combination of (a) and (d).} \label{fig:smt_example:5} \end{subfigure} \caption{Examples of how NB-SMT{} ``squeezes'' inputs to a single flexible multiplier unit, capable of either one 8b-8b multiplication or two independent 4b-8b multiplications.} \label{fig:smt_example} \end{figure} Consider a flexible multiplier, capable of conducting either a single 8b-8b multiplication or two 4b-8b multiplications per cycle (we further elaborate on such flexible multipliers in Section~\ref{sec:fmac}). For simplicity's sake, throughout this section we consider only two threads, that is, two input pairs, $(X,W)_1$ and $(X,W)_2$, with unsigned values. \subsubsection{Precision Reduction} \label{sec:the_idea_prec_reduce} On-the-fly precision reduction truncates values represented by more than 4 bits to 4 bits. Reducing thread precision takes place when a thread collision occurs and the thread operands are represented by more than 4 bits. Before reducing the 8-bit value (activation or weight) to 4 bits, we round the number to the nearest integer that is a whole multiple of 16 ($2^4$), to mitigate the noise it contributes to the entire inference pass. Figure~\ref{fig:smt_example:1} illustrates an example of reducing the numerical precision of the activation values (without loss in generality). $(X,W)_1$ and $(X,W)_2$ are equal to $(46_{10}, 23_{10})$ and $(178_{10}, 242_{10})$, respectively. Both $X$ inputs MSBs are rounded and truncated so as to be represented by 4-bits, yielding $(3_{10}, 23_{10})$ and $(11_{10}, 242_{10})$, respectively. Two 4b-8b multiplications then take place, followed by a 4-bit shift left, resulting in two approximated results $1104_{10}$ (instead of $1058_{10}$) and $42592_{10}$ (instead of $43076_{10}$). It is obvious, however, that it is unnecessary to reduce precision of all input values. \subsubsection{8-Bit Sparsity} If $X_1$ or $W_1$ or both are zero-valued, $(X,W)_2$ can use the entire 8b-8b multiplier, and vice versa. For example, consider the two input pairs in Fig.~\ref{fig:smt_example:2}, $(0, 23_{10})$ and $(178_{10}, 242_{10})$. It is clear that the first thread does not require the multiplier, since its first multiplication operand is $0$. The second thread will, therefore, utilize the entire multiplier to produce the original result with no computation error. \subsubsection{4-Bit Sparsity} If both threads are effectively represented by 4b-8b or 4b-4b, computation error is avoided. Without loss in generality, we consider only the 4-bit representation of $X$ inputs. Figure~\ref{fig:smt_example:3} illustrates an example of thread collision. The easiest way to solve the collision is simply by considering only the 4-bit MSBs, as described in Fig.~\ref{fig:smt_example:1}. Instead, we observe that in both threads, the four MSB bits are zero-valued. Therefore, instead of trimming the threads' LSBs, we keep them, taking into account that, in this case, multiplication should not be followed by a shift left operation. 4-bit sparsity of both $X$ and $W$ inputs may be exploited as well, as depicted in Fig.~\ref{fig:smt_example:4}. In this example, the $X$ and $W$ of the first thread are swapped. Now, the $W$ input of the first thread uses the LSBs, neglecting the zero-valued 4-bit MSBs. Even though exploiting data-width variability of both inputs seems trivial, additional hardware is required to dynamically determine which of the inputs, $X$ or $W$, will enter the 4-bit multiplier port. Figure~\ref{fig:smt_example:5} illustrates an example in which 4-bit sparsity and precision reductions are needed. In this example, the first and second threads effectively use 8b-8b and 4b-8b, respectively. The precision of the first thread is, therefore, reduced to fit the multiplier. The values in this example lead to, effectively, no collision, since the 4-bit LSBs of the first thread are all zeros. If this was not so, error was contributed by the first thread. \subsection{Shared Resources} \begin{figure*}[t] \begin{subfigure}{0.32\textwidth} \centering \includegraphics[height=2.2cm]{./imgs/vector_tiling1.pdf} \caption{Conventional} \label{fig:vector_tiling:1} \end{subfigure} \begin{subfigure}{0.4\textwidth} \centering \includegraphics[height=2.2cm]{./imgs/vector_tiling2.pdf} \caption{Shared MAC, independent psums} \label{fig:vector_tiling:2} \end{subfigure} \begin{subfigure}{0.28\textwidth} \centering \includegraphics[height=2.2cm]{./imgs/vector_tiling3.pdf} \caption{Shared MAC, shared psum} \label{fig:vector_tiling:3} \end{subfigure} \caption{Shared resources. \textbf{(a) Conventional:} A single input, $(X,W)$, feeds a single MAC unit to produce a single output, $O$, in a single partial sum register (psum). \textbf{(b) Shared MAC:} Two independent threads, $(X,W)_1$ and $(X,W)_2$, feed a single MAC unit, producing two independent outputs, $O_1$ and $O_2$, respectively. \textbf{(c) Shared MAC and psum:} Two threads, \emph{originating from the same input}, feed a single MAC unit, producing a single output.} \label{fig:vector_tiling} \end{figure*} NB-SMT{} can execute several independent threads, i.e., per-thread $X$, $W$, and $O$, which is, in a sense, similar to the way conventional SMT operates whereby each hardware thread is executed independently. Logically, however, threads can be dependent, so instead of independent ``DNN threads'' we propose threads that originate from the same execution flow, somewhat similar to the difference between software threads and processes. By doing so, we can share not only the MAC unit but also additional resources: (1) activation registers sharing: the same activation is used with different weights (filters), thereby computing different output activations; (2) weight registers sharing: the same weight is used with different activations (e.g., batch or another convolution window), thereby computing different output activations; and (3) output registers sharing: different activations and their corresponding weights compute the same output activation. We focus here on output sharing. Let $(X,W)$ be an input pair that consists of two vectors of length $K$ that are to be multiplied. Obviously, the multiplication result is a scalar equal to $\sum_{i=0}^{K-1} x_i w_i$. With 2T NB-SMT{}, for example, instead of doubling the partial sum registers, we split the input vectors, $X$ and $W$, between the two threads, and so both thread results are summed up to produce a single scalar value. In other words, given two independent threads, $(X,W)_1$ and $(X,W)_2$, of respective lengths $K_1$ and $K_2$, the outputs are also independent as follows: \begin{equation} O_1 = \sum_{i=0}^{K_1-1} x_i^{(1)} w_i^{(1)} \;\;\; \text{and} \;\;\; O_2 = \sum_{i=0}^{K_2-1} x_2^{(2)} w_i^{(2)} \,. \end{equation} A single $(X,W)$ input pair may, however, can span two different threads: \begin{equation} \begin{aligned} \text{Thread 1:} \;\;\; &(X[0, K/2-1], W[0, K/2-1]) \\ \text{Thread 2:} \;\;\; &(X[K/2, K-1], W[K/2, K-1]) \,, \end{aligned} \label{eq:vec_threads} \end{equation} where $G[i_1,i_2]$ denotes an arbitrary vector $G$, such as $X$ or $W$, consisting of elements $i_1$ through $i_2$, and, for simplicity's sake, we assume $K$ is an even number. Both threads therefore contribute to the same output as follows (see Fig.~\ref{fig:vector_tiling}): \begin{equation} O = \sum_{i=0}^{K/2-1} x_i w_i + \sum_{i=K/2}^{K-1} x_i w_i \,. \label{eq:vec_sum} \end{equation} \section{SySMT{}: Architecture Use Case} \label{sec:sa} NB-SMT{} may be enabled in different DNN hardware architectures. Specifically, we use an output-stationary (OS) systolic array (SA) designated for matrix multiplication \cite{kung1979systolic, gupta2015deep} as our case study. In this section, we first briefly review SAs. We then describe how data may be organized to decrease the number of thread collisions. And finally, we present the microarchitecture of the OS-SA NB-SMT{} --- SySMT{}. Throughout this paper we focus on the computation core. \subsection{Output-Stationary Systolic Arrays} SAs comprise a grid of processing elements (PEs). PEs work in tandem: each PE independently receives inputs from its upstream PE neighbors, conducts a certain task whose result it stores locally, and forwards its inputs downstream. The well-defined interactions between adjacent PEs and the specific and confined task that each PE conducts enable efficient data reuse and scalability \cite{kung1979systolic}. SAs serve many applications and come in many shapes and forms. Specifically, we take an SA designated for matrix multiplication and use it for computation of convolutional layers \cite{chetlur2014cudnn}. In addition, we use a variant of SA that is OS. In the OS-SA, each PE receives an activation and weight per cycle and accumulates their multiplication results locally. Data is pushed to the PE array in a skewed manner, so that corresponding activations and weights meet in the appropriate PE. Figure~\ref{fig:os-sa_arch} depicts the OS-SA architecture and PE microarchitecture. The SySMT{} grid is almost identical to the conventional SA grid, except that connectivity is scaled with the number of threads, as illustrated in Fig.~\ref{fig:os-sa_mt_arch}. In Fig.~\ref{fig:vector_tiling:3} we illustrated how an input vector is split into two threads; in the same manner, we split the activation and weight input matrices into two threads. Let $X_{M \times K}$ and $W_{K \times N}$ be the two input matrices, and consider a 2-threaded design, for example. Each row in $X$ and each column in $W$ is split as described by Eq.~(\ref{eq:vec_threads}). Each PE is therefore able to perform the computation presented in Eq.~(\ref{eq:vec_sum}). \subsection{Data Arrangement} \label{sec:reorder} Given two threads, it would be ideal if data was arranged so that in each cycle, one thread holds at least one zero-valued term and the other thread does not, or that both threads hold a pair represented by 4b-8b or 4b-4b. Reordering the data is not, however, trivial: (1) it is impractical to reorder the activation matrices according to their momentary values, since activation values are dynamic; (2) weights are static during inference, but we do not expect the weight tensors to exhibit much correlation between rows as we expect from the activation columns, since each row in the input activations matrix represents a sliding window \cite{chetlur2014cudnn}, and activations are known to exhibit spatial correlation \cite{mahmoud2018diffy, shomron2019thanks}; and (3) the SA structure dictates specific scheduling of the data inputs. Given the two $X_{M \times K}$ and $W_{K \times N}$ input matrices, reordering of $X$ must take place in column granularity followed by reordering of the corresponding $W$ rows accordingly so as to maintain SA data scheduling. Considering these constraints, we reorder the matrices according to per-layer statistics which are gathered \emph{once} on the activations \cite{zhao2019overwrite, migacz20178}. Using a random subset of the training set, we log which activation matrix columns are most likely to hold data that is represented by 8-bits. With these statistics in hand, which at this point are static, the activation matrices are rearranged so that an 8-bit activation value from one thread is more likely to be paired with a zero-valued activation from the other thread, and so that a 4-bit activation value from the one thread is paired with another 4-bit activation from the other thread (Fig.~\ref{fig:reorder}). In practical terms, during runtime the accelerator will rearrange the layer output according to the pre-determined order for the next layer. This mechanism is not part of the SySMT{} core, and is therefore beyond the scope of this paper. \begin{figure*}[t] \begin{subfigure}[b]{.45\textwidth} \centering \includegraphics[height=4.8cm]{./imgs/os_sa_arch_2.pdf} \caption{Conventional OS-SA} \label{fig:os-sa_arch} \end{subfigure} \begin{subfigure}[b]{.55\textwidth} \centering \includegraphics[height=4.8cm]{./imgs/os_sa_mt_arch_2.pdf} \caption{2T SySMT{}} \label{fig:os-sa_mt_arch} \end{subfigure} \caption{Architecture and microarchitecture of a 3$\times$3 OS-SA and SySMT{}.} \label{fig:arch} \end{figure*} \begin{figure}[t] \centering \begin{subfigure}[b]{\columnwidth} \centering \includegraphics[height=3.7cm]{./imgs/reorder_before.pdf} \caption{Before reordering} \label{fig:reorder:before} \end{subfigure} \begin{subfigure}[b]{\columnwidth} \centering \includegraphics[height=3.7cm]{./imgs/reorder_after.pdf} \caption{After reordering} \label{fig:reorder:after} \end{subfigure} \caption{Example of activation and weight tensors from ResNet-18 + ImageNet before and after data arrangement. Bold red pixels represent high positive values, bold blue pixels represent high negative values, and white pixels are zeros. It is evident that the activation matrix columns are correlated.} \label{fig:reorder} \end{figure} \subsection{PE Microarchitecture} In addition to the circuitry of a conventional OS-SA PE, the SySMT{} PE requires additional circuitry: (1) flexible multiplier units capable of conducting different precision multiplications on demand; (2) a controller for selecting the right MAC operation as a function of the current input sparsity and/or data width; (3) on-the-fly precision reduction units; and (4) additional output buffers, two per thread (for activation and weight). \subsubsection{Multiplication Decomposition} \label{sec:fmac} In the spirit of \cite{sharma2018bit}, we use a flexible multiplier unit (fMUL) capable of multiplication decomposition. Consider an 8b-8b multiplier and two 8-bit scalar inputs: activations, $\tilde{x}$, and weights, $\tilde{w}$. We set $\tilde{w}$ to be signed and $\tilde{x}$ to be unsigned, since it is common for activations to follow the ReLU activation function. Multiplication of these two inputs can be formulated as follows: \begin{equation} \begin{aligned} \tilde{x} \cdot \tilde{w} &= \sum_{i=0}^{7} 2^i x_i \cdot \tilde{w} = \left( \sum_{i=4}^{7} 2^i x_i + \sum_{i=0}^{3} 2^i x_i \right) \cdot \tilde{w} \\ &= \left( 2^4 \sum_{i=0}^{3} 2^{i} x_{i+4} + \sum_{i=0}^{3} 2^i x_i \right) \cdot \tilde{w} \\ &= (\verb|<<| \; 4) \underbrace{ ( \{0, \tilde{x}_{\text{MSB}} \} \cdot \tilde{w} )}_{\text{5b-8b sign mult}} + \underbrace{( \{0, \tilde{x}_{\text{LSB}} \} \cdot \tilde{w} ) }_{\text{5b-8b sign mult}} \,, \end{aligned} \end{equation} where we converted $\tilde{x}_{\text{MSB}}$ and $\tilde{x}_{\text{LSB}}$ into two's complement by adding a zero-valued MSB. This formulation shows that a multiplication of 8-bit unsigned with 8-bit signed can be implemented with two 5b-8b multipliers and a shift. By adding an additional 4-bit shift to the second 5b-8b signed multiplier and control, we achieve a generalized fMUL that is capable of two independent unsigned-signed 4b-8b multiplications or a single unsigned-signed 8b-8b multiplication, as illustrated in Fig.~\ref{fig:flex_mac_248}. Moreover, a 4b-8b multiplication can be shifted if the original value was approximated using its 4-bit MSBs. For example, consider the case illustrated in Fig.~\ref{fig:smt_example:5}. The multiplier performs a 2x4b-8b multiplication, since the first thread's MSBs are used. Also, notice that the 4-bit MSBs of the first thread are the input to the multiplier, as opposed to the second thread whose 4-bit LSBs are the input to the multiplier. The following multiplication then takes place: $1110_2 \cdot 00010111_2 = 322_{10}$ and $0010_2 \cdot 11110010_2 = 484_{10}$. The first thread computation is followed by a 4-bit shift, which yields a result of $5152_{10} + 484_{10} = 5636_{10}$. In a similar manner, an 8b-8b multiplication can be formulated as \begin{equation} \begin{aligned} \tilde{x} \cdot \tilde{w} &= \sum_{i=0}^{7} 2^i x_i \cdot \left( -2^7 w_7 + \sum_{i=0}^{6} 2^i w_i \right) \\ &= \left( \sum_{i=4}^{7} 2^i x_i + \sum_{i=0}^{3} 2^i x_i \right) \cdot \left( -2^7 w_7 + \sum_{i=4}^{6} 2^i w_i + \sum_{i=0}^{3} 2^i w_i \right) \\ &= (\verb|<<| \; 8) \overbrace{ ( \{0, \tilde{x}_{\text{MSB}} \} \cdot \tilde{w}_{\text{MSB}} ) }^{\text{5b-4b sign mult}} + (\verb|<<| \; 4) \overbrace{ ( \tilde{x}_{\text{MSB}} \cdot \tilde{w}_{\text{LSB}} ) }^{\text{4b-4b unsign mult}} + \\ & \;\;\;\;\;\, (\verb|<<| \; 4) \underbrace{ ( \{0, \tilde{x}_{\text{LSB}} \} \cdot \tilde{w}_{\text{MSB}} ) }_{\text{5b-4b sign mult}} + \underbrace{ (\tilde{x}_{\text{LSB}} \cdot \tilde{w}_{\text{LSB}} ) }_{\text{4b-4b unsign mult}} \,. \end{aligned} \end{equation} The 8b-8b multiplication can be represented as a combination of two 4b-4b unsigned multiplications and two 5b-4b signed multiplications. By adding additional shift logic and control, we can generalize this circuit to be capable of performing either four independent 4b-4b multiplications, two independent 4b-8b multiplications, or one 8b-8b multiplication. The 8b-8b multiplication can be further decomposed or formulated with any other N-bit input variables. In this paper, however, we only use the two decompositions above, for a 2-threaded and a 4-threaded SySMT{}. \begin{figure}[t] \centering \includegraphics[width=\columnwidth]{./imgs/flex_mac_248.pdf} \caption{Flexible multiplier (fMUL), capable of either one 8b-8b multiplication or two independent 4b-8b multiplications.} \label{fig:flex_mac_248} \end{figure} \subsubsection{Local PE Control} \label{sec:pe_ctrl} The conventional PE array is highly scalable due to lack of control. Each PE is responsible for a specific task which it conducts locally. The decision of how to use the local fMUL is, therefore, dynamic and local to each PE. Algorithm~\ref{alg:algorithm1} describes how a 2-threaded PE exploits input sparsity and effective data width (of activations, without loss of generality) to prepare the input data and control for the fMUL unit. Each cycle, the PE checks the input computation demands versus its available resources, in this case, an 8b-8b fMAC. If the two threads require the fMAC, the PE checks the data-width of each thread and forwards either its 4-bit MSBs or LSBs. If one of the threads does not require the fMAC, the PE passes the active thread to the fMUL, enabling an error-free 8b-8b multiplication. In either case, the PE sets the corresponding shift signals. \begin{algorithm}[t] \caption{--- 2T SySMT{} PE Logic}\label{alg:algorithm1} \begin{algorithmic}[1] \Require Two input pairs, $\{x_0, w_0\}$ and $\{x_1, w_1\}$ \Ensure MAC inputs, $\{\tilde{x}_0, \tilde{w}_0\}$, $\{\tilde{x}_1, \tilde{w}_1\}$, and $\{s_0, s_1\}$ \Statex \For{$\forall~\text{cycle}$} \If{$\text{all arguments are non-zero}$} \For{$\forall~\text{thread}~i$} \If{$\text{MSBs}(x_i) = \text{4'b0}$} \Comment{4-bit is suffice} \State $\tilde{x}_i \gets \text{LSBs}(x)$ \State $s_i \gets 0$ \Else \Comment{On-the-fly quantization} \State $\tilde{x}_i \gets \text{MSBs}(x_i) + x_i[3]$ \Comment{Rounding} \State $s_i \gets 1$ \Comment{Shifted after multiplication} \EndIf \State $\tilde{w}_i \gets w_i$ \EndFor \Else \State $i \gets \text{GetActiveThread}(\{x_0, w_0\}, \{x_1, w_1\})$ \State $\{\tilde{x}_0, \tilde{w}_0\} \gets \{\text{LSBs}(x_i), w_i\}$ \State $\{\tilde{x}_1, \tilde{w}_1\} \gets \{\text{MSBs}(x_i), w_i\}$ \State $\{s_0, s_1\} \gets \{0, 1\}$ \EndIf \EndFor \end{algorithmic} \label{alg:t2_ctrl} \end{algorithm} The 4-threaded (4T) implementation considers two more options. When all four threads require the fMAC, all activations and weights precision are reduced to 4 bits according to the effective input data-width of each thread (i.e., MSBs or LSBs). For simplicity's sake, a collision of three threads is treated similarly; that is, we reduce all input precision, even though theoretically one thread can utilize a 4b-8b MAC. Cases of two thread collisions or no collision are handled in the same manner that a 2-threaded SySMT{} does, but with additional logic that marks the active threads. \subsubsection{Putting It All Together} Enabling NB-SMT{} does not only require the fMUL (Section~\ref{sec:fmac}) and the control logic (Section~\ref{sec:pe_ctrl}), but also additional activation and weight output registers and on-the-fly precision reduction logic (Fig.~\ref{fig:arch}). First, the output registers are scaled linearly with the number of threads. Second, to reduce inputs represented by more than 4 bits to 4 bits, we first round them to the nearest integer that is a whole multiple of 16. This is done by summation of the bit at index 3 with the 4-bit MSBs, i.e., $x[7{:}4] + x[3]$. This is applicable for both signed and unsigned representations. For example, $59_{10} = 00111011_2 \Rightarrow 0011_2 + 1_2 = 0100_2 \Rightarrow 0100_2 \; \verb|<<| \; 4 = 64_{10}$; and $-59_{10} = 11000101_2 \Rightarrow 1100_2 + 0_2 = 1100_2 \Rightarrow 1100_2 \; \verb|<<| \; 4 = -64_{10}$. The only difference will occur with numbers that are at the same distance from the nearest integer that is a whole multiple of 16, for example, $56_{10}$ will be rounded to $64_{10}$, whereas $-56_{10}$ will be rounded to $-48_{10}$. SySMT{} data propagates the same as in conventional SA --- each cycle data enters and exits the PEs regardless of the data content. To maintain such systematic non-blocking operation, we trade backpressure by temporarily reducing numerical precision. Moreover, avoiding backpressure yields a constant speedup; a 2-threaded and a 4-threaded SySMT{} will deliver a speedup of 2$\times$ and 4$\times$, respectively. In the next section, we evaluate the impact of SySMT{} on accuracy as well as on the hardware. \section{Evaluation} \label{sec:eval} The execution of a DNN layer with two and four threads achieves a constant speedup of 2$\times$ and 4$\times$. However, the actual impact of NB-SMT{} on the underlying hardware, as well as on DNN accuracy, has yet to be evaluated. In Section~\ref{sec:eval:math}, we describe our evaluation environment and estimate the hardware area, power, and energy; in Section~\ref{sec:eval:exp}, we present the results of 2T and 4T SySMT{}s with five popular CNN models. \subsection{Methodology} \label{sec:eval:math} \textbf{Workloads.} To evaluate SySMT{}, we use the ILSVRC-2012 dataset \cite{russakovsky2015imagenet} with five popular CNN models for image classification, as described in Table~\ref{tbl:workloads}. The models are quantized with a simple 8-bit uniform min-max quantization, using symmetric unsigned quantization for activations and symmetric signed quantization for weights \cite{krishnamoorthi2018quantizing}. In addition, activations are quantized per layer, whereas weights are quantized per kernel. This configuration supports an efficient hardware implementation, since each dot product result is multiplied by only two scaling factors: the activations' scaling factor and the corresponding kernel's scaling factor \cite{kravchik2019low}. Prior to CNN execution, we conduct a quick statistics gathering run on 2K randomly picked images from the training set. In this rapid phase, we average the min-max values, correct the batch-norm layers' running mean and running variance, and log the relevant reordering statistics as described in Section~\ref{sec:reorder}; none of these steps involve gradient computation or weight update with gradient descent. In Section~\ref{sec:eval:exp:4t}, we explore the performance of a 4T SySMT{} given a pruned network. For weight pruning, we use simple magnitude-based pruning that iteratively prunes a certain percentage of the model weights followed by retraining, similar to \cite{han2015learning}. \begin{table}[] \centering \begin{tabular}{l|rr|rr} \hline \multicolumn{1}{c|}{} & \multicolumn{2}{c|}{\textbf{Accuracy}} & \multicolumn{2}{c}{\textbf{MAC Ops.}} \\ \multicolumn{1}{c|}{} & \multicolumn{1}{c}{\textbf{FP32}} & \multicolumn{1}{c|}{\textbf{INT8}} & \multicolumn{1}{c}{\textbf{CONV}} & \multicolumn{1}{c}{\textbf{FC}} \\ \hline AlexNet~\cite{krizhevsky2014one} & 56.55\% & 56.36\% & 0.6G & 59M \\ ResNet-18~\cite{he2016deep} & 69.76\% & 69.70\% & 1.8G & 0.5M \\ ResNet-50~\cite{he2016deep} & 76.15\% & 76.24\% & 4.1G & 2M \\ GoogLeNet~\cite{szegedy2015going} & 69.78\% & 69.63\% & 1.5G & 1M \\ DenseNet-121~\cite{huang2017densely} & 74.65\% & 74.66\% & 2.7G & 1M \\ \hline \end{tabular}% \caption{The evaluated CNN models. MAC operations are for a single input image.} \label{tbl:workloads} \end{table} \textbf{DNN simulation.} We use PyTorch 1.3.1 \cite{paszke2019pytorch} to simulate the impact of SySMT{} on the CNN model accuracies. Throughout this section, we consider only the convolution layers, since convolution MAC operations consume the bulk of the model operations (Table~\ref{tbl:workloads}). Also, both the first layer and the fully-connected layers are left intact. The convolution operations were mapped to matrix multiplication operations to fit the hardware simulator \cite{chetlur2014cudnn, kung2018mapping}. \textbf{Hardware simulation.} We implement a 16$\times$16 OS-SA baseline and 16$\times$16 2T and 4T SySMT{} cores with SystemVerilog. Synthesis is performed using Synopsys Design Compiler \cite{designcompiler} with the 45nm NanGate open cell \cite{knudsen2008nangate} at a clock frequency of 500MHz (similar to \cite{akhlaghi2018snapea}). Area and power estimations are extracted from Cadence Innovus \cite{innovus}. PEs are pipelined internally without affecting the systematic propagation of data between PEs in each cycle. The pipeline has two stages: the first includes multiplication and control, and the second includes accumulation. The two-staged pipeline increases latency by a cycle but does not affect throughput. Table~\ref{tbl:hw_summary} describes the hardware configuration. \begin{table}[] \centering \begin{tabular}{lcrr} \hline & \multicolumn{1}{l|}{\textbf{}} & \multicolumn{2}{c}{\textbf{SySMT{}}} \\ \multicolumn{1}{l|}{} & \multicolumn{1}{c|}{\textbf{SA}} & \multicolumn{1}{c}{\textbf{2T}} & \multicolumn{1}{c}{\textbf{4T}} \\ \hline \multicolumn{1}{l|}{Array Size} & \multicolumn{3}{c}{16$\times$16 PEs} \\ \multicolumn{1}{l|}{Frequency} & \multicolumn{3}{c}{500MHz} \\ \multicolumn{1}{l|}{Technology} & \multicolumn{3}{c}{45nm \cite{knudsen2008nangate}} \\ \multicolumn{1}{l|}{Throughput [GMACS]} & \multicolumn{1}{r}{256} & $^\dagger$512 & $^\dagger$1024 \\ \multicolumn{1}{l|}{Power [mW] @ 80\% Util.} & \multicolumn{1}{r}{320} & 429 & 723 \\ \multicolumn{1}{l|}{Total Area [mm\textsuperscript{2}]} & \multicolumn{1}{r}{0.220} & 0.317 & 0.545 \\ \multicolumn{1}{l|}{PE [\textmu m\textsuperscript{2}]} & \multicolumn{1}{r}{853} & 1233 & 2122 \\ \multicolumn{1}{l|}{MAC [\textmu m\textsuperscript{2}]} & \multicolumn{1}{r}{591} & 786 & 1102 \\ \hline \end{tabular} \caption{Design parameters, power, and area breakdown. PE area includes thread registers, control logic, and the MAC unit. MAC units are two-stage pipelines; their areas include the registers. $^\dagger$SySMT{} throughput is 2$\times$ and 4$\times$ for 2 and 4 threads, respectively, with on-demand precision reduction.} \label{tbl:hw_summary} \end{table} \textbf{Power and energy.} We estimate power consumption using a synthetic testbench that simulates different SA utilizations. A utilized PE is defined as a PE with a working MAC unit in any capacity, that is, both operands of at least one input pair are not equal to zero. To meet a certain utilization operating point, the testbenches zero out the activations at a probability corresponding to a configured utilization. Activations, rather than weights, are zeroed out, since weights are usually non-zero (when not considering pruning). The testbenches are used to produce value change dumps that are eventually used to estimate the power of the different SAs. To estimate energy consumption, we use our PyTorch-based simulator to extract average utilization per layer from each CNN model. Given the average power of layer $l$, $P_l$, we calculate the energy consumed by layer $l$ as follows: \begin{equation} \begin{aligned} E_l = \frac{\text{MAC}_l}{\text{Throughput}} \cdot P_l \,, \end{aligned} \end{equation} where $\text{MAC}_l$ is the number of MAC operations in layer $l$. The total model energy is the sum over all layers ($L$): ${E = \sum_{l=1}^{L} E_l}$. Our evaluation shows that SySMT{} saves an average of 33\% and 35\% energy when executing the five CNNs with 2 and 4 threads, respectively. A 2T SySMT{} does not consume twice the power of a conventional SA. For example, we estimate that a conventional SA and a 2T SySMT{} consume 277mW @ 40\% utilization and 429mW @ 80\% utilization, respectively. Assuming that two threads increase utilization by exactly 2$\times$, the power increase is 1.5$\times$ (429mW @ 80\% divided by 277mW @ 40\%). Since the 2T SySMT{} has a constant speedup of 2$\times$ over the conventional SA, energy is reduced. Energy is further reduced when actual utilization is not doubled or quadrupled, in which case the number of effective MAC operations is reduced. \subsection{Experimental Results} \label{sec:eval:exp} \subsubsection{Model Robustness} During inference, SySMT{} reduces the precision of parts of the computations to 4 bits. Precision reduction is conducted on-the-fly without variance and bias corrections, which are common in pure quantization mechanisms \cite{finkelstein2019fighting, banner2019post}. We consider a model as more robust than another if it achieves better accuracy given a decrease in its activations and weights representation \cite{shkolnik2020robust}. A model whose entire representation was reduced from 8b activations and weights (A8W8) to, for example, 4b activations and 8b weights (A4W8) is equivalent to the worst-case scenario for a 2T SySMT{}. It may, therefore, be considered as the lower accuracy boundary for the 2-threaded implementation. Figure~\ref{fig:exp:robustness} illustrates model robustness to further quantization of the entire model given an A8W8 baseline. For example, an 8b-8b GoogLeNet whose activations are further quantized to 4 bits incurs a 6.2\% accuracy drop. We observe that besides ResNet-50, all models are more robust to quantization of their activations rather than their weights. Therefore, when it is necessary to reduce threads precision, we prefer SySMT{} to further quantize its activations; we only consider further weight quantization for two-thread collisions with ResNet-50. \begin{figure}[t] \centering \begin{tikzpicture} \begin{axis}[ ybar, bar width=6pt, width=8.8cm, height=5.0cm, enlarge x limits=0.13, enlarge y limits=0, xlabel near ticks, ylabel near ticks, legend style={at={(0.5,-0.20)}, anchor=north,legend columns=-1}, ylabel={Top-1 Accuracy [\%]}, symbolic x coords={AlexNet, ResNet18, ResNet50, GoogLeNet, DenseNet}, xtick=data, x tick label style = {font=\footnotesize, rotate=20}, y tick label style = {font=\footnotesize}, legend style={font=\scriptsize, legend columns=5, legend cell align=left, at={(0.5, 1.01)}, anchor=south, draw=none}, tick style={draw=none}, ymajorgrids, major grid style={dashed}, nodes near coords, ymin={25}, ymax={88}, every node near coord/.append style={font=\scriptsize, rotate=90, anchor=west}, set layers=Bowpark ] \addplot[fill=black!60] plot coordinates {(AlexNet,56.4) (ResNet18,69.7) (ResNet50,76.2) (GoogLeNet,69.6) (DenseNet,74.7)}; \addplot[fill=black!40] plot coordinates {(AlexNet,53.0) (ResNet18,66.6) (ResNet50,70.1) (GoogLeNet,63.4) (DenseNet,71.9)}; \addplot[fill=black!30] plot coordinates {(AlexNet,52.3) (ResNet18,50.9) (ResNet50,72.5) (GoogLeNet,41.8) (DenseNet,66.1)}; \addplot[fill=black!20] plot coordinates {(AlexNet,48.0) (ResNet18,45.3) (ResNet50,63.2) (GoogLeNet,28.9) (DenseNet,60.1)}; \legend{A8W8 (Baseline), A4W8, A8W4, A4W4} \end{axis} \end{tikzpicture} \caption{Model robustness to on-the-fly numerical precision reduction of the entire model. The results may be considered as the \emph{worst-case} model performance for two threads (A4W8 and A8W4) and four threads (A4W4). Baseline quantization is 8-bit activations and weights (A8W8) with batch-norm recalibration. The other quantized operating points derive from the baseline without any calibration, similar to how the PEs perform the precision reduction on-the-fly.} \label{fig:exp:robustness} \end{figure} \subsubsection{2T SySMT{}} \textbf{Sparsity and data-width.} NB-SMT{} exploits 8-bit and 4-bit input sparsity to mitigate noise involved in ``squeezing'' threads into a shared MAC unit. Table~\ref{tbl:exp:sparse_quant} presents the impact of independently exploiting sparsity (8-bit) and data-width (4-bit) on the different CNN models, given a 2T SySMT{}. We denote the different options as follows: \renewcommand{\labelitemi}{\textendash} \begin{itemize} \item \textbf{S:} exploiting 8-bit sparsity, as illustrated in Fig.~\ref{fig:smt_example:2}. \item \textbf{A (W):} exploiting activation (weight) data-width (4-bit) and reducing their precision on-demand, as illustrated in Fig.~\ref{fig:smt_example:3}. \item \textbf{Aw (aW):} exploiting activation and weight data-width (4-bit) and reducing activation (weight) precision on-demand, as illustrated in Fig.~\ref{fig:smt_example:4}. \end{itemize} As expected, the combination of exploiting sparsity and data-width variability (S+A and S+W) achieves the best results. Exploiting both activation and weight sparsity (S+Aw and S+aW) does not, however, yield significant or consistent improvement in accuracy. Therefore, throughout this evaluation we exploit either S+A (for all models) or S+W for ResNet-50. \begin{table}[t] \centering \resizebox{\columnwidth}{!}{% \begin{tabular}{lrrcrrrr} \hline & \multicolumn{1}{l}{\textbf{}} & \multicolumn{1}{l|}{\textbf{}} & \multicolumn{5}{c}{\textbf{A8W8 SySMT{}}} \\ \multicolumn{1}{l|}{} & \multicolumn{1}{c}{\textbf{A8W8}} & \multicolumn{1}{c|}{\textbf{min}} & \textbf{S} & \multicolumn{1}{c}{\textbf{A}} & \multicolumn{1}{c}{\textbf{Aw}} & \multicolumn{1}{c}{\textbf{S+A}} & \multicolumn{1}{c}{\textbf{S+Aw}} \\ \hline \multicolumn{1}{l|}{AlexNet} & 56.36 & \multicolumn{1}{r|}{53.03} & \multicolumn{1}{r}{54.52} & 56.04 & 56.05 & 56.21 & 56.22 \\ \multicolumn{1}{l|}{ResNet-18} & 69.70 & \multicolumn{1}{r|}{66.59} & \multicolumn{1}{r}{67.86} & 67.60 & 67.66 & 68.49 & 68.38 \\ \multicolumn{1}{l|}{GoogLeNet} & 69.63 & \multicolumn{1}{r|}{63.42} & \multicolumn{1}{r}{66.09} & 65.37 & 65.46 & 67.45 & 67.34 \\ \multicolumn{1}{l|}{DenseNet-121} & 74.66 & \multicolumn{1}{r|}{71.94} & \multicolumn{1}{r}{73.45} & 73.00 & 73.23 & 74.05 & 73.87 \\ \hline & \multicolumn{1}{c}{} & \multicolumn{1}{c}{} & & \multicolumn{1}{c}{} & \multicolumn{1}{c}{} & \multicolumn{1}{c}{} & \multicolumn{1}{c}{} \\ \hline & \multicolumn{1}{c}{\textbf{}} & \multicolumn{1}{c|}{\textbf{}} & \multicolumn{5}{c}{\textbf{A8W8 SySMT{}}} \\ \multicolumn{1}{l|}{} & \multicolumn{1}{c}{\textbf{A8W8}} & \multicolumn{1}{c|}{\textbf{min}} & \textbf{S} & \multicolumn{1}{c}{\textbf{W}} & \multicolumn{1}{c}{\textbf{aW}} & \multicolumn{1}{c}{\textbf{S+W}} & \multicolumn{1}{c}{\textbf{S+aW}} \\ \hline \multicolumn{1}{l|}{ResNet-50} & 76.24 & \multicolumn{1}{r|}{72.49} & \multicolumn{1}{r}{74.36} & 72.36 & 73.00 & 75.10 & 75.22 \\ \hline \end{tabular}% } \caption{Contribution of exploiting sparsity and/or data-width variability to CNNs' top-1 accuracy with a 2T SySMT{} and without reordering.} \label{tbl:exp:sparse_quant} \end{table} \textbf{Mean squared error (MSE).} Since GoogLeNet is the one model that exhibits an accuracy drop of more than 1\% (2.18\%), we examine its per-layer MSE due to on-demand precision reduction. That is, for each layer we compute the MSE between its output, with and without NB-SMT{} (without NB-SMT{} is considered error-free). Figure~\ref{fig:googlenet:mse_sparsity} presents the MSE versus the activations sparsity for each GoogLeNet layer, with and without reordering. MSE and sparsity are correlated, since less sparsity means that more thread collisions occur, and vice versa. First, we observe that activation reordering decreases the MSE of all layers in GoogLeNet by avoiding thread collisions. As for classification accuracy, reordering increases the accuracy of ResNet-18, ResNet-50, GoogLeNet, and DenseNet-121 by 0.64\%, 0.24\%, 0.49\%, and 0.35\%, respectively. Insignificant improvement was recorded in AlexNet. Second, MSE differs between layers. SySMT{} is tunable, and specific layers can be executed with one thread and therefore be error-free. By doing so, we can trade speedup for accuracy. To increase GoogLeNet accuracy so as to meet, for example, a 1\% accuracy degradation cap, we execute GoogLeNet without the layer that exhibits the highest MSE. Since that layer had an insignificant number of MAC operations relative to the rest of the model, we achieve a speedup of 1.98$\times$ with a 69.25\% accuracy --- a 0.38\% degradation from the A8W8 baseline. \begin{figure}[t] \centering \begin{tikzpicture} \begin{axis}[ title style={font=\footnotesize, at={(0.5, 0.95)}, anchor=south}, ylabel={MSE (log scale)}, xlabel={Activations Sparsity [\%]}, xmin={0}, xmax={100}, width=8.5cm, height=5.0cm, xtick pos=left, ytick pos=left, xlabel near ticks, ylabel near ticks, xmajorgrids, ymajorgrids, major grid style={dashed}, x tick label style = {font=\scriptsize}, y tick label style = {font=\scriptsize}, legend style={font=\scriptsize, legend columns=3, at={(0.02, 0.1)}, anchor=west}, label style = {font=\footnotesize}, ymode = log, set layers=Bowpark ] \addplot[mark=*, mark size=1.4pt, color=pa1, only marks] file {plotdata/mse_sparsity_w_reorder.dat}; \addplot[mark=square*, mark size=1.4pt, color=pa3, only marks] file {plotdata/mse_sparsity_wo_reorder.dat}; \legend{w/ Reorder, w/o Reorder}; \end{axis} \end{tikzpicture} \caption{GoogLeNet MSE due to 2T SySMT{} as a function of sparsity. Each dot represents a layer.} \label{fig:googlenet:mse_sparsity} \end{figure} \textbf{Accuracy comparison}. A 2T SySMT{} enables 8b-8b computations with occasional precision reduction to 4b-8b, which, in a sense, is equivalent to a 4b-8b quantized model. On the one hand, SySMT{} is capable of maintaining some of the 8-bit computations, thereby reducing some noise. On the other hand, precision reduction is conducted on-the-fly, and SySMT{} lacks the careful quantization parameter adjustments that post-training quantization techniques perform. We compare 2T SySMT{} accuracy results to two state-of-the-art post-training quantization methods (Table~\ref{tbl:vdsmt_2t_acc_compare}). ACIQ \cite{banner2019post} limits the range of the model tensor values by approximating the optimal clipping value analytically from its distribution; and LBQ \cite{kravchik2019low} proposes an optimization framework to find an optimal quantization parameters of each layer. SySMT{} outperforms both ACIQ and LBQ methods in the 4b-8b scenario. \begin{table}[] \centering \begin{tabular}{l|c|crrc} \hline & \textbf{A/W} & \multicolumn{1}{c}{\textbf{SySMT{}}} & \multicolumn{1}{c}{\textbf{LBQ}} & \multicolumn{1}{c}{\textbf{ACIQ}} \\ \hline AlexNet & 4/8 & \textbf{56.23} & 55.51 & 52.30 \\ ResNet-18 & 4/8 & \textbf{69.13} & 68.32 & 65.69 \\ ResNet-50 & 8/4 & \textbf{75.34} & 74.98 & 75.30 \\ DenseNet-121 & 4/8 & \textbf{74.40} & 72.31 & \multicolumn{1}{c}{-} \\ \hline \end{tabular}% \caption{Accuracy comparison of a 2T SySMT{} (with reordering) versus LBQ~\cite{kravchik2019low}, ACIQ~\cite{banner2019post}. The input layers are not quantized. (GoogLeNet was not tested by any of the three comparison methods.)} \label{tbl:vdsmt_2t_acc_compare} \end{table} \textbf{Utilization.} We expect the improvement in utilization and sparsity to be correlated. Low sparsity means relatively little utilization improvement, since utilization was originally high. High sparsity means relatively high utilization improvement, since SySMT{} is capable of ``weaving'' the two threads without collisions. Figure~\ref{fig:googlenet:util_sparsity} presents the utilization improvement of a 2T SySMT{} over a conventional SA, with and without reordering, for GoogLeNet as a function of activation sparsity. The linear trend is somewhat expected. Consider a single PE, $T$ threads, and inputs $x_i$ and $w_i$ where $i$ is the thread number. Assume $r_i$ is the probability of $x_i$ to be non-zero and that $w_i$ is always non-zero. Therefore \begin{equation} \begin{aligned} \Pr(\textrm{utilized PE}) &= \Pr(\exists i, x_i w_i \neq 0) \\ &= 1 - \Pr(\forall i, x_i w_i = 0) \\ &= 1 - \prod\nolimits_{i=0}^T (1 - \Pr(x_i w_i \neq 0)) \\ &= 1 - \prod\nolimits_{i=0}^T (1 - r_i) \,. \end{aligned} \end{equation} For simplicity's sake, we assume all probabilities $r_i$ are equal and that all PEs act the same, so that the PE array utilization is approximately the same as that of a single PE. Utilization improvement of two threads over one thread may, therefore, be formulated as follows: \begin{equation} \begin{aligned} \text{Utilization Gain} = \frac{1 - (1-r)^2}{1 - (1-r)} = s + 1 \,, \end{aligned} \label{eq:util_gain} \end{equation} where $s = (1-r)$ is the sparsity. This result, which is a simple linear curve, is in a good agreement with our measurements (Fig.~\ref{fig:googlenet:util_sparsity}). Reordering increases utilization of SySMT{}, since it trades thread collisions with no collisions, thereby increasing utilization while reducing error. Utilization measurements with reordering are above the analytical line of Eq.~\ref{eq:util_gain}, since the assumption of thread independence does not hold then. Interestingly, even though utilization is not doubled, a 2T SySMT{} still achieves 2$\times$ performance. The mismatch between utilization improvement and performance speedup is due to the PEs' ability to momentarily operate on two low-precision inputs in one cycle by sacrificing some accuracy. \begin{figure}[t] \centering \begin{tikzpicture} \begin{axis}[ ylabel={Util. Improvement [$\times$]}, xlabel={Activations Sparsity [\%]}, width=8.5cm, height=5cm, xmin={0}, xmax={100}, xtick pos=left, ytick pos=left, xlabel near ticks, ylabel near ticks, xmajorgrids, ymajorgrids, major grid style={dashed}, x tick label style = {font=\scriptsize}, y tick label style = {font=\scriptsize}, legend style={font=\scriptsize, legend columns=3, at={(0.98, 0.1)}, anchor=east}, label style = {font=\footnotesize}, set layers=Bowpark ] \addplot[mark=*, mark size=1.4pt, color=pa1, only marks] file {plotdata/util_sparsity_w_reorder.dat}; \addplot[mark=square*, mark size=1.4pt, color=pa3, only marks] file {plotdata/util_sparsity_wo_reorder.dat}; \addplot[mark=none, dashed, line width=0.5pt][domain=0:100] {0.01*x + 1}; \legend{w/ Reorder, w/o Reorder, Eq.~(\ref{eq:util_gain})}; \end{axis} \end{tikzpicture} \caption{GoogLeNet utilization improvement due to SySMT{} as a function of sparsity, with and without statistical data reordering. Each dot represents a layer.} \label{fig:googlenet:util_sparsity} \end{figure} \subsubsection{4T SySMT{}} \label{sec:eval:exp:4t} \textbf{Accuracy comparison.} As opposed to a 2T SySMT{}, thread collisions are more likely to occur in a 4T SySMT{}. Moreover, thread collision of three or four threads results in the precision reduction of all activations and weights, leading to additional noise. We therefore examine SySMT{} operating points, in which some layers execute with two threads instead of four threads, thereby decreasing the noise they contribute during inference. Layers chosen to be slowed down are those with the highest recorded MSE. If different layers exhibit approximately the same MSE, we choose to first slowdown those located at the beginning of the network. Table~\ref{tbl:4t:comparison} presents results for a 4T SySMT{} and compares them with those of LBQ \cite{kravchik2019low}. We do not compare our results to those of ACIQ, since ACIQ quantizes its 4-bit activations per-channel, which is not trivial to be implemented in hardware. It is worth mentioning that LBQ also considers that some layers exhibit high MSEs and therefore should be treated differently. For example, LBQ quadruples the number of 4-bit computations in 23.8\% of ResNet-18 layers to achieve their 4-bit results. We observe that a 4T SySMT{} achieves competitive results compared with LBQ with only minor algorithmic pre-processing (gathering min-max statistics versus finding an optimal solution to an optimization problem). Moreover, SySMT{} is expected to achieve even higher results if pruning is considered. \begin{table}[] \centering \resizebox{\columnwidth}{!}{% \begin{tabular}{l|rrrr} \hline & \multicolumn{3}{c|}{\textbf{4T SySMT{}}} & \multicolumn{1}{l}{} \\ & \multicolumn{1}{c}{\textbf{4T}} & \multicolumn{1}{c}{\textbf{1L@2T}} & \multicolumn{1}{c|}{\textbf{2L@2T}} & \multicolumn{1}{c}{\textbf{LBQ}} \\ \hline AlexNet & 53.65 (4$\times$) & \textbf{56.02} (2.9$\times$) & \multicolumn{1}{c|}{-} & 54.48 \\ ResNet-18 & 64.32 (4$\times$) & 66.08 (3.7$\times$) & \multicolumn{1}{r|}{\textbf{67.98} (3.5$\times$)} & 67.42 \\ ResNet-50 & 70.79 (4$\times$) & 71.96 (3.9$\times$) & \multicolumn{1}{r|}{\textbf{72.72} (3.9$\times$)} & 72.60 \\ GoogLeNet & 60.00 (4$\times$) & 64.47 (3.9$\times$) & \multicolumn{1}{r|}{64.83 (3.9$\times$)} & \multicolumn{1}{c}{-} \\ DenseNet-121 & \textbf{72.41} (4$\times$) & 72.5 (3.8$\times$) & \multicolumn{1}{r|}{72.82 (3.7$\times$)} & 71.56 \\ \hline \end{tabular}% } \caption{4T SySMT{} accuracy and speedup with one (1L) and two (2L) layers set to execute at 2T. LBQ also treats layers with high MSE differently.} \label{tbl:4t:comparison} \end{table} \begin{figure}[t] \centering \begin{tikzpicture} \begin{axis}[ ylabel={Accuracy [\%]}, xlabel={Speedup [$\times$]}, width=8.5cm, height=5cm, xmin={2.9}, xmax={4.1}, xtick pos=left, ytick pos=left, xlabel near ticks, ylabel near ticks, xmajorgrids, ymajorgrids, major grid style={dashed}, x tick label style = {font=\scriptsize}, y tick label style = {font=\scriptsize}, legend style={font=\scriptsize, legend columns=4, at={(0.02, 0.1)}, anchor=west}, label style = {font=\footnotesize}, set layers=Bowpark ] \addplot[mark=*, mark size=1.4pt, color=pa1, line width=0.7pt] file {plotdata/resnet18_acc_speedup_p0.dat}; \addplot[mark=square*, mark size=1.4pt, color=pa2, line width=0.7pt] file {plotdata/resnet18_acc_speedup_p20.dat}; \addplot[mark=triangle*, mark size=1.6pt, color=pa3, line width=0.7pt] file {plotdata/resnet18_acc_speedup_p40.dat}; \addplot[mark=diamond*, mark size=1.6pt, color=pa4, line width=0.7pt] file {plotdata/resnet18_acc_speedup_p60.dat}; \addplot[mark=none, dashed, line width=0.5pt][domain=2.5:5] {69.7}; \legend{0\%, 20\%, 40\%, 60\%}; \end{axis} \node[below] at (6.1, 3.15) {\scriptsize A8W8 (69.7\%)}; \end{tikzpicture} \caption{ResNet-18 accuracy versus 4T SySMT{} speedup with different percentage of pruned weights. Each dot represents a measurement with additional layer tuned to run with two threads.} \label{fig:4t:acc_speedup} \end{figure} \textbf{Weights pruning.} SySMT{} exploits unstructured sparsity in both activations and weights. Yet, conventional DNN training with only a loss function (i.e., no regularization terms) produces weights that do not comprise many zeros. Different techniques have, therefore, emerged to increase weight sparsity either through regularization, e.g. L1, or by iteratively removing weights and retraining the model to compensate for the degradation in accuracy. SySMT{} benefits from sparse inputs, since more zeros means less thread collisions. Figure~\ref{fig:4t:acc_speedup} presents ResNet-18 accuracy for different percentages of pruned weights (e.g., 20\% means that 20\% of weights are equal to zero). As before, we trade speedup for accuracy by slowing down layers to run with two threads. We observe that with a speedup of 4$\times$, the 60\%-pruned model achieves highest accuracy. However, as speedup decreases (i.e., as more layers are slowed down), the most pruned model achieves lowest accuracy. This stems from the fact that the 60\%-pruned model has the lowest baseline accuracy, that is, accuracy of the 60\%-pruned model without SySMT{} is 68.8, 0.9\% below that of original 8-bit model. Therefore, there is a trade-off between how much accuracy is achieved from avoiding thread collisions thanks to pruning and the potential of the baseline pruned model. The method in which we set layers from four threads to two threads may not be the most efficient way in terms of accuracy gains to speedup loss. A different mixture of layers that are set to run with two threads may possibly yield better speedup with better accuracy than those presented in Fig.~\ref{fig:4t:acc_speedup}. We leave this, however, for future work. \section{Discussion and Related Work} \label{sec:related_work} \textbf{Applying NB-SMT{} in other accelerators.} NB-SMT{} may be beneficial in accelerators other than OS-SAs. Google's TPUv1 \cite{jouppi2017datacenter} and TPUv2 \cite{chao2019tpu} implement an SA core. Even though it is weight-stationary (WS), NB-SMT{} may still be enabled similarly to the OS version. Moreover, since TPUv2 comprises floating-point units in its matrix unit (MXU), the relative NB-SMT{} overheads will be smaller than those of SySMT{}. Eyeriss \cite{chen2016eyeriss} is a 16-bit fixed-point accelerator designated for CNNs. It exploits the reuse inherent in the convolution operations with a dataflow scheme named row stationary (RS). Each PE within Eyeriss comprises 12$\times$16b, 224$\times$16b, and 24$\times$16b scratch pads for activations, weights, and partial sums, respectively, and is capable of handling different reuse strategies, such as weight reuse, in an interleaved fashion. Instead of interleaving the data, NB-SMT{} may be used to execute convolution flows in parallel. As with TPUv2, we expect the relative overhead of NB-SMT{} to be smaller than that of SySMT{}, since Eyeriss's PEs are 16-bit, they consist of three pipeline stages, and they have more memory. DaDianNao \cite{chen2014dadiannao} is largely a pipelined version of the basic computations involved in DNNs, which are multiplications, additions, and activation functions. The multipliers in the first pipeline stage may be shared and serve several threads, as long as each multiplier does not contribute to different output activations (i.e., it should use psum sharing). Otherwise, multipliers will need to dynamically propagate their results to the appropriate adder tree as a function of the input values. SnaPEA \cite{akhlaghi2018snapea} is an architecture with early activation prediction. Each PE within SnaPEA comprises compute lanes, and each compute lane is responsible for the computation of a single output activation. An NB-SMT{}-enabled SnaPEA may keep a compute lane utilized in case one of its threads is predicted to be negative. The number of compute lanes may be reduced without affecting performance, while saving area and energy, and SnaPEA pre-processing phase may take NB-SMT{} into consideration. \textbf{Exploiting sparsity.} Sparsity has long been a DNN characteristic exploited in different manners in hardware to achieve performance, power, and energy savings. (1) Exploiting sparsity with dedicated hardware that operates on compressed encodings, such as SparTen~\cite{gondimalla2019sparten}, Cambricon-S~\cite{zhou2018cambricon}, SCNN~\cite{parashar2017scnn}, and EIE~\cite{han2016eie}; (2) Predicting whether certain activations in the layer's output are zero-valued and their computation can be, therefore, skipped. Prediction must be low-cost relative to the original activation computation and can be based on partial computation of the predicted activation \cite{akhlaghi2018snapea, song2018prediction}, on spatially adjacent fully computed activations \cite{shomron2019thanks, shomron2018spatial}, and on input activations \cite{zhu2018sparsenn}, for example; (3) Skipping over zero-valued input activations and weights \cite{albericio2016cnvlutin}, which can be further enhanced by skipping over zero-valued bits \cite{albericio2017bit, sharify2019laconic}; and (4) Actively fine-tuning the DNN parameters to better fit the hardware architecture \cite{kung2018adaptive, liu2020sta}. In this paper, we introduce a fifth approach that has yet to be explored and which is based on the concept of SMT. \textbf{Exploiting data-width variability.} DNNs can maintain accuracy while altering their numerical precision. Numerical representation may differ between layers and within layers. Proteus~\cite{judd2016proteus} and ShapeShifter~\cite{lascorz2019shapeshifter} exploit data-width variability to reduce memory traffic and memory footprint. Stripes~\cite{judd2016stripes} exploits precision variability with bit-serial computations; and Bit Fusion~\cite{sharma2018bit} is a configurable accelerator capable of DNN execution in different bit-widths. In this paper, we exploit data-width variability and DNN tolerance to precision changes in order to ``squeeze'' several threads to the same execution unit in parallel. \section{Conclusions} \label{sec:conclusions} Deep neural networks (DNNs) involve abundant multiply-and-accumulate (MAC) operations, many of which underutilize the underlying hardware due to particular values. In this paper, we mapped the concept of simultaneous multithreading (SMT), known from CPUs, to hardware designated for DNNs. We show that by considering the input values and by acknowledging that DNNs may endure some perturbations in their MAC results, non-blocking SMT (NB-SMT{}) can increase hardware utilization and save energy with negligible accuracy degradation. NB-SMT{} differs from conventional SMT as it does not stall threads on structural hazards. Instead, NB-SMT{} ``squeezes'' threads to the shared resources when a structural hazard occurs, taking advantage of DNN resiliency and enabling the implementation of multithreading even in rigid structures such as systolic arrays (SAs). We implement NB-SMT{} as an extension to an SA, which we name SySMT{}, and evaluate its impact on five popular CNN architectures as well as its area, power, and energy. For example, compared with a conventional SA, a 2-threaded SySMT{} consumes 1.4$\times$ the area and delivers a 2$\times$ speedup with 33\% energy savings with less than 1\% accuracy degradation. \section*{Acknowledgements} We thank Mario Nemirovsky, Yoav Etsion, Shahar Kvatinsky, Ronny Ronen, Tzofnat Greenberg, Moran Shkolnik, Samer Kurzum, and Avi Baum for their valuable feedback. We acknowledge the support of Nvidia for its donation of a Titan V GPU used for this research. This research was supported by Technion AI center and Intel ICRI-CI center. \bibliographystyle{IEEEtranS}
{'timestamp': '2020-04-21T02:27:30', 'yymm': '2004', 'arxiv_id': '2004.09309', 'language': 'en', 'url': 'https://arxiv.org/abs/2004.09309'}
arxiv
\section{Introduction} \label{Introduction} The consensus that human activity caused the climate crisis \cite{cook2016consensus} has led to the development of many tools and agreements, designed to support climate change mitigation efforts. Most notably the Paris Agreement, adopted by 197 countries that aims to keep global warming below 2°C \cite{paris}. However, research efforts to mitigate the climate crisis are lost without an efficient international adaptation of proposed tools and policies. Scientists, non-state actor , and voters increasingly critique their government for insufficient action mitigating climate change \cite{dupont2012insufficient}. This suggests a gap between promises made by politicians and actual action taken: ambitious promises for climate change mitigation have turned into careless discourse with insufficient measures taken. Holding politicians accountable for their actions has been shown to be a major factor in preventing mismanagement, political corruption and misalignment of politician’s opinions and the public they are representing \cite{adsera2003you,lyrio2018thirty}. Transparency herein is so crucial, that it has been considered a direct substitute for accountability in the democratic process \cite{lyrio2018thirty}. Political transparency, unfortunately, has been made increasingly difficult, not due to a lack, but because of the overwhelming quantity of data accessible: The public and civil society organizations, lack the overview of all that politicians are discussing across a multitude of platforms such as interviews, blog posts, parliamentary speeches and social media posts. Our work therefore, provides a tool for transparency, supporting civil society in efforts to monitor political discourse around climate change and hold policy makers accountable for their promises and claims. In Section \ref{section-MuSTAS} we introduce a Multi-Source Topic Aggregation System (MuSTAS) which increases transparency by providing an overview of topics discussed by politicians across a broad range of platforms. Additionally, MuSTAS provides a user interface with topic summaries and tagged source-texts. In Section \ref{section-ml} we describe the ML foundation for MuSTAS: a novel multi-source hybrid latent Dirichlet allocation model which forms the core of this research proposal. In Section \ref{section-climate} we outline how MuSTAS impacts climate change. \section{Multi-Source Topic Aggregation System}\label{section-MuSTAS} To help holding policy makers accountable, MuSTAS processes documents (e.g. speech transcripts, tweets, blog posts) from several publicly available sources into a compact report, highlighting the distribution of topics the candidate or party has been discussing during the given time period on the given platforms. \begin{figure}[h!] \centering \includegraphics[width=\columnwidth,trim={0 36 0 0},clip]{MuSTAS-v3.png} \vskip -0.1in \caption{Overview of MuSTAS. 1) Crawling and pre-processing data from Twitter API, Facebook API, blog posts, parliamentary transcripts, etc. produced by the given politician. 2) Database for storing the documents and modelling results. Each processed entry includes topic, person, party, timestamp, data type, and source URL, and document metadata. 3) Topic modelling over all document types using a hybrid latent Dirichlet allocation as described in Section \ref{section-ml}. 4) Users can access the results through a graphical user interface, which supports different analyses by topic, time, person, platform, and example documents for the given topic. } \label{fig:MuSTAS} \vskip -0.15in \end{figure} Through MuSTAS, the public and civil society will have access to infographics that provide answers to questions regarding candidates or groups of candidates, topics discussed, and mediums used, over different time periods (Figure \ref{fig:MuSTAS} step 4). The questions answered with MusTAS could be e.g. "Do parliamentary discussions address climate change?", "How much does the politician X talk about climate in contrast to economy?", "Does the political discourse differ between platforms meant to address the electorate (such as social media) and political spheres (parliamentary discussions)?", and "Does candidate X talk about different topics prior to the elections in comparison to their time in the government?". With answers to these questions voters have better insight what their candidate/party discuss in parliamentary sessions after being elected. The civil society organisations can assess how much each politician talks about climate in contrast to other topics, which enables efficient targeting of individuals that need convincing on the urgency of climate friendly policies. Machine learning methods are crucial for this analysis, as hundreds of politicians produce documents every day, and expensive human-conducted surveys are not made regularly. To enable the system to read and analyze the for-humans-intractable amount of data and update the analysis by doing online inference on daily basis, topic modelling has to be outsourced to a ML model. \section{Topic Modelling: Multi-Source Hybrid LDA} \label{section-ml} Topic modelling is a widely used approach to describe the content of text documents through a limited number of topics \cite{yi_comparative_2009}, and used previously also on isolated legislative speech \cite{glavas_computational_2019}. The topics are seen as latent variables defining a probability distribution for the vocabulary of words in the document. The probability distributions of topics are modelled with a probabilistic method such as latent Dirichlet allocation (LDA) \cite{blei_latent_2003}, which has been implemented in many different use cases \cite{heidenreich_media_2019, rehurek_software_2010, tong_text_2016, uys_leveraging_2008, yi_comparative_2009} to model topics that are present in a document. In order to build a holistic understanding which topics a politician discusses, one needs to gather data from many different media, see phase 1 of Figure \ref{fig:MuSTAS}. This poses a novel challenge, since methods which successfully model topics in tweets and other short documents, such as Biterm Topic Model \cite{chen_user_2015}, Supervised LDA \cite{jonsson_evaluation_2015, resnik_beyond_2015}, or LDA-U \cite{jonsson_evaluation_2015}, differ from the models designed for longer documents and large corpora \cite{rehurek_software_2010}. We propose a multi-source approach, where all documents are processed to paragraphs $p$ of similar length. For example, a tweet could equal to one paragraph while a speech might be split into several. Topic modelling is then performed on these paragraphs individually, and a document's topic distribution is attained by aggregating the distributions of its paragraphs. Different types of documents might radically vary in vocabulary and style. To mitigate this, we propose to use a hybrid LDA \cite{moody_mixing_2016} approach, where the easily interpretable LDA has been made more robust by utilizing word embeddings \cite{mikolov_distributed_2013} provided by transformer models such as BERT \cite{devlin_bert_2019} or RoBERTa \cite{liu_roberta_2019}. The recently observed performance of large transformer models \cite{brown_language_2020} suggests that the word-, document-, and topic embeddings applied in a hybrid LDA \cite{moody_mixing_2016} could be learned from a corpora of various types of documents. In climate change mitigation, hybrid LDA has been previously proposed for monitoring climate change technology transfer \cite{kulkarni_using_2020}. The topics are learned in unsupervised manner, and therefore depend on the available data. The number of topics, defined by the researcher before training, will affect how granular the found topics will be\footnote{For example, with 20 different topics all climate change related discussion could be part of e.g. two topics, while 200 topics will result much more granular topics and discussion on e.g. land usage or fossil fuels can be expected to belong to different topics.}. The suitable number of topics will be experimented during the research and documented in the findings. The topic model will be trained offline before made available in MuSTAS. This ensures that the topic modelling results are comparable over time. Later models trained with updated datasets can be released to MuSTAS alongside the original model. \subsection{Empirical Evaluation - Modelling the Topics of Finnish Politicians} \label{sub-finland} We will demonstrate the functionality of multi-source hybrid LDA as part of MuSTAS by implementing the system in the Finnish context. In the case of Finland, a major portion of public statements and discussions of politicians can be covered by the data sources provided in Table \ref{table-data}. All the sources are publicly available on the internet, so they can be programmatically gathered to the MusTAS database (Figure \ref{fig:MuSTAS}, step 1). \begin{table}[t] \caption{Example data sources} \label{table-data} \vskip 0.1in \begin{scriptsize} \centering \begin{tabular}{lll}\toprule Name & Document type & URL \\ \midrule \multirow{2}{2cm}{Finnish parliament database} & \multirow{3}{2.3cm}{MP's speeches, written questions, proposals, law initiatives etc.} & \href{https://www.eduskunta.fi/FI/search/Sivut/Vaskiresults.aspx}{www.eduskunta.fi/FI/search/...} \\\vspace{0.5cm}\\ Social media APIs & \multirow{2}{2.3cm}{Policy makers' social media posts} & e.g. \href{https://developer.twitter.com/en/docs/twitter-api}{developer.twitter.com/...} \vspace{0.5cm}\\ Blogs & Blog posts & e.g. \href{https://puheenvuoro.uusisuomi.fi/author/paavovayrynen/}{puheenvuoro.uusisuomi.fi/...} \\ \bottomrule \end{tabular} \end{scriptsize} \vskip -0.1cm \end{table} The documents related to each decision maker, are retrieved from each source and pre-processed to a common format required by the hybrid LDA. Since the majority of documents produced by Finnish politicians are in Finnish, the transformer used should be compatible with the language, for example FinBERT \citep{virtanen_multilingual_2019}. \section{Climate Impact} \label{section-climate} MuSTAS provides researchers, civil society, and the general public with an easily interpretable digest of topics which the policy makers have talked about. To reach the goals of the Paris Agreement and mitigate climate change, politicians need to implement a range of ambitious policies. Increased accountability of government officials has been shown to be crucial in preventing political mismanagement \citep{adsera2003you}. Because an accountable actor needs to provide information and justification for their decisions \citep{mees2019framework}, the degree of information (transparency) citizens have about their government's actions is one of two major hinges in accountability \citep{adsera2003you}. Currently, despite many democratic governments providing greater access to government proceedings, transparency is hindered by the sheer amount of data accessible. Media coverings of political developments are biased toward specific topics \citep{eady2019many}, actors \citep{snyder2010press,shor2015paper,vos2013vertical}, and private political interests \citep{statham1996television}. The proposed MuSTAS (Section \ref{section-MuSTAS}) overcomes these barriers by jointly analysing a wide range of publicly available data and presenting data analyses in accessible and dynamic form without representation- or political-bias. MuSTAS allows the public to monitor political speech across platforms by bringing a concise digest of politician's statements, easily accessible with links to the original documents. Therefore, MuSTAS is a tool to track rhetorical political commitments on climate change, equipping civil society and voters with the means to hold decision makers accountable and incentivize policy makers to follow through with legitimate policies. The proposed work implements MuSTAS in the Finnish context (Subsection \ref{sub-finland}). However, the flexible system allows a for a straight-forward implementation in other countries by simply providing basic information on the national politicians such as social media account IDs, blog URLs or links to speeches and law initiatives. This way MuSTAS can crawl and process the provided source-documents for topic modelling regardless of the country or other context of the politician. For the new context, and possibly language, a new topic model needs to be trained, but the data processing and visualisations of the topic digests can be done using the same code base. This paves way for implementing MuSTAS in other countries, providing data for accountability in all parliamentary democracies.
{'timestamp': '2021-07-12T02:21:20', 'yymm': '2010', 'arxiv_id': '2010.08346', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08346'}
arxiv
\section{Algorithm} \label{sec:algorithm} Our approach makes use of the polynomial encoding of temporal walks introduced by Thejaswi et al.~\cite{Thejaswi2020pattern}, building on the earlier work of Bj\"{o}rklund et al.~\cite{BjorklundKK2016} for static graphs. Because algebraic fingerprinting techniques are not well-known, we first provide some intuition behind our methods before diving into details. \subsection{Intuition} Algebraic fingerprinting methods have been successfully applied to pattern detection problems on graphs. On a high level, the approach works by encoding a problem instance $G$ as a multivariate polynomial where the variables in the polynomial correspond to entities of $G$ such as a vertex or an edge. The key idea is to design a polynomial encoding, which evaluates to a non-zero term if and only if the desired pattern is present in $G$. We can then evaluate the polynomial by substituting random values to its variables. Now, if one of the substitution evaluates to a non-zero term, it implies that the desired pattern is present in $G$. Since the substitutions are random, the approach can give false negatives. However, the resulting algorithms typically have one-sided error meaning false positives are not possible. Moreover, as is typical, the error probability can be made arbitrarily small (e.g., as unlikely as hardware failure) by repeating the substitutions. In our case we need to decide the existence of a restless path in a temporal graph~$G$. Following the approach presented above, we encode all the restless walks in $G$ using a multivariate polynomial where each monomial corresponds to a restless walk and variables in a monomial correspond to vertices and/or edges. Specifically, we design an encoding where a monomial is \textit{multilinear} (i.e., no variables in the monomial are repeated) if and only the corresponding restless \textit{walk} it encodes is a restless \textit{path}. As such, the problem of deciding the existence of a restless path is equivalent to the problem of deciding the existence of a multilinear monomial in the generated polynomial. The existence of a multilinear monomial in a polynomial, in turn, can be determined using {\em polynomial identity testing}, in particular, by evaluating random substitutions for the variables; if one of the substitution evaluates to a non-zero term then there exists at least one multilinear monomial in the polynomial. Importantly, {\em note that an explicit representation of the polynomial encoding can be exponentially large. However, in our approach we do not need to represent the polynomial explicitly, but we only need to evaluate random substitutions efficiently.} To lay foundation for our approach we begin our discussion with encoding walks in static graphs and continue to encode walks in temporal graphs. Finally, we extend the approach to encode restless walks in temporal graphs. \subsection{Monomial encoding of walks} \mpara{Static graphs.} We introduce a set of variables $\vec{x} = \{x_{v_1},\dots,x_{v_n}\}$ for vertices in $V=\{v_1,\dots,v_n\}$ and a set of variables $\vec{y} = \{y_{uv,\ell}: (u,v) \in E, \ell \in [k]\}$ such that $y_{uv,\ell}$ corresponds to an edge $(u,v) \in E$ that appears at position $\ell$ in a walk. Using these variables a walk $W = v_1 e_1 v_2 \dots e_{k-1}v_k$ can be encoded by the monomial \[ x_{v_1}\,\,y_{v_1v_2,1}\,\,x_{v_2}\, \dots\, y_{v_{k-1}v_k,k-1}\,\,x_{v_k}. \] The monomial encoding of walks in static graphs is illustrated in Figure~\ref{fig:encoding:walks}. It is easy to see that the encoding is multilinear, i.e., no variable in a monomial is repeated, if and only if the corresponding walk is a path. To encode a walk of length $k-1$, we need $k$ variables of $\mathbf{x}$ and $k-1$ variables of $\mathbf{y}$, for a total of $2k-1$ variables. \begin{figure} \begin{tabular}{c c} \input{tikz/tikz-polynomial-encoding-walk} & \input{tikz/tikz-polynomial-encoding-path} \\ $x_{v_1}\,y_{v_1v_2, 1}\, \textcolor{red}{x_{v_2}}\,y_{v_2v_3,2}\, x_{v_3}\,y_{v_3v_4,3}\, x_{v_4}\,y_{v_4v_2,4}\, \textcolor{red}{x_{v_2}}$ & $x_{v_1}\,y_{v_1v_2,1}\,x_{v_2}\, y_{v_2v_3,2}\,x_{v_3}$ \end{tabular} \caption{\label{fig:encoding:walks} A monomial encoding of a walk (left) and a path (right) in static graphs. Arrows indicate the direction of the walk. Variables highlighted in red are repeated if and only if a walk is not a path.} \end{figure} \mpara{Temporal graphs.} We introduce a set of variables $\vec{x} =\{x_{v_1},\dots,x_{v_n}\}$ for vertices $V=\{v_1,\dots,v_n\}$ and a set of variables $\vec{y} = \{y_{uv,\ell,j}: (u,v,j) \in E, \ell \in [k]\}$ such that $y_{uv,\ell,j}$ corresponds to an edge $(u,v,j) \in E$ that appears at position $\ell$ in a walk. Using these variables a temporal walk $W = v_1 e_1 v_2 \dots e_{k-1} v_k$ can be encoded using the monomial \[ x_{v_1}\,\,y_{v_1v_2,1,j_1}\,\, x_{v_2}\,\,y_{v_2v_3,2,j_2}\, \dots \, y_{v_{k-1}v_k,k-1,j_{k-1}}\,\,x_{v_k}. \] The polynomial encoding of temporal walks is illustrated in Figure~\ref{fig:encoding:tempwalks}. A monomial encoding of a temporal walk of length $k-1$ has $2 k-1$ variables. \begin{figure} \begin{tabular}{c c} \input{tikz/tikz-polynomial-encoding-tempwalk} & \input{tikz/tikz-polynomial-encoding-temppath} \\ $x_{v_1}\,y_{v_1v_2,1,j_1}\, \textcolor{red}{x_{v_2}}\,y_{v_2v_3,2,j_2}\, x_{v_3}\,y_{v_3v_4,3,j_3}\, x_{v_4}\,y_{v_4v_2,4,j_4}\, \textcolor{red}{x_{v_2}}$ & $x_{v_1}\,y_{v_1v_2,1,j_1}\,x_{v_2}\, y_{v_2v_3,2,j_2}\,x_{v_3}$ \end{tabular} \caption{\label{fig:encoding:tempwalks} A monomial encoding of a temporal walk (left) and a temporal path (right). Arrows indicate the direction of the walk. Variables highlighted in red are repeated if and only if a temporal walk is not a temporal path.} \end{figure} Again, observe that the encoding is multilinear if and only if the corresponding temporal walk is a temporal path. In fact, it can be shown that a temporal walk is a temporal path if and only if the corresponding monomial encoding is multilinear~\cite[Lemma~2]{Thejaswi2020pattern}. Likewise, the problem of deciding the existence of temporal path of length $k-1$ is equivalent to deciding the existence of a multilinear monomial of degree $2k-1$~\cite[Lemma~3]{Thejaswi2020pattern}. In other words, if we encode all the walks of length $k-1$ in a temporal graph using a polynomial where each monomial encodes a walk, then the problem of detecting the existence of a temporal path of length $k-1$ is equivalent to the problem of detecting existence of a multilinear monomial of degree $2k-1$ in the encoded polynomial. \subsection{Generating temporal walks} To generate a polynomial encoding of temporal walks, we turn to a dynamic-programming recursion. That is, we make use of polynomial encoding of temporal walks of length $\ell-2$ to generate the encoding of temporal walks of length $\ell-1$ recursively. Consider the example illustrated in Figure~\ref{fig:encoding:temppath:1}, where the vertex $u$ has incoming edges from vertices $\{v_1,v_2\}$ at timestamp $i$, i.e., $N_i(u)=\{v_1,v_2\}$. Let $\prepp{u}{\ell}{i}$ denote the polynomial encoding of all temporal walks of length $\ell-1$ ending at vertex $u$ at latest time $i$. Following our notation, $\prepp{v_1}{\ell-1}{i}$, $\prepp{v_2}{\ell-1}{i}$ represent the polynomial encoding of walks ending at vertices $v_1, v_2$, respectively, such that all walks have length $\ell -1$ and end at latest time $i$. From the definition of a temporal walk, it is clear that we can walk from vertices $v_1, v_2$ to vertex $u$ at time $i$ if we have reached $v_1$ and/or $v_2$ at latest time $i$. The polynomial encoding of walks of length $\ell-1$ ending at vertex $u$ at latest time $i$ can be written as \[ \prepp{u}{\ell}{i} = x_u \sum_{j \leq i} y_{v_1u,\ell-1,j}\,\prepp{v_1}{\ell-1}{j} + x_u \sum_{j \leq i} y_{v_2u,\ell-1,j}\,\prepp{v_2}{\ell-1}{j}. \] By generalizing the above intuition, a generating polynomial for temporal walks can be written as \[ \prepp{u}{1}{i} = x_u, \text{ for each } u \in V \text{ and } i \in [\tau], \text{ and} \] \begin{equation} \label{eq:encoding:tempwalk} \prepp{u}{\ell}{i} = x_u \sum_{v \in N_i(u)} \sum_{j \leq i} y_{vu,\ell-1,j}\,\prepp{v}{\ell-1}{j} \end{equation} for each $u \in V$, $\ell \in \{2,\dots,k\}$ and $i \in [\tau]$. \begin{figure} \input{tikz/tikz-generating-polynomial-temppath} \caption{\label{fig:encoding:temppath:1} Polynomial encoding of temporal walks.} \end{figure} An illustration of polynomial encoding of temporal walks is presented in Figure~\ref{fig:encoding:temppath:2}, in which we depict the polynomial encoding of temporal walks of length zero (a, b), length one (c, d) and length two (e, f). \begin{figure} \renewcommand{\arraystretch}{2.5} \begin{tabular}{c c} \input{tikz/tikz-generating-polynomial-temppath-11} & \input{tikz/tikz-generating-polynomial-temppath-12} \\ (a) $\ell=1, i=1$ & (b) $\ell =1, i = 2$\\ \input{tikz/tikz-generating-polynomial-temppath-21} & \input{tikz/tikz-generating-polynomial-temppath-22} \\ (c) $\ell=2, i=1$ & (d) $\ell =2, i = 2$\\ \input{tikz/tikz-generating-polynomial-temppath-31} & \input{tikz/tikz-generating-polynomial-temppath-32} \\ (e) $\ell=3, i=1$ & (f) $\ell =3, i = 2$\\ \end{tabular} \caption{\label{fig:encoding:temppath:2} An illustration of polynomial encoding of temporal walks of length zero (a,b), length one (c, d), and length two (e, f). Arrows denote direction of edges and numbers on edges denote edge timestamps. Observe that the monomial encoding corresponding to a walk that is not a path is not multilinear (highlighted in red).} \end{figure} Before continuing to introduce a generating function for restless walks let us present an overview of the algorithm. \subsection{Overview} To obtain our algorithm, we proceed by taking the following steps. First, we present a dynamic programming algorithm to encode restless walks as a polynomial and from this polynomial, show that detecting a multilinear monomial of degree $2\ell-1$ is equivalent to detecting a restless path of length~$\ell-1$, and vice versa. Then, we extend the approach to detecting restless paths with additional color constraints on the vertices. Finally, we use this algorithm to solve the problems described in Section~\ref{sec:problems}. \change{ In this work we use finite fields for evaluating polynomials, in particular we make use of Galois fields (\ensuremath{\text{GF}}\xspace) of characteristic $2$. An element of $\ensuremath{\text{GF}}\xspace(2^b)$ can be represented as a bit vector of length $b$. We can perform field operations such as addition and multiplication on these bit vectors in time $\ensuremath{\mathcal{O}}\xspace(b \log b)$~\cite{lin2016novel}. The polynomial $\prepp{u}{\ell}{i}$ on variables $\vec{x}=\left\{x_v: v \in V \right\}$, $\vec{y}=\left\{ y_{uv,\ell,ji}: (u,v,j) \in E, \ell \in [k] \right\}$ in Equation~(\ref{eq:encoding:tempwalk}) can be evaluated using a random assignment $\tilde{x}=\{\tilde{x}_v \in \ensuremath{\text{GF}}\xspace(2^b)\} : x_v \in \vec{x}\}$, $\tilde{y}=\left\{ \tilde{y}_{uv,\ell,j} \in \ensuremath{\text{GF}}\xspace(2^b): y_{uv,\ell,j} \in \vec{y} \right\}$. Now we can build an arithmetic circuit that represents an algorithm which evaluates the polynomial $\mathcal{P}_{u,\ell,i}$ for input $(\tilde{x}, \tilde{y})$ in time linear in the number of gates in the circuit. Most importantly, observe that the expanded expression of the polynomial $\prepp{u}{\ell}{i}$ can be exponentially large, however the arithmetic circuit evaluating $\prepp{u}{\ell}{i}$ can be reduced to size polynomial in number of gates by applying the associativity of addition and distributivity of multiplication over addition. } For detecting the existence of a multilinear monomial in the generated polynomial, the algorithm works by randomly substituting values $(\tilde{x},\tilde{y}) \in \ensuremath{\text{GF}}\xspace(2^b)$, for a suitable $b$, to variables in $\vec{x}=\left\{x_v: v \in V\right\}$ and $\vec{y}=\left\{y_{uv,\ell,j} :\allowbreak (u,v,j) \in E^\tau, \ell\in [k]\right\}$. Specifically, the parameter $b$ is the number of bits used to generate the field variables. Because multiplication between two field variables is defined as an {\tt XOR} operation, multiplication between two variables with the same value results in a zero term. That is, the monomials corresponding to walks that are not paths evaluate to a zero term, while the monomials corresponding to paths evaluate to a non-zero term. However, it is possible that an evaluation results in a zero term even though there is a multilinear monomial term corresponding to a path. To eliminate the effect of such false negatives we repeat the evaluation of the polynomial with $2^k$ random substitutions. The probability of a false negative then becomes ${2^{-b}}{(2k-1)}$, where $k-1$ is the length of the temporal walk. In practice, the false negative probability depends on the quality of the random number generator. It is important to note, however, that the false positive probability is zero. For full technical details, we refer the interested reader to Bj\"{o}rklund et al.~\cite{BjorklundKK2016} and Cygan et al.~\cite[Chapter~10]{cygan2015parameterized}. \subsection{Generating restless walks} In this subsection we extend the dynamic-programming recursion to generate a polynomial encoding of restless walks of length $\ell-1$ using encoding of restless walks of length $\ell-2$. An example is illustrated in Figure~\ref{fig:generating:1}, in which we depict a vertex $u$ with incoming neighbors $N_i(u)=\{v_1,v_2\}$. From the definition of a restless walk, it is clear that we can continue the walk from vertices $v_1, v_2$ to vertex $u$ at time $i$ only if we had reached $v_1$ or $v_2$ no earlier than time $i-\delta(v_1)$ and $i-\delta(v_2)$, respectively. Let $\prep{u}{\ell}{i}$ denote the encoding of all restless walks of length $\ell-1$ ending at vertex $u$ at time $i$. \begin{figure}[t] \centering \input{tikz/tikz-generating-polynomial-restlesspath} \caption{\label{fig:generating:1} An illustration of generating restless walks.} \end{figure} We generate restless walks of length $\ell-1$ that end at vertex~$u$ at time $i$ using restless walks of length~$\ell-2$ by having \[ \begin{split} \prep{u}{\ell}{i} =\; & x_u \sum_{\substack{j \in \{0,\dots,\delta(v_1)\}\\i-j>0}} y_{uv_1,\ell-1,i-j}\,\prep{v_1}{\ell-1}{i-j} \;+ \\ & x_u \sum_{\substack{j \in \{0,\dots,\delta(v_2)\}\\i-j>0}} y_{uv_2,\ell-1,i-j}\,\prep{v_2}{\ell-1}{i-j}. \end{split} \] Generalizing from the previous example, the dynamic-programming recursion is written as \[ \prep{u}{1}{i} = x_u, \text{ for each } u \in V \text{ and } i \in [\tau], \text{ and} \] \begin{equation} \label{eq:poly-enc:1} \prep{u}{\ell}{i} = x_u \sum_{v \in N_i(u)} \sum_{\substack{j \in \{0,\dots,\delta(v)\}\\ i-j>0}} y_{uv,\ell-1,i-j}\,\prep{v}{\ell-1}{i-j}, \end{equation} for each $u \in V$, $\ell \in \{2,\dots,k\}$ and $i \in [\tau]$. The following result is fundamental to our approach. \begin{lemma} \label{lemma:algo:1} The polynomial encoding $\prep{u}{\ell}{i}$ presented in Equation~(\ref{eq:poly-enc:1}) contains a multilinear monomial of degree $2\ell-1$ if and only if there exists a restless temporal path of length $\ell-1$ ending at vertex $u$ reaching at time $i$. \end{lemma} \begin{proof} From Equation~(\ref{eq:poly-enc:1}) it is clear that if the $y$-variables are not repeated in a monomial, the walk ends at vertex $u$ and has length $\ell-1$. Let us assume that the polynomial has a multilinear monomial with degree $2\ell-1$. It is easy to see that the variables of this monomial are different, so the walk represented by the monomial is a path. From the construction it is also clear that we only continue the walk if we have reached the neighbor $v$ at time at least $i-\delta(v)$. Conversely, let us assume that there exists a restless path of length $\ell-1$ that ends at vertex $u$ at latest time~$i$. Since the length of the path is $\ell-1$, there are $\ell$ unique $x$-terms and $\ell-1$ unique $y$-terms, and thus, there exists a multilinear monomial of degree $2\ell-1$. \end{proof} The next part of the problem is to detect a multilinear monomial in the polynomial in Equation~(\ref{eq:poly-enc:1}) representing the restless walks. There is already established theory related to this problem \cite{BjorklundKK2016,koutis-icalp08,koutis-williams-icalp09}. In particular, it is known that by substituting $2^\ell$ random values for the variables in $x$ and $y$, and evaluating them, if one of the evaluation results in a non-zero term, it implies that there exists at least one multilinear monomial of degree $2\ell-1$. For each $u \in V$ and $j \in [\ell]$ we introduce a new variable $z_{u, j}$. The vector of all variables of $z_{u,j}$ is denoted as $\mathbf{z}$ and the vector of all variables of $y$ is denoted as $\mathbf{y}$. We write $z_{u}^L = \sum_{j \in L} z_{u,j}$, for $u \in V$, $L \subseteq [\ell]$ and $\mathbf{z}^L=\{z^{L}_{u}: u \in V\}$ for $L \subseteq [\ell]$. The values of the variables $z_{u,j}$ are assigned uniformly at random from $\ensuremath{\text{GF}}\xspace(2^b)$. For simplicity we write $V = \{u_1, \dots,u_n\}$. \begin{lemma}[Multilinear sieving \cite{Bjorklund2014}] \label{lemma:multilinear-sieving} The polynomial \begin{equation} \label{eq:multilinear:1} \qrep{u}{\ell}{i} = \sum_{L \subseteq [\ell]} \chi_{u,\ell,i}(z_{u_1}^L,\dots,z_{u_n}^L, \vec{y}) \end{equation} is not identically zero if and only if $\prep{u}{\ell}{i}$ contain a multilinear monomial of degree $2\ell-1$. \end{lemma} \iffalse We write $\chi_{\ell,i}(\mathbf{x}, \mathbf{y}) = \sum_{u \in V} \prep{u}{\ell}{i}$ to represent all walks of length $\ell-1$ \textcolor{red}{reaching at time $i$}; the corresponding evaluation polynomial is represented as $\zeta_{\ell, i}(\mathbf{z,y}) = \sum_{u \in V} \qrep{u}{\ell}{i}$. \note{Reaching to where? } \fi \begin{lemma} \label{lemma:multilinear} Evaluating the polynomial in Equation~(\ref{eq:multilinear:1}) can be done in time $\ensuremath{\mathcal{O}}\xspace(2^\ell \ell m \Delta)$ and space $\ensuremath{\mathcal{O}}\xspace(n\tau)$. \end{lemma} \begin{proof} Recall that $\Delta = \max_{v \in V} \delta(v)$, $m_i$ is the number of edges at $i \in [\tau]$, and $n$ is the number of vertices. Computing $\prep{u}{j}{i}$ for all $u \in V$ requires $(\Delta+1) m_i$ multiplications and additions. We repeat this for all $i \in [\tau]$ and $j \in [\ell]$, which requires $\ensuremath{\mathcal{O}}\xspace(\ell m \Delta)$ multiplications and additions. Finally we evaluate the polynomial $\qrep{u}{\ell}{i}$ for all $u \in V$ using $2^\ell$ random substitution of variables in $\mathbf{z}^L=\{z_{u_1}^L,\dots,z_{u_n}^L\}$, for each $L \subseteq [\ell]$, which takes time $\ensuremath{\mathcal{O}}\xspace(2^\ell \ell m \Delta)$. So the runtime is $\ensuremath{\mathcal{O}}\xspace(2^\ell m \Delta)$. To store $\prep{u}{\ell}{i}$, for all $v \in V$, $i \in [\tau]$, requires at most $\ensuremath{\mathcal{O}}\xspace(n \tau)$ space. The dynamic-programming scheme iterates over $j \in [\ell]$ for computing $\prepp{u}{\ell+1}{i}$, which requires the values of $\prepp{u}{\ell}{i}$, for all $u \in V$, $i \in [\tau]$. It follows that the space requirement is $\ensuremath{\mathcal{O}}\xspace(n \tau)$. \end{proof} In the next subsection, we introduce color constraints for the vertices in the restless path. More precisely, given a vertex-colored temporal graph $G=(V,E)$ with a coloring function $c:V \rightarrow C$, where $C$ is a set of colors, and a multiset $M$ of colors, we consider the problem of deciding the existence of a restless path such that the vertex colors of the path agree with the multiset of colors in $M$. This generalization of the restless path problem with color constraints will be used to solve restless reachability problems in the later sections. \subsection{Introducing vertex-color constraints} Given a multiset of colors $M$, we extend the multilinear sieving technique to detect the existence of a multilinear monomial, such that colors corresponding to the $x$-variables agree with the colors in multiset~$M$. Recall our earlier definition where $\mu(s)$ denotes the number of occurrences of color $s$ in a multiset $M$. Furthermore, for each $s \in C$, let $S_s$ denote the set of $\mu(s)$ \emph{shades} of the color $s$, with $S_s \cap S_{s'} = \emptyset$ for all $s \neq s'$. In other words, for each color $s \in C$ we create $\mu(s)$ shades, so that any two distinct colors have different shades. As an example, for the color multiset $M=\{1,1,2\}$ we have $S_1=\{1_1,1_2\}$ and $S_2=\{2_1\}$, so that $S_1 \cap S_2 = \emptyset$. For each $u \in V$ and $d \in S_{c(u)}$ we introduce a new variable $\gamma_{u, d}$. For each $d \in \cup_{s \in C} S_s$ and each label $j \in [\ell]$ we introduce a new variable $\omega_{j,d}$. The values of variables $\gamma_{u,d}$ and $\omega_{d,j}$ are drawn uniformly at random from the Galois field $\ensuremath{\text{GF}}\xspace(2^b)$. We write \begin{equation} \label{eq:multilinear:3} z_{u,j} = \sum_{d \in S_{c(u)}} \gamma_{u,d} \omega_{d,j}, \text{\: and \:} z_u^L = \sum_{j \in L} z_{u,j}, \end{equation} for $L \subseteq [\ell]$, $u \in V$. The following lemma extends Lemma~\ref{lemma:multilinear-sieving} in the case of vertex-color constraints. \begin{lemma}[Constrained multilinear sieving~\cite{BjorklundKK2016}] \label{lemma:constraint-multilinear-sieving} The polynomial $\prep{u}{\ell}{i}$ contain a multilinear monomial of degree $2\ell-1$ and it is properly colored if and only if the polynomial \begin{equation} \label{eq:multilinear:2} \qrepw{u}{\ell}{i} = \sum_{L \subseteq [l]} \chi_{u,\ell,i}(z_{u_1}^L,\dots,z_{u_n}^L,\vec{y}) \end{equation} is not identically zero. % \end{lemma} From Lemma~\ref{lemma:constraint-multilinear-sieving}, we can determine the existence of a multilinear monomial in $\qrepw{u}{\ell}{i}$, by making $2^\ell$ random substitutions of the new variables $\mathbf{z}$ in Equation~\ref{eq:multilinear:2}. As detailed in Bj{\"o}rklund et al.~\cite{BjorklundKK2016} these substitutions can be random for a low-degree polynomial that is not identically zero with only few roots. If one evaluates the polynomial at a random point, one is likely to witness that it is not identically zero~\cite{Schwartz1980,zippel}. This gives rise to a randomized algorithm with a false negative probability of $2^{-b}(2\ell-1)$, where the arithmetic is over the Galois field $\ensuremath{\text{GF}}\xspace(2^b)$. Here, again, $b$ is the number of bits used to generate the random values. We make use of this result for designing our algorithms. \begin{lemma} \label{lemma:multilinear:2} Evaluating the polynomial in Equation~(\ref{eq:multilinear:2}) can be done in time $\ensuremath{\mathcal{O}}\xspace(2^\ell \ell m \Delta)$ and space $\ensuremath{\mathcal{O}}\xspace(n \tau)$. \end{lemma} The proof of Lemma~\ref{lemma:multilinear:2} is similar to the one of Lemma~\ref{lemma:multilinear}. From Lemma~\ref{lemma:constraint-multilinear-sieving} we obtain an algorithm to detect the existence of a restless path ending at vertex $u \in V$ at time $i$ and the vertex colors of the restless path agree with the colors in multiset $M$. \subsection{A fine-grained decision oracle} \label{sec:algo:finegrained} \cnote[Suhas]{Check this section.} In this subsection we present a \emph{fine-grained} evaluation scheme to evaluate the polynomial in Equation~(\ref{eq:multilinear:2}). \mpara{Intuition.} Consider the graph illustrated in Figure~\ref{fig:fine-grained:1}, with vertex set $V=\{v_1,\dots,v_5\}$ with resting time $\delta(v_1) = \dots = \delta(v_5) = 2$, i.e., we can wait at most~$2$ time steps at any vertex. In order to decide whether there exists a restless path of length $3$ (i.e., $\ell=4$) in the graph, we need to evaluate the polynomial $\chi(\vec{x},\vec{y})=\sum_{u \in \{v_1,\dots,v_5\}} \sum_{i \in [\tau]} \prep{u}{4}{i}$. However, to decide if there exists a restless path of length $3$ ending at vertex $v_5$ it is sufficient to evaluate the polynomial $\sum_{i \in [\tau]} \prep{v_5}{4}{i}$. Furthermore, to decide if there exists a restless path of length $3$ ending at vertex $v_5$ at time $5$, we can restrict the evaluation to the polynomial $\prep{v_5}{4}{5}$. Similarly, it suffices to evaluate the polynomial $\prep{u}{\ell}{i}$ to determine whether there exists a path of length $\ell-1$ ending at vertex $u$ at time $i$. \begin{figure} \input{tikz/tikz-finegrained-evaluation} \caption{\label{fig:fine-grained:1} An example to illustrate the fine-grained evaluation scheme. The resting time of vertices is $\delta(v_1) = \dots = \delta(v_5) = 2$. A restless path of length $3$ (i.e, $\ell=4$) from vertex $v_1$ to vertex $v_5$ is highlighted in bold.} \end{figure} \mpara{Fine-grained decision oracle.} Let us generalize the fine-grained evaluation scheme to any temporal graph using the intuition presented. Instead of evaluating a single polynomial $\chi(\mathbf{x},\mathbf{y}) = \sum_{u \in V} \sum_{\ell \in [k]} \sum_{i \in[\tau]} \prep{u}{\ell}{i}$, we work with a set of $n \tau$ polynomials $\left\{\prep{u}{\ell}{i}: u \in V, i \in [\tau]\right\}$ and evaluate each $\prep{u}{\ell}{i}$ independently. Observe carefully that our generating function in Equation~(\ref{eq:poly-enc:1}) generates a polynomial encoding of all restless walks $\prep{u}{\ell}{i}$ for each $u \in V$ and $i \in [\tau]$ independently for a fixed $\ell$. If the corresponding evaluation polynomial $\qrepw{u}{\ell}{i}$ evaluates to a non-zero term, it implies that there exists a restless path of length $\ell-1$ ending at vertex $u$ at time $i$ and the vertices in the path agree with the multiset of colors in $M$. Using this fine-grained evaluation scheme, we obtain a set of timestamps $R_u = \{i : \qrepw{u}{\ell}{i} \neq 0 \text{ for all } i \in [\tau]\}$ of restless paths ending at vertex $u \in V$ and satisfying the color constraints in $M$. The pseudocode is presented in Algorithm~\ref{algo:1}. The term \emph{fine-grained oracle} is used to differentiate it from a decision oracle, which only reports the existence of a restless path with a {\small YES}/{\small NO} answer. Our fine-grained decision oracle reports more insightful details, for instance it can answer if there exists a restless path of length $\ell-1$ ending at vertex $u \in V$ at time $i \in [\tau]$ satisfying the color constraints specified in $M$ with a {\small YES}/{\small NO} answer. A single run of the fine-grained oracle is sufficient to obtain the set of vertices $D \subseteq V$ such that there exists a restless path of length $\ell-1$ ending at each $u \in D$. Additionally, we can obtain the set of reachable timestamps $R_u=\{i : R_{u,i}=1, i \in [\tau]\}$ for each $u \in D$ using a single query to the fine-grained oracle. This re-design of the polynomial evaluation scheme improves the runtime for solving the temporal path problems described in previous work~\cite{Thejaswi2020pattern,thejaswi2020finding}, where the authors search for a temporal path that contains colors specified in the query. That is, by replacing their decision oracle with our fine-grained decision oracle, we reduce the number of queries by a factor of $\log \tau$. This, in turn, reduces the total runtime of their solution for detecting an optimal solution from $\ensuremath{\mathcal{O}}\xspace(2^\ell \ell (n\tau + m) \log \tau)$ to $\ensuremath{\mathcal{O}}\xspace(2^\ell \ell (n\tau + m))$. Even though the theoretical improvement is modest, it is important to note that for large values of $\ell$ a single run of the decision oracle can take hours to complete, so the practical improvement is significant (for precise results, see Section~\ref{sec:experiments} and Table~\ref{table:exp:realworld:2}, as well as previous work~\cite{KaskiLT2018}). \begin{algorithm}[t] \DontPrintSemicolon \caption{\sc FineGrainedOracle($G=(V,E), c, k, M$)} \label{algo:1} \KwIn{$G=(V,E)$, input graph \\ \Indp \Indp $c$, coloring function\\ $k$, length of path\\ $M$, multiset of colors} \KwOut{$R$, reachability time\\ \Indp \Indp $D$, set of reachable vertices} \For{$L \subseteq [k]$}{ $\mathbf{z}^L \gets \textsc{\small Get-z-assignment}(c, M, L)$ \tcp*{Eq.\,(\ref{eq:multilinear:3})} \For{$u \in V, i \in \tau$} { $\qrepw{u}{1}{i} \gets z_{u}^{L}$ } } \For{$\ell \in \{2,\dots,k\}$}{ \For{$ u \in V, i \in [\tau]$} { $\qrepw{u}{\ell}{i} \gets 0$\\ \For{$L \subseteq [k]$}{ $\mathbf{z}^L \gets \textsc{\small Get-z-assignment}(c, M, L)$ \tcp*{Eq.\,(\ref{eq:multilinear:3})} $\qrepw{u}{\ell}{i} \gets \qrepw{u}{\ell}{i} \oplus \chi_{u,\ell,i}(\mathbf{z}^L,\vec{y})$ \tcp*{Eq.\,(\ref{eq:multilinear:2})} } } } $D \gets \emptyset$, $R \gets \{R_{u,i} \gets 0: u \in V, i \in [\tau]\}$\\ \For{$u \in V, i \in [\tau]$} { \If{$\qrepw{u}{k}{i} \neq 0$}{ $R_{u,i} \gets 1$\\ \If{$u \notin D$}{ $D \gets D \cup \{u\}$ } } } \Return $R, D$ \end{algorithm} Let us then turn to our algorithmic results. \begin{theorem} \label{theorem:algo:restlessmotifreach} There exists a randomized algorithm for solving \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace problem in time $\ensuremath{\mathcal{O}}\xspace(2^k k m \Delta)$ and space $\ensuremath{\mathcal{O}}\xspace(n \tau)$. \end{theorem} \begin{proof} Given an instance $(G,c,k,M,s)$ of the \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace problem we build a graph $G'=(V',E')$ such that $V=V \cup \{s'\}$, $E'=E \cup \{(s',s,i): (s,u,i) \in E\}$, $c'(u) = c(u)$ for all $u \in V$, $c'(s')=k+1$, $M'=M \cup \{c'(s')\}$ and query the {\sc Fine\-Grained\-Oracle}\xspace with instance $(G',c',k+1,M')$. The construction is depicted in Figure~\ref{fig:algo:krestlessmotifreach}. In the instance $(G',c',k+1,M')$, the origin of the graph is enforced by introducing an additional vertex $s'$ adjacent to $s$. Since $s'$ is assigned a unique color, if there is a resting path agreeing with $M'$, then the path must originate from $s'$ and pass through $s$. If there exists a restless path originating from $s'$ and ending at $u \in V \setminus \{s, s'\}$ such that the vertex colors of the path agree with $M'$, then we have a restless path originating from $s$ and ending at $u$ such that the vertex colors of the path agree with $M$. As the graph $G'$ will have at most $2m$ edges and $n+1$ vertices, we have obtained an algorithm for solving \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace using $\ensuremath{\mathcal{O}}\xspace(2^k k m \Delta)$ time and $\ensuremath{\mathcal{O}}\xspace(n \tau)$ space. \end{proof} \begin{figure} \tikzset{every picture/.style={scale=0.9}} \setlength{\tabcolsep}{30pt} \begin{tabular}{c c} \input{tikz/tikz-k-restless-motif-reach-1} & \input{tikz/tikz-k-restless-motif-reach-2} \end{tabular} \caption{\label{fig:algo:krestlessmotifreach} An illustration of graph construction to solve the \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace problem. An instance of the \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace problem with a multiset of colors (left) and the transformation of the graph and the multiset (right). For illustrative purpose, we denote the vertices with color \underline{r}ed, \underline{b}lack and \underline{g}reen using diamond, circular and square shapes, respectively.} \end{figure} Next, we present our algorithm for \ensuremath{k \text{\sc -Restless\-Reach}}\xspace obtained by transforming it to an instance of \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace. More precisely, the algorithm works by constructing a vertex-colored instance that encodes the source, whereas a multiset of colors encodes the path length. We first present the solution for \ensuremath{k \text{\sc -Restless\-Reach}}\xspace with the solution to {\sc Restless\-Reach}\xspace following as a special case. \begin{theorem} \label{theorem:algo:krestlessreach} There exists a randomized algorithm for solving the \ensuremath{k \text{\sc -Restless\-Reach}}\xspace problem in time $\ensuremath{\mathcal{O}}\xspace(2^k k m \Delta)$ and space $\ensuremath{\mathcal{O}}\xspace(n \tau)$. \end{theorem} \begin{proof} Given an instance $(G,s,k)$ of the \ensuremath{k \text{\sc -Restless\-Reach}}\xspace problem, we introduce a coloring function $c:V \rightarrow \{1,2\}$ such that $c(s) = 2$ and $c(v) = 1$ for all $v \in V \setminus \{s\}$. We obtain a graph $G'=(V, E \setminus \{(u,v,i) \in E : v = s\})$ by removing all incoming edges to $s$ in $G$, and by setting the multiset $M=\{1^{k-1}\} \cup \{2\}$. We query the {\sc Fine\-Grained\-Oracle}\xspace with instance $(G', c, k , M)$. The transformation is illustrated in Figure~\ref{fig:algo:krestlessreach}. In the instance $(G', c, k, M)$, the origin of the restless path is enforced by removing all incoming edges to $s$ and coloring $s$ with a unique color. If we have a restless path ending at $u \in V \setminus \{s\}$ and agreeing with multiset $M$, it implies that the temporal path originates from $s$ and ends at $u$. The graph $G'$ has $n+1$ vertices and $m$ edges, so we have a $\ensuremath{\mathcal{O}}\xspace(2^k k m \Delta)$ time and $\ensuremath{\mathcal{O}}\xspace(n \tau)$ space algorithm for solving \ensuremath{k \text{\sc -Restless\-Reach}}\xspace. \end{proof} \begin{figure} \tikzset{every picture/.style={scale=0.9}} \setlength{\tabcolsep}{30pt} \begin{tabular}{c c} \input{tikz/tikz-k-restless-reach-1} & \input{tikz/tikz-k-restless-reach-2} \end{tabular} \caption{\label{fig:algo:krestlessreach} The transformation of the \ensuremath{k \text{\sc -Restless\-Reach}}\xspace problem instance (left) to a \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace problem instance (right). For illustrative purposes we denote vertices with color \underline{r}ed and \underline{b}lack using diamond and circular shapes, respectively.} \end{figure} \begin{algorithm}[t] \caption{\sc RestlessReach($G=(V,E), s$)} \label{algo:restlessreach} \KwIn{$G=(V,E)$, input graph\\ \Indp \Indp $s$, source vertex} \KwOut{$R'$, reachability time\\ \Indp \Indp $D'$, set of reachable vertices} $n \gets |V|$\\ \For{$u \in (V \setminus \{s\})$} { $c(u) \gets 1$ } $c(s) \gets 2$\\ $G' \gets (V, E \setminus \{(u,s,i) \in E\})$\\ $D' \gets \emptyset,$ $R' \gets \{R'_{u,i} \gets 0: u \in V, i \in [\tau]\}$\\ \For{$k \in \{2,\dots,n-1\}$} { $M \gets \{1^{k-1}\} \cup \{2\}$\\ $R, D \gets \textsc{FineGrainedOracle}(G', c, k, M)$\\ \For{$u \in V, i \in [\tau]$}{ \If{$R_{u,i} = 1$} { $R'_{u,i} \gets 1$\\ \If{$u \notin D'$} { $D' = D' \cup \{u\}$ } } } } \Return{$R',D'$} \end{algorithm} \begin{theorem} \label{theorem:algo:restlessreach} There exists a randomized algorithm for the {\sc Restless\-Reach}\xspace problem in time $\ensuremath{\mathcal{O}}\xspace(2^n n m \Delta)$ and space $\ensuremath{\mathcal{O}}\xspace(n \tau)$. \end{theorem} \begin{proof} For solving {\sc Restless\-Reach}\xspace, the construction is similar to Theorem~\ref{theorem:algo:krestlessreach}. However, we need to make $n-2$ calls to the {\sc Fine\-Grained\-Oracle}\xspace assuming the maximum length of the restless path is $n-1$. Finally, we obtain a set $R' = \{ R'_{u,i}: u \in V, i \in [\tau]\}$ such that $R'_{u,i} = 1$ if there exists a restless path from $s$ to $u$ ending at time $i$ with length at most $n-1$, and $R'_{u,i} = 0$, otherwise. The pseudocode is available in Algorithm~\ref{algo:restlessreach}. In total, we make $n-2$ {\sc Fine\-Grained\-Oracle}\xspace calls for each $k \in \{2,\dots,n-1\}$. Each run of the oracle takes $\ensuremath{\mathcal{O}}\xspace(2^k k m\Delta)$ time. To summarize, the runtime of the algorithm is ${\sum_{k=2}^{n-1} 2^k k m\Delta}$, which is $\ensuremath{\mathcal{O}}\xspace(2^n n\allowbreak m\Delta )$. The space complexity is $\ensuremath{\mathcal{O}}\xspace(n\tau)$, completing the proof. \end{proof} \subsection{Discussion} \label{sec:algo:discussion} Consider the following variant of the restless reachability problem that we call at-most-$k$-restless reachability problem (\ensuremath{\textit{atm-} k \text{\sc -Restless\-Reach}}\xspace). Given a temporal graph and a source vertex we need to find a set of vertices which are reachable from source via a restless path such that the length of the path is at most $k-1$. From Theorem~\ref{theorem:algo:restlessreach}, we have a randomized algorithm for solving \ensuremath{\textit{atm-} k \text{\sc -Restless\-Reach}}\xspace in time $\ensuremath{\mathcal{O}}\xspace(2^k k m\Delta)$ and space $\ensuremath{\mathcal{O}}\xspace(n \tau)$. Also note that we can use the algorithms for \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace, \ensuremath{k \text{\sc -Restless\-Reach}}\xspace and {\sc Restless\-Reach}\xspace as we can solve the \ensuremath{k\text{\sc-Restless\-Motif}}\xspace, \ensuremath{k \text{\sc-Restless\-Path}}\xspace and \ensuremath{\text{\sc Restless\-Path}}\xspace problems, respectively. A general variant of the {\sc Restless\-Reach}\xspace problem with a set of sources $S \subseteq V$ can be reduced to the {\sc Restless\-Reach}\xspace problem with a single source by introducing an additional vertex $s'$ and connecting all the sources $s \in S$ to $s'$ with a temporal edge. More precisely, given a graph $G=(V,E)$ and set of sources $S \subseteq V$, we construct a graph $G'=(V',E')$ with $V' = V \cup \{s'\}$ and $E'=E \cup \left\{(s',s,i)\mid s\in S \text{~and~} (s,u,i) \in E\right\}$. Solving the {\sc Restless\-Reach}\xspace problem on the graph instance $G'$ with source $s'$ is equivalent to solving the {\sc Restless\-Reach}\xspace problem with set of sources~$S$. Additionally, finding the restless path that minimizes the length (shortest path), minimizes the arrival time (fastest path), or minimizes the total waiting time (foremost path) can be computed using the output $\left\{R'_u: u \in V\right\}$ for each $\ell \in \{2,\dots,k\}$ from the fine-grained oracle. However, enabling such computation requires $\ensuremath{\mathcal{O}}\xspace(n \tau k)$ space. \subsection{Extracting an optimal solution using $k$ queries} \label{sec:algo:extraction} In this subsection, we present an algorithm for extracting an optimal solution for \ensuremath{k\text{\sc-Restless\-Motif}}\xspace and \ensuremath{k \text{\sc-Restless\-Path}}\xspace using $k$ queries to the {\sc Fine\-Grained\-Oracle}\xspace. By optimal we mean that the maximum timestamp in the restless path is minimized. Our {\sc Fine\-Grained\-Oracle}\xspace reports the existence of a restless path from a given source to a destination at discrete timestamps with a {\small YES}/{\small NO} answer. However, in many cases we also require an explicit solution, i.e., a restless path which actually witnesses the fact. We present two approaches to extracting an optimal solution. Our first approach makes use of self-reducibility of decision oracles and temporal {\small DFS}, based on the previous work of Bj\"{o}rklund et al.~\cite{BjorklundKK-esa2014} and Thejaswi et al.~\cite{thejaswi2020finding}. Our second approach makes use of the fine-grained oracle. For using self-reducibility, we implement a naive version of the multilinear sieve which only reports a {\small YES}/{\small NO} answer without the fine-grained capabilities, that is, the algorithm does not report the set of vertices and the timestamps at which the vertices are reachable from a given source via a restless path. We summarize our results in Table~\ref{table:summary:1}. \spara{Using self-reducibility and temporal {\small DFS}.} The approach works in three steps: First, we obtain the minimum (optimal) timestamp $t \in [\tau]$ for which there exists a feasible solution. For this, we construct the polynomial encoding of restless walks of length $k-1$ which end at time at most $t' \in [\tau]$ and query the decision oracle for the existence of a solution. Using binary search on the range $[\tau]$, we use at most $\log \tau$ queries to obtain the optimal timestamp. Next, we extract a $k$-vertex temporal subgraph that contains a restless temporal path. By recursively dividing the graph in to two halves we can obtain the desired subgraph using $\ensuremath{\mathcal{O}}\xspace(k \log n)$ queries to the decision oracle in expectation~\cite{BjorklundKK-esa2014}. Finally, we extract the restless path by performing a temporal {\small DFS} from a given source in the $k$-vertex subgraph. Even though the worst case complexity of the temporal {\small DFS} is $\ensuremath{\mathcal{O}}\xspace(k!)$, we demonstrate that the approach is practical. For technical details of self-reducibility of decision oracles, we refer the interested reader to Bjorklund et al.~\cite{BjorklundKK-esa2014}. In summary, the overall complexity of extracting an optimal solution using self-reducibility and temporal {\small DFS} is $\ensuremath{\mathcal{O}}\xspace((2^k k^2 m \Delta \log n \log \tau) + k!)$. \spara{Using fine-grained oracle.} As a second approach, extracting a solution can also be done with $k$ queries to the fine-grained oracle. Let us present the high-level idea behind fine-grained extraction. Consider a temporal graph presented in Figure~\ref{fig:finegrained-extraction} with vertex set $V=\{v_1,\dots,v_6\}$ with resting times $\delta(v_1)=\dots=\delta(v_6)=2$. In this example we want to extract a restless path of length $3$ from vertex $v_1$ to vertex $v_6$, if such a restless path exists. For illustrative purposes, we use colors \underline{b}lack and \underline{r}ed and have the multiset of colors $M=\{r,b,b,b\}$. For the first iteration it suffices to verify if $\qrepw{v_6}{4}{i}$ evaluates to a non-zero term for each $i \in [\tau]$. Since there exists a restless path of length $3$ ending at vertex $v_6$ at time $5$ agreeing with the colors in $M$, the corresponding evaluation polynomial $\qrepw{v_6}{4}{5}$ is non-zero. For the second iteration, delete vertex $v_6$ from the graph and remove a $b$ from $M$ leaving us with $M = \{ r,b,b \}$. Now check if there exists a restless path of length $2$ ending at any of the neighbors of $v_6$, i.e., $N_5(v_6) = \{v_3, v_5\}$ at any of the timestamps $i \in \{3,4,5\}$. This can be done by verifying if the polynomials $\qrepw{v_3}{2}{i}, \qrepw{v_5}{2}{i}$ evaluate to a non-zero term for timestamps $i \in \{3,4,5\}$. In our case, $\qrepw{v_5}{2}{3}$ evaluates to a non-zero term, which implies that there exists a restless path from $v_1$ to $v_3$ ending at timestamp $3$ agreeing with the colors in $M'$, so we add the edge $(v_5,v_6,5)$ to the solution. We can recursively repeat the second iteration until we reach the vertex $v_1$ to obtain a restless path from $v_1$ to $v_5$. \begin{figure} \tikzset{every picture/.style={scale=0.9}} \begin{tabular}{c c} \input{tikz/tikz-finegrained-extraction-1} & \input{tikz/tikz-finegrained-extraction-2} \\ iteration-$1$ & iteration-$2$ \end{tabular} \caption{\label{fig:finegrained-extraction} Extracting a restless path using the fine-grained decision oracle. On iteration one (left), a \ensuremath{k \text{\sc-Restless\-Path}}\xspace instance with a multiset of colors $M$ and a restless path of length $3$ from vertex $v_1$ to vertex $v_6$ highlighted in bold. On iteration two (right), a \ensuremath{k \text{\sc-Restless\-Path}}\xspace instance with a multiset of colors $M$ and a restless path of length $2$ from vertex $v_1$ to vertex $v_5$ highlighted in bold.} \end{figure} A generalization of the approach is described as follows: Let $(G,c,M,k,s,d,\tau)$ be an instance of the \ensuremath{k\text{\sc-Restless\-Motif}}\xspace problem. We build an instance $(G^\ell,c',M^\ell,\ell,s',\tau^\ell)$ of the \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace problem for each $\ell \in \{k+1,k,\dots,2\}$. % For the first iteration, where $\ell=k+1$, the graph $G^\ell$ is constructed as described in Theorem~\ref{theorem:algo:restlessmotifreach} to obtain a new source vertex $s'$ and a coloring function $c'$, $M^\ell=M \cup c'(s')$, and $\tau^\ell = \tau$. The graph construction of the \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace problem for $\ell=k+1$ is illustrated in Figure~\ref{fig:algo:finegrained-extraction:2}. We apply the algorithm from Theorem~\ref{theorem:algo:restlessmotifreach} to obtain~$R^\ell$ and~$D^\ell$. Let $(u_\ell,i_\ell) \in R^\ell$ be a (vertex, minimum timestamp) pair such that $R^\ell_{u_\ell,i_\ell} = 1$. For the first iteration, where $\ell = k+1$, we remove the vertex $u_{k+1}=d$ and remove the incoming and outgoing edges of $u_{k+1}$ in $G^{k+1}$ to obtain $G^{k}$. Let $M^{\ell-1}=M^\ell \setminus c(u_\ell)$ and $\tau^{\ell-1}=i_\ell$. We evaluate the instance $(G^{\ell-1},c',M^{\ell-1},\ell-1,s', \tau^{\ell-1})$ to obtain $R^{\ell-1}$. Let $(u_{\ell-1},i_{\ell-1}) \in R^{\ell-1}$ be a (vertex, timestamp) pair such that $R^{\ell-1}_{u_{\ell-1}, i_{\ell-1}} = 1$. As $R^\ell_{u_\ell,i_\ell} = 1$ there exists an edge $(u_{\ell-1}, u_{\ell}, i_\ell) \in E(G^{\ell})$ in $G^\ell$. In each iteration, we add the edge $(u_{\ell-1}, u_\ell, i_\ell)$ to the solution and continue the process for each $\ell \in \{k+1,k,\dots,2\}$. In total we make $k$ queries to the fine-grained oracle. Thus, the runtime of extracting an optimal solution is $\sum^{k+1}_{\ell=2} 2^\ell \ell m \Delta = \ensuremath{\mathcal{O}}\xspace(2^k k m \Delta)$. Similarly, we have a $\ensuremath{\mathcal{O}}\xspace(2^k k m \Delta)$-time algorithm for extracting an optimal solution for the \ensuremath{k \text{\sc-Restless\-Path}}\xspace problem. \begin{figure} \tikzset{every picture/.style={scale=0.9}} \setlength{\tabcolsep}{30pt} \begin{tabular}{c c} \input{tikz/tikz-finegrained-extraction-3} & \input{tikz/tikz-finegrained-extraction-4} \\ \ensuremath{k\text{\sc-Restless\-Motif}}\xspace & \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace \end{tabular} \caption{\label{fig:algo:finegrained-extraction:2} The transformation of the \ensuremath{k\text{\sc-Restless\-Motif}}\xspace problem (left) to an instance of the \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace problem (right) for extracting a solution using the fine-grained oracle. Vertices with color \underline{r}ed, \underline{b}lack and \underline{g}reen are drawn using diamond, circular and square shapes, respectively. } \end{figure} Using a similar construction, we can improve the runtime of extracting an optimal solution for the \ensuremath{\text{\sc Path\-Motif}}\xspace and \ensuremath{k\text{\sc{-Temp}\-Path}}\xspace problems introduced in~\cite{Thejaswi2020pattern,thejaswi2020finding} from $\ensuremath{\mathcal{O}}\xspace((2^k k (n\tau + m))(k \log n + \log \tau)) + k!)$ to $\ensuremath{\mathcal{O}}\xspace(2^k k (n \tau + m))$. \begin{table*}[t] \caption{A summary of time and space complexity. Here, $n$ is the number of vertices, $m$ is the number of edges, $\tau$ is the maximum timestamp, $k-1$ is the length of path and $\Delta$ is the maximum resting time. For each row, the space complexity is $\ensuremath{\mathcal{O}}\xspace(n \tau)$.} \label{table:summary:1} \centering \begin{tabular}{l r} \toprule Problem & Time complexity\\ \midrule {\em {Fine-grained oracle}} \\ \cmidrule(r{3.5em}){1-1} \ensuremath{\text{\sc Restless\-Path}}\xspace & $\ensuremath{\mathcal{O}}\xspace(2^n n m \Delta)$ \\ \ensuremath{k \text{\sc-Restless\-Path}}\xspace & $\ensuremath{\mathcal{O}}\xspace(2^k k m \Delta)$ \\ \ensuremath{k\text{\sc-Restless\-Motif}}\xspace & $\ensuremath{\mathcal{O}}\xspace(2^k k m \Delta)$ \\ {\sc Restless\-Reach}\xspace & $\ensuremath{\mathcal{O}}\xspace(2^n n m \Delta)$ \\ \ensuremath{k \text{\sc -Restless\-Reach}}\xspace & $\ensuremath{\mathcal{O}}\xspace(2^k k m \Delta)$ \\ \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace & $\ensuremath{\mathcal{O}}\xspace(2^k k m \Delta)$ \\ \ensuremath{\textit{atm-} k \text{\sc -Restless\-Reach}}\xspace & $\ensuremath{\mathcal{O}}\xspace(2^k k m \Delta)$ \\ \midrule {\em {Extraction} (\ensuremath{k \text{\sc-Restless\-Path}}\xspace)}\\ \cmidrule{1-1} Self-reducibility + temporal {\small DFS} & $\ensuremath{\mathcal{O}}\xspace((2^k k^2 m \Delta \log n \log \tau) + k!)$ \\ Fine-grained extraction & $\ensuremath{\mathcal{O}}\xspace(2^k k m \Delta)$ \\ \bottomrule \end{tabular} \end{table*} \subsection{Infeasibility of a $\ensuremath{\mathcal{O}}\xspace^*((2-\epsilon)^k)$-time algorithm for \ensuremath{k\text{\sc-Restless\-Motif}}\xspace} \label{sec:algo:infeasibility} In this subsection, we prove that under plausible complexity-theoretic assumptions, the algorithms presented for \ensuremath{k\text{\sc-Restless\-Motif}}\xspace and \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace are optimal. In particular, the assumption that we rely on is the Set Cover Conjecture~\cite{cygan2016problems} (SCC) which is formulated as follows. In the {\sc Set\-Cover}\xspace problem we are given an integer $f$ and a family of sets $\pazocal{S}$ over the universe $U = \bigcup \pazocal{S}$ with $n = |U|$ and $m = |\pazocal{S}|$. The goal is to decide whether there is a subfamily of at most $f$ sets $S_1, S_2, \ldots, S_f \in \pazocal{S}$ such that $U = \bigcup_{i=1}^{f} S_i$, i.e., that the selected sets cover the universe $U$. The SCC of {Cygan et al.}~\cite{cygan2016problems} states that there is no algorithm for the {\sc Set\-Cover}\xspace problem that runs in time $(2-\epsilon)^n (nm)^{\ensuremath{\mathcal{O}}\xspace(1)}$ for any $\epsilon > 0$. In fact, the fastest known algorithm for solving {\sc Set\-Cover}\xspace runs in time $\ensuremath{\mathcal{O}}\xspace^*(2^n)$, and an algorithm running in time $\ensuremath{\mathcal{O}}\xspace^*((2-\epsilon)^n)$ for any $\epsilon > 0$ has been deemed a major breakthrough after decades of research on the problem. Under SCC, exponential lower bounds for several fundamental problems are known (see e.g.,~\cite{cygan2016problems,bjorklund2013probably,krauthgamer2019set}). However, even if SCC turned out to be false, these results (and Theorem~\ref{theorem:motifalgo:infeasibility}) are still meaningful: instead of trying to find a faster algorithm for e.g., the arguably richer problem of \ensuremath{k\text{\sc-Restless\-Motif}}\xspace, one can focus on {\sc Set\-Cover}\xspace which is simpler. To obtain our result, it will convenient to recall the \ensuremath{\text{\sc Color\-ful\-Path}}\xspace problem in static graphs, and to perform a reduction from that problem to \ensuremath{k\text{\sc-Restless\-Motif}}\xspace problem. \mpara{Colorful path problem (\ensuremath{\text{\sc Color\-ful\-Path}}\xspace).} Given a static graph $G=(V,E)$ and a coloring function $c:V\rightarrow [k]$, the problem asks if there exists a path of length $k-1$ in $G$ such that the vertex colors of the path are different (i.e., such that each color occurs exactly once). The problem is known to be \ensuremath{\mathbf{NP}}\xspace-hard, and known not to admit a $\ensuremath{\mathcal{O}}\xspace^*((2 - \epsilon)^k)$ algorithm for any $\epsilon > 0$ assuming SCC. \begin{theorem}[Kowalik and Lauri~\cite{KowalikL2016}] \label{theorem:algo:infeasibility} Assuming the Set Cover Conjecture, there exists no $\ensuremath{\mathcal{O}}\xspace^*((2-\epsilon)^k)$ time algorithm for solving the \ensuremath{\text{\sc Color\-ful\-Path}}\xspace problem for any $\epsilon > 0$. \end{theorem} \begin{theorem} \label{theorem:motifalgo:infeasibility} If the \ensuremath{k\text{\sc-Restless\-Motif}}\xspace problem has a $\ensuremath{\mathcal{O}}\xspace^*((2-\epsilon)^k)$ time algorithm for any $\epsilon > 0$ then \ensuremath{\text{\sc Color\-ful\-Path}}\xspace problem has a $\ensuremath{\mathcal{O}}\xspace^*((2-\epsilon)^k)$ time algorithm. \end{theorem} \begin{proof} Given an instance $I = (G, c, k)$ of the \ensuremath{\text{\sc Color\-ful\-Path}}\xspace problem in static graphs, we construct an instance $I' = (G', M', c', k')$ of the \ensuremath{k\text{\sc-Restless\-Motif}}\xspace problem in temporal graph by letting $G'=(V',E')$, $V' = V \cup \{s, d\}$, $E'= \{(u,v,1): (u,v) \in E\} \cup \{(s,u,1): u \in V\} \cup \{(u,d,1): u \in V\}$, $c'(u) = c(u)~\text{for all}~u \in V$, $c(s)=k+1$, $c(d) = k+2$, $M=\{1,\dots,k+2\}$, and $\delta: V \rightarrow 1$, $\Delta=1$, $k'=k+2$. Informally, $G'$ is constructed from $G$ by replacing each edge with a temporal edge with timestamp one, and by making $s$ and $d$ adjacent to a new vertex both receiving a new unique color. We claim that the instance $I$ of \ensuremath{\text{\sc Color\-ful\-Path}}\xspace has a solution if and only if the instance $I'$ of \ensuremath{k\text{\sc-Restless\-Motif}}\xspace has a solution. Let $P=v_1e_1v_2 \dots e_{k-1}v_k$ be a colorful path in $G$. By construction, we know that for each edge $(u,v) \in E$ we have $(u,v,1) \in E'$, so the path $P'=s e'_0 v_1 e'_1 v_2 \dots e'_{k-1} v_k e'_k d$ exists in $G'$, where $e'_0=(s,v_1,1)$, $e'_k=(v_k,d,1)$, and $e'_i=(v_i,v_{i+1}, 1)$ for all $i \in [k-1]$. Also, the vertex colors of $\{v_1,\dots,v_k\}$ agree with $\{1,\dots,k\}$ since the $P$ is colorful, so the vertex colors of $\{s,d\} \cup \{v_1,\dots,v_k\}$ agree with $M'$. We conclude that $P'$ is a \ensuremath{k\text{\sc-Restless\-Motif}}\xspace in $G'$. Conversely, let $P'=s e'_0 v_1 e'_1 \dots e'_{k-1} v_k e'_{k+1} d$ be a solution for $I'$ in $G'$. We construct a static path $P=v_1 e_1 v_2 \dots e_{k-1}v_k$ by replacing the edges $e'_i=(v_i,v_{i+1},1)$ by $e_i=(v_i,v_{i+1})$ for all $i \in [k+1]$. Since the vertices $\{s,d\} \cup \{v_1,\dots,v_k\}$ agree with colors $M = \{1,\dots,k+2\}$, the vertex colors of $\{v_1,\dots,v_k\}$ agree with colors $\{1,\dots,k\}$ as the colors $k+1$ and $k+2$ only appear once each on $G'$. Evidently, $P$ is a colorful path in $G$. \end{proof} It follows that if we have an algorithm for solving \ensuremath{k\text{\sc-Restless\-Motif}}\xspace with $\ensuremath{\mathcal{O}}\xspace^*((2-\epsilon)^k)$ time for some $\epsilon > 0$, we can use it solve \ensuremath{\text{\sc Color\-ful\-Path}}\xspace in static graphs using the construction described in Theorem~\ref{theorem:motifalgo:infeasibility} within the same time bound. However, from Theorem~\ref{theorem:algo:infeasibility} we know that such an algorithm does not exists unless SCC is false. Put differently, assuming SCC, \ensuremath{k\text{\sc-Restless\-Motif}}\xspace does not admit an algorithm running in time $\ensuremath{\mathcal{O}}\xspace^*((2-\epsilon)^k)$ for any $\epsilon > 0$. Finally, since \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace problem generalizes the \ensuremath{k\text{\sc-Restless\-Motif}}\xspace problem, the former problem does not admit an algorithm running in time $\ensuremath{\mathcal{O}}\xspace^*((2-\epsilon)^k)$ for any $\epsilon > 0$, assuming SCC. \iffalse In this section, we present evidence that the algorithms presented for the \ensuremath{k\text{\sc-Restless\-Motif}}\xspace and \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace problem are probably optimal under the standard complexity theory assumptions. For this purpose we reduce the set cover problem to \ensuremath{k\text{\sc-Restless\-Motif}}\xspace problem and prove that the set cover instance has a solution if and only if \ensuremath{k\text{\sc-Restless\-Motif}}\xspace instance has a solution. \mpara{Set cover problem ({\sc Set\-Cover}\xspace).} Given a collection of subsets $\mathcal{X}=\{X_1,\dots,X_m\}$ over the universe $U = \bigcup_{j \in [m]} X_j$, $|U|=n$ and an integer $t < n$. The problem asks to find a collection $X_{j_1},\dots,X_{j_t}$ such that $ \bigcup_{i \in [t]}X_{j_i} = U$. For simplicity let us assume $U=[n]$. We make use of the following lemma. \begin{lemma}[Cygan et al.~\cite{cygan2015parameterized}] If {\sc Set\-Cover}\xspace instance has a $\ensuremath{\mathcal{O}}\xspace^*((2-\epsilon)^{n+t}))$ time algorithm for some $\epsilon > 0$ then it also has a $\ensuremath{\mathcal{O}}\xspace^*((2-\epsilon')^n)$ time algorithm for some $\epsilon' > 0$. \end{lemma} \begin{lemma} If \ensuremath{k\text{\sc-Restless\-Motif}}\xspace problem has a $\ensuremath{\mathcal{O}}\xspace^*((2-\epsilon)^{k})$ time algorithm for some $\epsilon > 0$ then the {\sc Set\-Cover}\xspace problem has a $\ensuremath{\mathcal{O}}\xspace^*((2-\epsilon')^n)$ algorithm for some $\epsilon' > 0$. \end{lemma} \begin{proof} Given a {\sc Set\-Cover}\xspace instance $(U, \mathcal{X}, t)$, we construct a \ensuremath{k\text{\sc-Restless\-Motif}}\xspace instance $(G, c, M, s, d, k)$. The graph has $t+2$ layers and each layer $\ell \in \{0,\dots,t+1\}$ is denoted by $G^\ell$. For each $X_j \in \mathcal{X}$ we construct $t$ copies of complete graph $S^\ell_j$ for each $\ell \in \{1,\dots,t\}$ such that $$ V(S^\ell_j) = s^\ell_j \cup \{u^\ell_{i,j}: i \in X_j\}, E(S^\ell_j) = V(S^\ell_j) \times V(S^\ell_j) \times [1],$$ $$V(G^\ell)=\bigcup_{j \in [m]} V(S^\ell_j), E(G^\ell)=\bigcup_{j \in [m]} E(S^\ell_j),$$ $$ c(s^\ell_j)=n+1, c(u^\ell_{i,j}) = i~\text{for all}~ u^\ell_{i,j} \in V(S^\ell_j) \setminus s^\ell_j.$$ For layers $\ell = \{0, t+1\}$, we build $G^0, G^{t+1}$ such that, $$V(G^0)=\{s^0_{m+1}\}, V(G^{t+1}) =\{s^{t+1}_{m+1}\}, E(G^0) = E(G^{t+1}) = \emptyset,$$ $$c(s^0_{m+1}) = n+2, c(s^{t+1}_{m+2}) = n+3.$$ Finally, we construct the graph $G=(V,E)$ by connecting the vertices $V(G^\ell)$ of layer $\ell$ with the vertices $s^{\ell+1}_j \in V(G^{\ell+1})$ of layer $\ell+1$ for all $\ell \in \{0,\dots,t\}$. Using such a construction ensures that a path passing from layer $\ell$ to layer $\ell+1$ must pass through a vertex $s^{\ell+1}_j$ for some $j \in [m]$. $$V = \bigcup_{\ell \in \{0,\dots,t+1\}} V(G^\ell),$$ $$E = \bigcup_{\ell \in \{0,\dots,t+1\}} E(G^\ell) \cup \{(u, s^{\ell+1}_{j},1): u \in V(G^{\ell}), s^{\ell+1}_j \in V(G^{\ell+1})~ \text{for all}~ \ell \in \{0,\dots,t\}\},$$ $$\tau= 1, \Delta=1, \delta:V \rightarrow \Delta, M= U \cup \{(n+1)^t, n+2, n+3\}, k=n+t+2.$$ For simplicity, we denote the source $s^{0}_{m+1} = s$ and the destination $s^{t+1}_{m+2} = d$. The graph construction is illustrated in Figure~\ref{fig:graph-construction}. Without loss of generality let $X_1,\dots,X_t$ be a solution for the {\sc Set\-Cover}\xspace problem. For each $\ell \in [t]$ let $Z_\ell = X_\ell \setminus \bigcup_{j < \ell} X_j$ be the set of elements covered by $X_\ell$. We construct a restless temporal path $P^\ell$ starting from $s^\ell_\ell$ and passing through all the vertices $u^\ell_{i,j} \in Z_\ell$. Such a path is possible since $S^\ell_\ell$ is a complete subgraph. Finally we join the paths $P = s,e_1,P^1,\dots,P^t,e_{t+1},d$. The vertex colors of $P$ agree with $M$ since $X_1,\dots,X_t$ cover $U$ so there exists one vertex with $u^\ell_{i,j}$ for each $i \in [n]$ and for some $\ell \in [t]$. Additionally, the vertices $s^1_1,\dots,s^t_t$ have color $n+1$, vertices $s, d$ has colors $n+2, n+3$, respectively. Since all the edges have timestamp $1$ the maximum resting time of the path is at most $0$. So $P$ is a solution for the \ensuremath{k\text{\sc-Restless\-Motif}}\xspace problem. Let $P$ be a solution for the \ensuremath{k\text{\sc-Restless\-Motif}}\xspace problem. From the construction it holds that for each graph layer $G^\ell$, $\ell \in [t]$, the path $P$ must enter $G^\ell$ via a vertex $s^\ell_j$. Without loss of generality let $\{s^1_1,\dots,s^t_t\}$ be the vertices in the solution occurring in $P$ in this order then $\{S_1,\dots,S_t\}$ is a solution for the {\sc Set\-Cover}\xspace problem. Since $P$ contain a vertex with each color in $[n]$ there must be at least one occurrence of $i \in \bigcup_{j \in [t]} S_j$. So $\bigcup_{j \in [t]} S_j = U$. So given a {\sc Set\-Cover}\xspace instance we can transform it to the \ensuremath{k\text{\sc-Restless\-Motif}}\xspace instance we reduce the {\sc Set\-Cover}\xspace instance to \ensuremath{k\text{\sc-Restless\-Motif}}\xspace instance and solve the problem. Using the reduction described above any {\sc Set\-Cover}\xspace instance can be solved in time $\ensuremath{\mathcal{O}}\xspace^*((2-\epsilon)^{n+k+2}))$. Furthermore from Lemma~\ref{} it implies that we also have a $\ensuremath{\mathcal{O}}\xspace^*((2-\epsilon')^n)$ algorithm for the {\sc Set\-Cover}\xspace problem. \end{proof} Assuming the set-cover conjecture there exists no algorithm with time $\ensuremath{\mathcal{O}}\xspace^*((2-\epsilon')^n)$ algorithm for solving the {\sc Set\-Cover}\xspace problem. So it is most likely that the exponent cannot be reduced to a factor below $2$ and our only hope is to improve the polynomial factor in the algorithm runtime. \begin{figure}[t] \centering \caption{\label{fig:generating:1} An illustration of constructing \ensuremath{k\text{\sc-Restless\-Motif}}\xspace instance from {\sc Set\-Cover}\xspace instance.} \end{figure} \fi \section{Conclusions and future work} \label{sec:conclusion} In this work, we studied a family of reachability problems in temporal and vertex-colored temporal graphs under waiting-time restrictions. We presented an algebraic algorithm framework for solving restless reachability problem we proposed, running in $\ensuremath{\mathcal{O}}\xspace(2^k k m \Delta)$ time and $\ensuremath{\mathcal{O}}\xspace(n\tau)$ space. We presented evidence that the algorithms for solving variants of the restless reachability problems involving colors presented in this work are optimal under plausible complexity-theoretic assumptions. Further, we engineered an open-source implementation of our algorithm, and demonstrated its viability in experiments on graphs with millions of temporal edges from real-world datasets. Finally, we applied the algorithm we developed in a case study for estimating the change in disease spreading with the presence of people with immunity. Our finding is that heuristic approaches such as selecting vertices with high degree as separators are not effective in all the graph datasets. Towards this end, we would like to investigate effective ways to choose a small set of separators under waiting time restrictions to contain the spread of the disease in the network. We believe our algorithms, based on multilinear and constrained multilinear sieving, can be extended even further to solve a range of other pattern-detection problems in temporal graphs, including finding arborescences, connected temporal subgraphs and temporal subgraphs with additional color constraints on the vertices. We also note that our temporal reachability setting corresponds to the {\sc\large SIS} (susceptible-infectious-susceptible) epidemic model. Another interesting direction is to develop algorithms for temporal reachability that corresponds to the SIR (susceptible-infectious-removed) model. \begin{table} \footnotesize \caption{\label{table:symbols} List of symbols.} \begin{tabular}{l l} \hline Symbol & Description \\ \hline {\em {Graphs}}\\ \cmidrule(r{1em}){1-1} $G=(V,E)$ & graph $G$ with vertex set $V$ and edge set $E$\\ $n$ & number of vertices\\ $m$ & number of edges\\ $m_i$ & number of edges at time stamp $i$\\ $\Delta$ & maximum resting time\\ $\tau$ & maximum timestamp\\ $k$ & length of path or walk \\ $\delta:V \rightarrow [\Delta]$ & restless function mapping vertices to resting time\\ $N_i(u)$ & in-neighbors of vertex $u$ at time stamp $i$\\ $\ulg{G}$ & \change{underlying static graph of temporal graph $G$}\\ $\deltaexp{G}$ & \change{$\delta$-expansion of temporal graph $G$}\\ \hline {\em {Coloring}}\\ \cmidrule(r{1em}){1-1} $C$ & set of colors \\ $c:V \rightarrow C$ & coloring function mapping vertices to colors \\ $M$ & multiset of colors \\ $\mu(s)$ & number of occurrences of color $s$ in $M$\\ \hline {\em {Polynomials}} \\ \cmidrule(r{1em}){1-1} $\mathcal{P}$ & polynomial encoding of temporal walks\\ $\chi$ & polynomial encoding of restless walks\\ $\zeta$ & evaluation polynomial of restless walks\\ $x_u$ & $x$-variable encoding vertex $u$\\ $y_{uv,\ell,j}$ & $y$-variable encoding edge $(u,v,j)$ at position $\ell$\\ $\vec{x}$ & \change{vector of $x$ variables}\\ $\vec{y}$ & \change{vector of $y$ variables}\\ $\vec{z}$ & \change{vector of $z$ variables}\\ \hline \end{tabular} \end{table} \section{Experiments} \label{sec:experiments} In this section, we describe our setup and the experimental results to validate our approach and demonstrate its scalability. Our implementation is available as open source~\cite{restless-paths-code}. \subsection{Implementation} A high-level intuition of the implementation is as follows: For variables $\{x_v : v \in V\}$ and $\{y_{uv,\ell,i}: (u,v,i) \in E, \ell \in [k]\}$ we assign a value from the Galois field $\ensuremath{\text{GF}}\xspace(2^b)$. Multiplication between any two field variables is defined as an {\tt XOR} operation, likewise, multiplying two variables with same value results in a zero-term. We know that the monomials corresponding to walks that are not paths have at least one repeated variable, so the corresponding monomial evaluates to a zero term, while the monomial corresponding to a path evaluates to a non-zero term since there are no repeated variables. It is possible that a monomial corresponding to a path might evaluate to a zero term resulting in a false negative. To reduce the probability of false negatives, we repeat the evaluation with $2^k$ random assignments for variables $\{x_u: u \in V$ and $\left\{y_{uv,\ell,i}: (u,v,i) \in E, \ell \in [k]\right\}$. In theory, the false negative probability of our algorithm is $2^{-b}(2k-1)$. For our experiments, we choose the field size $b=64$, which makes the false negative probability negligible. Modern CPUs have very high arithmetic and memory bandwidth, however, the bandwidth comes at the cost of latency. Each arithmetic and memory-access operation is associated with a corresponding latency factor, and often the memory-access latency is orders of magnitude greater than the arithmetic latency. As such, the challenge for efficient implementation engineering is to keep the arithmetic pipeline busy while fetching data from memory for the subsequent arithmetic operations. Memory bandwidth can be improved by using coalesced-memory access, that is, by organizing the memory layout such that the data for consecutive computations are available in consecutive memory addresses. In addition, we can use hardware pre\-fetching to fetch the data required in subsequent computation while performing computation on the data, which is currently in the memory. Arithmetic bandwidth can be improved using vector extensions, that is, by grouping the data on, which the same arithmetic operations are executed. More precisely, if we are executing the same arithmetic instructions on different operands or data, we can group the operands using vector extensions to execute arithmetic operations in parallel. For more technical details related to implementation engineering we refer the reader to~\cite{BjorklundKKL2015,KaskiLT2018,thejaswi2020finding}. Our implementation is written in the C programming language with OpenMP constructs to achieve thread-level parallelism. Vector parallelism is achieved by enabling parallel executions of the same arithmetic operations, which make use of advanced vector extensions (AVX2). Additionally, we use carry-less multiplication of one quadword ({\sc\large pclmulqdq}) instruction set to enable fast finite-field arithmetic. The finite-field arithmetic implementation we use is from~\cite{BjorklundKKL2015}. Our engineering effort boils down to implementing the recursions in Equations~(\ref{eq:poly-enc:1}) and~(\ref{eq:multilinear:3}) and evaluating the polynomial using $2^\ell$ random substitutions for the $x$-variables. Recall that from the construction of the generating function the $y$-variables are unique, so we generate the values of $y$-variables using a pseudo\-random number generator. The values of the $x$-variables are computed using Equation~(\ref{eq:multilinear:3}). Our implementation loops over four variables: the outer most loop is over $[\ell]$, the second loop is over $[\tau]$, the third loop is over $V$, and the final loop is over $\{0,\dots,\delta(u)\}$ for $u \in V$. In Equation~(\ref{eq:multilinear:3}), computing the polynomial $\prep{u}{\ell}{i}$ is independent for each $u \in V$ if we fix~$\ell$ and~$i$, so the algorithm can be thread-parallelized up to $|V| = n$ threads. We make use of the OpenMP API using the {\tt omp parallel for} construct with {\tt default} scheduling over vertices in $V$ to achieve thread parallelism. Additionally, performing $2^\ell$ random substitutions of $x$-variables is independent of each other, so each of the $2^\ell$ evaluations can be vector-parallelized. We achieve this by grouping the arithmetic operations on $2^\ell$ random substitutions of variables in $x$ and enabling the vector extensions from AVX2. Recall that our inner-most loop is over $\{0,\dots,\delta(u)\}$, so we arrange the memory layout as $n \times \tau$ to saturate the memory bandwidth. We also employ hardware pre\-fetching by forcing the processor to fetch data for subsequent computations while we are still performing the computation on the data, which is already in the memory. Our implementation uses $\ensuremath{\mathcal{O}}\xspace(n \tau + m)$ memory, which is due to the adjacency list representation of the temporal graphs. \mpara{Preprocessing.} In the restless reachability problems considered in our work, we compute reachability from a given source vertex to all other vertices without an explicit restriction on the time window. As such, we do not see a straightforward approach to preprocessing the temporal graph $G$ to reduce its size using heuristic preprocessing techniques such as slicing $G$ within a time window, i.e., considering the edges between a minimum and maximum timestamp window. Alternatively, we can merge $G$ to obtain a static graph, compute reachability on the static graph, and reconstruct a temporal graph by only using the vertices, which are reachable in the static graph. Such a preprocessing technique is correct since there exists a restless path between any two vertices in a temporal graph only if there exists a path in the corresponding static graph, while the other direction is not always true. However, most of the datasets considered in our experiments have a connected static underlying graph, and therefore we do not see a significant reduction in graph size. For the restless reachability problems with additional color constraints i.e., for the \ensuremath{k\text{\sc-Restless\-Motif}}\xspace and \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace problems, we can take advantage of two preprocessing techniques to reduce the graph size: ($i$) by removing all the vertices whose vertex colors do not match with the multiset colors; ($ii$) by merging the temporal graph to a static graph instance, build a vertex-localized sieve on the static graph, and reconstruct the graph using the set of vertices reachable in the static graph instance. Note that these are heuristic approaches to reduce the graph size and we do not claim any theoretical bounds for the reduction in the graph size. For a detailed discussion of preprocessing using vertex-localized sieving we refer the reader to an earlier work~\cite[\S~Preprocessing]{thejaswi2020finding}. \subsection{Experimental setup} \label{sec:exp:setup} Here we describe the hardware details and the input graphs used for our experiments. \spara{Hardware.} We make use of two hardware configurations for our experiments. \squishlist \item A \emph{workstation} with $1 \times 3.2$~GHz Intel Core\,i5-4570\,CPU, Haswell microarchitecture, $4$ cores, $16$~Gb memory, Ubuntu, and \texttt{gcc}\,v9.1.0. \item A {\em compute\-node} with $2\times${2.5}~GHz Intel Xeon\,2680\,V3 CPU, 24 cores, 12 cores/CPU, 256~Gb memory, Red Hat, and $\texttt{gcc}$\,v9.2.0. \squishend The experiments make use of all the cores. Additionally, we make use of AVX2 and hardware pre\-fetching to saturate the arithmetic and memory bandwidth, respectively. \spara{Input graphs.} We use both synthetic and real-world graphs in our experiments. For \emph{synthetic} graphs, we use the temporal-graph generator from Thejaswi et al.~\cite[\S\,9.3]{thejaswi2020finding}, in particular we make use of $d$-regular and power-law graphs. The regular graphs are generated using the \emph{configuration model}~\cite[\S\,2.4]{Bollobas01}. The configuration model for power-law graphs is as follows: given non-negative integers $D$, $n$, $w$, and $\alpha < 0$, we generate an $n$-vertex graph such the following properties roughly hold: ($i$) the sum of vertex degrees is~$Dn$; ($ii$) the distribution of degrees is supported at $w$ distinct values with geometric spacing; and ($iii$) the frequency of vertices with degree $d$ is proportional to~$d^\alpha$. The edge timestamps are assigned uniformly at random in the range~$[\tau]$. Both directed and undirected graphs are generated using the same configuration model, however, for directed graphs the orientation is preserved. We ensure that the graph generator produces identical graph instances in all the hardware configurations. For \emph{real-world} graphs, we use the co-presence dataset from socio-patterns \cite{Genois2018}, Koblenz network collections~\cite{koblenz}, Copenhagen study network~\cite{sapiezynski2019interaction}, and public-transport networks~\cite{kujala2018collection}. For a description of the datasets, see the respective references. The preprocessing details of each dataset is described below. We pre\-process the datasets to generate a graph by renaming the location identifiers (or vertices) in the range from $1$ to the maximum number of locations (or vertices) available in the dataset. If the time values in dataset are Unix timestamps, we approximate the value to the closest second rounded down before assigning an unique timestamp identifier. For datasets from socio-patterns, we reduce the maximum timestamp $\tau$ by dividing each timestamp by 20 and rename the timestamps in the range from $1$ to the difference between the maximum and minimum timestamps. Since socio-patterns datasets are undirected contact-networks we replace each undirected edge with two directed edges in both directions. For the Koblenz datasets we round the timestamp to the closest day. \spara{Dataset statistics.} For each real-world dataset we report the number of vertices $n$, the maximum timestamp $\tau$, the number of temporal edges $m$, and the average temporal degree $d_{\text{avg}} = \frac{m}{n \tau}$. Furthermore, for each dataset we construct a static undirected graph or an {\em underlying graph} by considering the edges without the timestamp information ignoring multiple edges (if any) between the same set of vertices. For a temporal graph $G$, we denote the corresponding underlying (static) graph as $\ulg{G}$. For the underlying graph we report the number of edges $\ulg{m}$, the average degree $\ulg{d}_{\text{avg}}$, the length of the diameter $\ulg{D}_{\text{max}}$, the feedback edge number (FEN), and the feedback vertex number (FVN). The dataset statistics are reported in Table~\ref{table:exp:datasets}. The {\em average degree} $\ulg{d}_{\text{avg}}=\frac{\ulg{m}}{n}$ is the ratio of number of edges and the number of vertices in the static graph. The {\em diameter} of a static graph is the length of a longest shortest path between any two vertices and it can be computed in time $\ensuremath{\mathcal{O}}\xspace(n \ulg{m})$, where $n$ is number of vertices and $\ulg{m}$ is number of edges, however, the run\-time can be further reduced to $\ensuremath{\mathcal{O}}\xspace(\ulg{m})$ in practice~\cite{crescenzi2013on}. The diameter of the underlying graph is neither a lower bound nor an upper bound on the maximum length of the restless path. We report this value only to show that usually the path length parameter is orders of magnitude less than the parameters FVN and FEN in most real-world graph datasets. The {\em feedback edge number} of a static graph $G=(V,E)$ is the minimum number of edges that need to be removed from $G$ in order to make $G$ acyclic. Formally, a set $F \subseteq E$ is a \emph{feedback edge set} if $(V,E \setminus F)$ does not contain a cycle. In other words, the feedback edge number of $G$ is the size of a minimum feedback edge set for $G$. The feedback edge number can be computed in polynomial-time by computing a maximum spanning forest of $G$ and by taking its edge-complement. The {\em feedback vertex number} of a static graph $G=(V,E)$ is the minimum number of vertices that need to be removed from $G$ in order to make $G$ acyclic. Formally, a set $F \subseteq V$ is a \emph{feedback vertex set} if $(V \setminus F, E \setminus \{(u,v): u \in F~\text{or}~v \in F\})$ does not contain a cycle. The feedback vertex number of $G$ is the size of minimum feedback vertex set of $G$. In contrast to the feedback edge number, computing the feedback vertex number is \ensuremath{\mathbf{NP}}\xspace-hard (see e.g.,~\cite{karp1972reducibility}). For computing the feedback vertex number, we use the solvers from the work of Iwata et al.~\cite{iwata2016half,fvs-code}. \begin{table} \centering \caption{\label{table:exp:datasets} Dataset statistics. Here, $n$ is the number of vertices, $m$ is the number of temporal edges, $\tau$ is the number of timestamps, $d_{\text{avg}}$ is the average degree of the temporal graph; and $\ulg{m}$ is number of edges, $\ulg{d}_{\text{avg}}$ is the average degree, $\ulg{D}_{\text{max}}$ is the diameter, FEN is the feedback edge number, FVN is the feedback vertex number of the underlying static graph. See main text for a precise definition of these parameters. } \footnotesize \begin{tabular}{l r r r r r r r r r} \toprule & \multicolumn{4}{c}{{\em temporal graph}} & \multicolumn{5}{c}{{\em static undirected graph}}\\ \cmidrule(l{2em}){2-5} \cmidrule(l{2em}){6-10} Dataset & $n$ & $m$ & $\tau$ & $d_{\text{avg}}$ & $\ulg{m}$ & $\ulg{d}_{\text{avg}}$ & $\ulg{D}_{\text{max}}$ & FEN & FVN\\ \midrule {\em Copenhagen}\\ \cmidrule(r{1em}){1-1} {\sf Calls} & 536 & 3\,600 & 4\,028 & 0.00 & 621 & 1.16 & 22 & 248 & 50 \\ {\sf SMS} & 568 & 24\,333 & 4\,032 & 0.01 & 697 & 1.23 & 20 & 233 & 58 \\ \midrule {\em Socio-patterns}\\ \cmidrule{1-1} {\sf LH10} & 73 & 300\,252 & 12\,960 & 0.31 & 1\,381 & 18.92 & 3 & 1\,309 & 50 \\ {\sf InVS13} & 95 & 788\,494 & 49\,679 & 0.16 & 3\,915 & 41.21 & 2 & 3\,821 & 85 \\ {\sf InVS15} & 219 & 2\,566\,388 & 49\,679 & 0.24 & 16\,725 & 76.37 & 3 & 16\,508 & 198 \\ {\sf SFHH} & 403 & 2\,834\,970 & 5\,328 & 1.32 & 73\,557 & 182.52 & 2 & 73\,155 & 384 \\ {\sf LyonSchool} & 242 & 13\,188\,984 & 5\,887 & 9.26 & 26\,594 & 109.89 & 2 & 26\,353 & 235 \\ {\sf Thiers13} & 328 & 37\,226\,078 & 19\,022 & 5.96 & 43\,496 & 132.61 & 2 & 43\,169 & 315 \\ \midrule {\em Koblenz}\\ \cmidrule(r{1em}){1-1} {\sf sqwikibooks} & 6\,607 & 21\,709 & 906 & 0.00 & 7\,731 & 1.17 & 7 & 6\,693 & 22 \\ {\sf pswiktionary} & 26\,595 & 66\,112 & 982 & 0.00 & 53\,167 & 2.00 & 10 & 39\,591 & 30 \\ {\sf sawikisource} & 48\,960 & 106\,991 & 948 & 0.00 & 72\,608 & 1.48 & 4 & 60\,588 & 83 \\ {\sf knwiki} & 78\,142 & 714\,594 & 1\,107 & 0.00 & 306\,077 & 3.92 & 9 & 254\,671 & 1\,965 \\ {\sf epinions} & 131\,828 & 841\,372 & 189 & 0.01 & 711\,783 & 5.40 & 16 & 652\,338 & - \\ \midrule {\em Transport}\\ \cmidrule(r{1em}){1-1} {\sf Kuopio} & 549 & 32\,122 & 1\,232 & 0.05 & 699 & 1.27 & 29 & 219 & 43 \\ {\sf Rennes} & 1\,407 & 109\,075 & 1\,223 & 0.06 & 1\,670 & 1.19 & 57 & 329 & 95 \\ {\sf Grenoble} & 1\,547 & 114\,492 & 1\,314 & 0.06 & 1\,679 & 1.09 & 82 & 489 & 50 \\ {\sf Venice} & 1\,874 & 118\,519 & 1\,474 & 0.04 & 2\,647 & 1.41 & 61 & 875 & 222 \\ {\sf Belfast} & 1\,917 & 122\,693 & 1\,132 & 0.06 & 2\,180 & 1.14 & 64 & 291 & 95 \\ {\sf Canberra} & 2\,764 & 124\,305 & 1\,095 & 0.04 & 3\,206 & 1.16 & 51 & 475 & 135 \\ {\sf Turku} & 1\,850 & 133\,512 & 1\,260 & 0.06 & 2\,335 & 1.26 & 67 & 665 & 157 \\ {\sf Luxembourg} & 1\,367 & 186\,752 & 1\,211 & 0.11 & 1\,903 & 1.39 & 34 & 687 & 160 \\ {\sf Nantes} & 2\,353 & 196\,421 & 1\,280 & 0.07 & 2\,743 & 1.17 & 82 & 524 & 145 \\ {\sf Toulouse} & 3\,329 & 224\,516 & 1\,233 & 0.05 & 3\,734 & 1.12 & 111 & 542 & 147 \\ {\sf Palermo} & 2\,176 & 226\,215 & 1\,270 & 0.08 & 2\,559 & 1.18 & 90 & 384 & 123 \\ {\sf Bordeaux} & 3\,435 & 236\,595 & 1\,307 & 0.05 & 4\,026 & 1.17 & 98 & 668 & 211 \\ {\sf Antofagasta} & 650 & 293\,921 & 1\,097 & 0.41 & 963 & 1.48 & 51 & 327 & 94 \\ {\sf Detroit} & 5\,683 & 214\,863 & 1\,510 & 0.03 & 5\,946 & 1.05 & 206 & 647 & 100 \\ {\sf Winnipeg} & 5\,079 & 333\,882 & 1\,296 & 0.05 & 5\,846 & 1.15 & 84 & 818 & 259 \\ {\sf Brisbane} & 9\,645 & 392\,805 & 1\,283 & 0.03 & 11\,681 & 1.21 & 164 & 2\,306 & 607 \\ {\sf Adelaide} & 7\,548 & 404\,300 & 1\,270 & 0.04 & 9\,234 & 1.22 & 89 & 1\,992 & 524 \\ {\sf Dublin} & 4\,571 & 407\,240 & 1\,256 & 0.07 & 5\,537 & 1.21 & 81 & 1\,559 & 319 \\ {\sf Lisbon} & 7\,073 & 526\,179 & 1\,457 & 0.05 & 8\,817 & 1.25 & 101 & 2\,158 & - \\ {\sf Prague} & 5\,147 & 670\,423 & 1\,510 & 0.09 & 6\,714 & 1.30 & 67 & 2\,446 & 470 \\ {\sf Helsinki} & 6\,986 & 686\,457 & 1\,465 & 0.07 & 9\,022 & 1.29 & 74 & 2\,401 & 655 \\ {\sf Athens} & 6\,768 & 724\,851 & 1\,506 & 0.07 & 7\,978 & 1.18 & 131 & 1\,375 & 399 \\ {\sf Berlin} & 4\,601 & 1\,048\,218 & 1\,520 & 0.15 & 6\,600 & 1.43 & 46 & 2\,245 & 575 \\ {\sf Rome} & 7\,869 & 1\,051\,211 & 1\,506 & 0.09 & 10\,068 & 1.28 & 100 & 2\,519 & 686 \\ {\sf Melbourne} & 19\,493 & 1\,098\,227 & 1\,441 & 0.04 & 21\,434 & 1.10 & 254 & 2\,531 & 665 \\ {\sf Sydney} & 24\,063 & 1\,265\,135 & 1\,519 & 0.03 & 28\,695 & 1.19 & 115 & 5\,176 & 1511 \\ {\sf Paris} & 11\,950 & 1\,823\,872 & 1\,359 & 0.11 & 13\,726 & 1.15 & 159 & 3\,736 & 613 \\ \bottomrule \end{tabular} \end{table} \subsection{Baselines} In this subsection we discuss baseline approaches considered for comparison. Additionally, we present careful justification on why certain approaches used to solve temporal reachability problems fail to solve restless reachability problems. \mpara{Random (restless) walks.}\change{ Algorithmic approaches based on random walks can be used to estimate reachability in temporal graphs. The approach works by performing a random walk in a temporal graph and update reachability using the transitive closure property by respecting time constraints. More precisely, let $u, v$ and $w$ be distinct vertices. Now, if there exists a temporal walk from $u$ to $v$ ending at time $i$ and a temporal walk starting at time $j$ from $v$ to $w$ such that $i \leq j$, then there is a temporal walk from $u$ to $w$. Most reachability methods using temporal walks can be extended to estimate reachability with temporal paths, since a temporal walk can be transformed into a temporal path by removing loops in the walk. However, a similar approach of transforming reachability using restless walks to restless paths is not straightforward, since a restless walk cannot be transformed into a restless path by simply removing loops, as it may not satisfy waiting-time constraints (see Figure~\ref{fig:random-walk}).} \begin{figure} \tikzset{every picture/.style={scale=0.7}} \setlength{\tabcolsep}{25pt} \begin{tabular}{c c} \input{tikz/tikz-random-walk-1} & \input{tikz/tikz-random-walk-2} \\ \change{A restless walk} & \change{A temporal path (highlighted in blue)} \end{tabular} \caption{\label{fig:random-walk}\change{ An illustration of infeasibility to transform a restless walk to a restless path. On the left, a restless (temporal) walk $v_1~e_{v_1,v_2,1}~v_2~e_{v_2,v_3,2}~v_3~e_{v_3,v_4,3}~v_4~e_{v_4,v_2,4}~v_2~e_{v_2,v_5,5}~v_5$ from vertex $v_1$ to $v_5$, where resting time of vertices is $\delta(v_1)=\dots=\delta(v_5)=2$. On the right, a temporal path $v_1~e_{v_1,v_2,1}~v_2~e_{v_2,v_5,5}~v_5$ from $v_1$ to $v_5$ (highlighted in blue) obtained by removing the loop (highlighted in red). Observe that the obtained temporal path is not a restless path since the difference in edge timestamps entering and leaving $v_2$ is $4>\delta(v_2)=2$. In conclusion, even though there is a restless walk from $v_1$ to $v_5$, there exists no restless path from $v_1$ to $v_5$.}} \end{figure} \mpara{Temporal graph expansion.}\change{ A time-expansion of a temporal graph to a static directed graph has been applied to reduce temporal reachability to reachability questions in static directed graphs~\cite{mertzios2019temporal,WuC2016,zschoche2020complexity,sengupta2019arrow,CasteigtsHMZ2019}. Again, the approach can be used to solve reachability problems when vertices need to be connected via a restless walk, however, it fails to solve reachability problems when vertices must be connected via a restless path. Here, we describe a transformation of a temporal graph to a static directed graph which respects waiting-time restrictions called $\delta$-expansion, and describe the limitations of this approach. Let $G=(V,E)$ be a temporal graph with maximum timestamp $\tau$ and let $\delta:V \rightarrow \ensuremath{\mathbb{N}_{+}}\xspace$ be a vertex-dependent waiting time. The $\delta$-expansion of $G$ is a static directed graph $\deltaexp{G}=(V',E')$ where $V' =\bigcup_{t \in [\tau]} V^t$ for $V^t = \{v^t_i: v_i \in V, t \in [\tau]\}$ and $E' = \{(v^t_i,v^{t+\ell}_j):(v_i,v_j,t) \in E, \ell \in \{0, \dots, \delta(v_j)\}, t+\ell \leq \tau\}$. For an illustration, see Figure~\ref{fig:delta-expansion}. Observe that $|V'|= \tau\,|V|$ and $|E'|=(\Delta + 1)\,|E|$, where $\Delta = \max_{v_i \in V} \delta(v_i)$. Finally, note that $\deltaexp{G}$ can be computed efficiently.} \begin{figure} \tikzset{every picture/.style={scale=0.8}} \setlength{\tabcolsep}{25pt} \begin{tabular}{c c} \input{tikz/tikz-delta-expansion-1} & \input{tikz/tikz-delta-expansion-2} \\ \change{A temporal graph $G$} & \change{$\delta$-expansion of $G$} \end{tabular} \caption{\label{fig:delta-expansion} \change{ An illustration of $\delta$-expansion of temporal graph. On the left, a temporal graph $G=(V,E,\tau)$ with vertex set $V=\{v_1,\dots,v_5\}$, edge set $E=\{(v_1,v_2,1), (v_2,v_3,2), (v_3,v_4,3), (v_4,v_2,4), (v_2,v_5,5)\}$, maximum timestamp $\tau=5$ and resting time of vertices $\delta(v_1)=\dots=\delta(v_5)=2$. On the right, $\delta$-expansion $\deltaexp{G}$ of $G$. For each vertex $v_i \in V$, we introduce $\tau$ copies $v_i^1,\dots,v_i^\tau \in V'$, colored the same here. For each temporal edge $(v_i,v_j,t) \in E$, we introduce at most $\delta(v_j)$ static edges $\{(v^t_i,v^{t+\ell}_j): \ell \in \{0, \dots, \delta(v_j), t+\ell \leq \tau\}$. }} \end{figure} \change{ From the construction, it is easy to see that there exists a restless walk from vertex $v_i$ to $v_j$ in $G$ if and only if there exist a directed path from vertex $v^\ell_i$ to $v^{\ell'}_j$ in $\deltaexp{G}$ for some $\ell, \ell' \in [\tau]$ such that $\ell \leq \ell'$. Using $\delta$-expansion, we can use existing algorithmic approaches for solving reachability problems in static directed graphs to solve reachability problems where vertices must be connected via a restless walk. Observe that even though there exists a directed path from $v^1_1$ to $v^5_5$ in $\deltaexp{G}$, there is no restless path from $v_1$ to $v_5$ in $G$, so it is not straightforward to employ this approach to solve reachability problems when vertices must be connected via a restless path.} \mpara{Index construction.}\change{ In a $2$-hop labeling of static graphs, each vertex $v \in V$ is assigned a label-set pair $(\lin{v}, \lout{v})$ such that $v$ is reachable from each $u \in \lin{v} \subseteq V$ and each $w \in \lout{v} \subseteq V$ is reachable from $v$. From the transitive closure property, it follows that a vertex $v$ is reachable from a vertex $u$ if and only if $\lout{u} \cap \lin{v} \neq \emptyset$. Computing a $2$-hop labeling of minimum size is \ensuremath{\mathbf{NP}}\xspace-hard~\cite[Theorem~4.1]{cohen2003reachability}, while approximable within a logarithmic factor~\cite[Theorem~4.2]{cohen2003reachability}. The approach is extended to solve temporal reachability using a transformation to a directed acyclic graph (DAG)~\cite[Section~3]{wu2016reachability}. Here, the authors try to answer reachability questions in temporal graphs constrained by time intervals. More specifically, given two vertices $u,v \in V$ and timestamps $t_1, t_2 \in [\tau]$, the goal is to decide whether $v$ is reachable from $u$ via a temporal path (or a temporal walk) such that the timestamps of the edges in the path are in range $\{t_1,t_1+1,\dots,t_1+t_2\}$. A key difference in our reachability model is that the transition time of an edge can be zero which makes the $\delta$-expansion described in Figure~\ref{fig:delta-expansion} a static directed graph but not a DAG. Additionally, we established that even though two vertices are reachable via a directed path in the $\delta$-expansion, it does not imply that there exists a restless path connecting the vertices in the temporal graph. We would like to note that the \ensuremath{\text{\sc Restless\-Path}}\xspace problem is \ensuremath{\mathbf{NP}}\xspace-complete for all integers $\Delta \geq 1$ and $\tau \geq \Delta + 2$, even if there exists at most one temporal edge between any two vertices~\cite[Theorem~5]{CasteigtsHMZ2019}. So it is highly unlikely that there exists a straightforward extension of $2$-hop cover to solve the \ensuremath{\text{\sc Restless\-Path}}\xspace problem even if we constrain time intervals. } \mpara{Parameterized (exact) algorithms.}\change{ Casteigts et al.~\cite{CasteigtsHMZ2019} presented algorithms for solving the \ensuremath{\text{\sc Restless\-Path}}\xspace problem parameterized by the feedback edge number of the underlying graph and the timed feedback vertex number (TFVN) of the temporal graph. Additionally, they showed that the TFVN of the temporal graph is lower bounded by the FVN of the underlying graph. For a temporal graph $G=(V,E)$ with maximum timestamp $\tau$, the \emph{timed feedback vertex set} of $G$ is a set $F \subseteq V \times [\tau]$ of vertex appearances such that $\ulg{(G-F)}$ is acyclic, where $G-F = (V,E')$ such that $E'=E \setminus \{(u,v,i) \in E: (v,i) \in F~\text{or}~(v,i)~\in F\}$ and $\ulg{(G-F)}$ is the underlying graph of $(G-F)$. The {\em timed feedback vertex number} of a temporal graph $G$ is the minimum cardinality of a timed feedback vertex set of $G$. From the statistics in Table~\ref{table:exp:datasets}, it is clear that the values of FVN and FEN are orders of magnitude greater than the diameter of the graph, for most datasets. Most importantly, it appears difficult to change the value of the parameters FEN and FVN, whereas the length of the restless path $k$ to be found can be readily varied. Indeed, as we will see, such an approach leads to a solution scaling to graphs with millions of temporal edges provided that the parameter $k$ remains small enough. } \mpara{Exhaustive search (baseline).} Finally, we consider an exhaustive search algorithm based on temporal depth-first-search ({\sc\large dfs}), which a parameterized algorithm with respect to the maximum degree of the graph $d_{\max}$. We perform temporal {\sc\large dfs} starting from a source~$s$ by respecting waiting-time constraints and restrict the depth of the search to $k$. We report the minimum reachability time for the vertices that are reachable from~$s$ by at most $k-1$ hops. The time complexity of the exhaustive search algorithm is $\ensuremath{\mathcal{O}}\xspace(d_{\text{max}}^k)$. As demonstrated in previous work~\cite{Thejaswi2020pattern, thejaswi2020finding}, and also shown in our experiments (see Subsection~\ref{sec:experiments:results}), the exhaustive search does not scale for large scale-free graphs. In particular, many real-world graphs exhibit a power-law degree distribution, or more generally, scale-free structure. However, the exhaustive search algorithm is highly practical for some structured graphs such as graphs that are close to being $d$-regular with small maximum degree. In our experiments, we refer the exhaustive search algorithm as the {\em baseline}. \mpara{Discussion.} We stress that our focus is on exact computation of restless reachability. As such, we do not compare our proposed algorithms to probabilistic methods, heuristics or approximation schemes. Further, to the best of our knowledge, there is no publicly available implementation for solving the restless reachability problem that scales to large graphs such as those considered in our experiments. For instance, we argue that the algorithms presented by~\citet{CasteigtsHMZ2019} are unlikely to perform adequately in practice given their exponential dependency on a structural parameter that, in many real-world networks, has a high value (see Table~\ref{table:exp:datasets}). \change{In addition, it is not immediate how index computation techniques such as 2-hop or 3-hop covers or location based indexing would extend to solve restless reachability.} Finally, a careful reader might question our focus on \emph{exact computation} by recalling that our algorithm has a false negative probability of $(2k-1)/2^b$. However, by fixing a suitable value for $b$ and potentially running our method multiple times, we can make this probability arbitrarily close to zero. For concreteness, we choose $b=64$ for our experiments, which means that when say $k=10$, the per-vertex false negative probability is less than $2^{59} \approx 5.76 \cdot 10^{-17}$. In comparison, a modern consumer CPU running for at least five days has a 1 in 330 chance of a hardware failure due a machine-check exception, a 1 in 470 chance of a disk subsystem failure, and 1 in 2700 ($\approx 3.7 \cdot 10^{-4}$) chance of a DRAM memory failure~\cite[Figure~2]{nightingale2011cycles}, all significantly more likely than our algorithm making an error. \subsection{Experimental results} \label{sec:experiments:results} In this section we report our experimental results. The experiments are designed to study the following aspects: ($i$)~scalability of the algorithm to graphs with up to 10 million edges on the workstation configuration; ($ii$)~scalability of the algorithm to large graphs with up to one billion edges on the compute\-node configuration; ($iii$)~computing restless reachability in real-world datasets; and ($iv$)~a case study investigating the effectiveness of different vertex-selection strategies to act as barriers and minimize the spread of diffusion processes (e.g., infectious diseases) through the temporal network. \change{An overview of our experiments is available in Table~\ref{table:exp:results:0}.} In our experimental results, run\-time refers to the empirical running time and memory refers to the peak-memory usage of our implementation. \begin{table}[t] \caption{\change{Overview of the experimental results. Here $n$ is the number of vertices, $m$ is the number of edges, $d=\frac{m}{n}$ is the average degree, $k$ is the length of path, $\Delta$ is maximum resting time, $\delta$ is the function mapping vertices to resting time, maximum timestamp $\tau = 100$ (fixed) and percentage of vertices considered as separators `Sep (\%)'. For power-law graphs we use $\alpha=-1.0$ (fixed) and $w = 100$ (fixed). Recall that for a positive integer $k$ we write $[k]=\{1,\dots,k\}$. }} \label{table:exp:results:0} \centering \footnotesize \begin{tabular}{l r r r r r r r} \toprule Experiment & \multicolumn{1}{c}{$n$} & \multicolumn{1}{c}{$m$} & \multicolumn{1}{c}{$d$} & \multicolumn{1}{c}{$k$} & \multicolumn{1}{c}{$\Delta$} & \multicolumn{1}{c}{$\delta$} & \multicolumn{1}{c}{Sep (\%)} \\ \midrule \multicolumn{2}{l}{\em {Figure~\ref{fig:exp:scalability}}}\\ \cmidrule(r{1em}){1-1} {\sf left} & $10^2,\dots,10^5$ & $10^4,\dots,10^7$ & $10^2$ & $10$ & $10$ & $V \rightarrow \{10\}$ & - \\ {\sf center-left} & $10^3$ & $10^5$ & $10^2$ & $5,\dots,15$ & $10$ & $V \rightarrow \{10\}$ & - \\ {\sf center-right} & $10^5$ & $10^7$ & $10^2$ & $10$ & $10,20,\dots,100$ & $V \rightarrow \{\Delta\}$ & - \\ {\sf right} & $10^5,\dots,10^2$ & $10^6$ & $10,\dots,10^4$ & $10$ & $10$ & $V \rightarrow \{10\}$ & - \\ \midrule \multicolumn{2}{l}{\em {Figure~\ref{fig:exp:extraction}}}\\ \cmidrule(r{1em}){1-1} {\sf left, center} & $10^3,\dots,10^7$ & $10^5,\dots,10^9$ & $10^2$ & $10$ & $10$ & $V \rightarrow \{10\}$ & - \\ {\sf right} & $10^2,\dots,10^5$ & $10^4,\dots,10^7$ & $10^2$ & $10$ & $10$ & $V \rightarrow \{10\}$ & - \\ \midrule \multicolumn{2}{l}{\em {Real-world graphs}}\\ \cmidrule(r{1em}){1-2} {\sf {Table~\ref{table:exp:realworld:1}}} & - & - & - & $5$ & $10$ & $V \rightarrow \{10\}$ & - \\ {\sf {Table~\ref{table:exp:realworld:2}}} & - & - & - & $10$ & $10$ & $V \rightarrow \{10\}$ & - \\ {\sf {Table~\ref{table:exp:realworld:3}}} & - & - & - & $10$ & $5,10$ & $V \rightarrow \{\Delta\}$ & - \\ {\sf {Figure~\ref{fig:exp:reachability:1}}} & - & - & - & $10$ & $5,20$ & $V \rightarrow [\Delta]$ & - \\ \midrule \multicolumn{2}{l}{\em {Case study} (Socio-patterns)}\\ \cmidrule(r{1em}){1-2} {\sf {Figure~\ref{fig:exp:immunization:1}}} & - & - & - & $10$ & $10$ & $V \rightarrow [10]$ & $5$ \\ {\sf {Figure~\ref{fig:exp:immunization:2}}} & - & - & - & $10$ & $10$ & $V \rightarrow [10]$ & $25$ \\ {\sf {Figure~\ref{fig:exp:immunization:3}}} & - & - & - & $10$ & $10$ & $V \rightarrow [10]$ & $5,10,25$ \\ \bottomrule \end{tabular} \end{table} \spara{Scalability.} To demonstrate the scalability of the algorithm we experiment with synthetic graphs. In Figure~\ref{fig:exp:scalability} (left), we compare the run\-time as a function of the number of edges for the fine-grained oracle and the baseline. The experiments are performed on five independent random power-law graphs for each configuration of $n=10^2,\dots,10^5$ with fixed values of $d=100$, $k=10$, $\tau=100$, $\Delta=10$, $\delta:V \rightarrow \{\Delta\}$, $\alpha=-1.0$, and $w=100$. We observe a linear increase in the run\-time with the the number of edges, as predicted by the theoretical analysis. In Figure~\ref{fig:exp:scalability} (center-left), we compare the run\-time as a function of the length of the restless path for the fine-grained oracle and the baseline. The experiments are performed on five independent random power-law graphs for each configuration of $k=5,\dots,15$, with fixed values of $n=10^3$, $d=100$, $\tau=100$, $\Delta=10$, $\delta:V \rightarrow \{\Delta\}$, $\alpha=-1.0$, and $w=100$. We observe an exponential increase in the run\-time with the increase in length of the restless path, as predicted by the theoretical analysis. The source vertex is chosen uniformly at random. The variance in run\-time between the independent graph inputs is very small for the algebraic algorithm as compared to the baseline, which exhibit high variance in run\-time. We observe that our baseline fails to report the solution for power-law graphs with $n=10^3$, $m=10^6$, and $k=10$. Note that we terminate experiments that take more than ten hours. The run\-time of the exhaustive search algorithm depends on the degree distribution of the graph: if the temporal {\sc\large dfs} visits a high-degree vertex then the baseline algorithm takes long time to complete the execution. However, the baseline is efficient for sparse $d$-regular graphs, where the maximum degree is small. Again, for scaling with respect to the length of the restless path our baseline failed to report a solution for $k \ge 10$. We terminate the experiments, which take more than ten hours of run\-time. Our implementation can handle the \ensuremath{k \text{\sc -Restless\-Reach}}\xspace problem on a graph instance with one million nodes, ten million edges, and path length $k=10$, in less than 20 minutes using less than 2~gigabytes of working memory on the workstation configuration. In Figure~\ref{fig:exp:scalability} (center-right), we report the run\-time of the algorithm as a function of the maximum resting time $\Delta$. The experiments are performed on five independent random power-law graphs for each configuration of $\Delta=10,20,\dots,100$, $\delta:V \rightarrow \{\Delta\}$ with fixed values of $n=10^5$, $d=100$, $\tau=100$, $\alpha=-1.0$, $w=100$, and $k=10$. We do not observe a linear-scaling of the run\-time as the theoretical analysis tells us. A possible explanation is that the graphs used for the experiments are sparse, and there is not enough workload to saturate the empirical arithmetic and memory bandwidth of the hardware, simultaneously. However, with the increase in the resting time $\Delta$ we need to perform more arithmetic operations there by improving the arithmetic and memory bandwidth. This is due to the fact that, the implementation enables more streamlining of the memory and arithmetic pipeline of the computer hardware when there is enough workload to parallelize. Our final scalability experiments report the effect of the graph density on scalability. In Figure~\ref{fig:exp:scalability} (right), we report the run\-time of the algorithm as a function of the graph density. Density of the graph is the ratio of number of edges and the number of vertices. The experiments are executed on five independent random power-law graphs for each configuration of $d=10,10^2,10^3,10^4$ and corresponding values of $n=10^5,10^4,10^3,10^2$, with fixed values of $m=10^6$, $\tau=100$, $\Delta=10$, $\delta:V \rightarrow \{\Delta\}$, and $k=10$. We observe that our implementation performs better for dense graphs. Again a possible explanation is that for sparse graphs there is not enough work to keep both the arithmetic and memory pipeline busy, simultaneously. This also presents us a challenge to design an efficient implementation for handling sparse graphs. All experiments are executed on the workstation configuration using all cores with directed graphs. Note that we demonstrated the scalability of the algorithm for \ensuremath{k \text{\sc -Restless\-Reach}}\xspace problem instances, however for other problem instances the run\-times are similar. \begin{figure}[] \centering \setlength{\tabcolsep}{0.01cm} \renewcommand{\arraystretch}{0.01} \begin{tabular}{c c c c} \includegraphics[width=0.25\linewidth]{fig/Corei5_edge_scaling_finegrain-oracle_runtime.pdf} & \includegraphics[width=0.25\linewidth]{fig/Corei5_path-length_scaling_finegrain-oracle_runtime.pdf}& \includegraphics[width=0.25\linewidth]{fig/Corei5_resting-time_scaling_finegrain-oracle_runtime.pdf} & \includegraphics[width=0.25\linewidth]{fig/Corei5_degree_scaling_finegrain-oracle_runtime.pdf} \end{tabular} \caption{\label{fig:exp:scalability Scalability in synthetic graphs. FG-oracle is fine-grained oracle. } \end{figure} \spara{Extracting an optimal solution.} Our second set of experiments compares the run\-time of the algorithm for extracting an optimal restless path between a source and a destination using the decision oracle and the fine-grained oracle. Recall that the algorithm only returns a {\sc\large yes}/{\sc\large no} answer for the existence of a solution and we need multiple queries to the oracle to obtain a solution. Using a decision oracle we require $\ensuremath{\mathcal{O}}\xspace(k \log n \log \tau)$ queries in expectation to obtain an optimum solution as compared to $k$ queries using a fine-grained oracle (see Section \ref{sec:algo:extraction}). In Figure~\ref{fig:exp:extraction} we compare the run\-time (left) and the peak-memory usage (center) of the decision oracle and the fine-grained oracle for extracting an optimum solution for five independent random power-law graphs for each configuration of $n=10^3,\dots,10^7$ with fixed values of $d=100$, $\tau=100$, $\Delta=10$, $\delta: V \rightarrow \{\Delta\}$ and $k=10$. The source and the destination are chosen at random. We observe little variance in run\-time for the fine-grained extraction as compared to oracle extraction. For large graphs with hundred million edges the fine-grained extraction is up to four times faster than the oracle extraction. Even though in theory we reduce the number of queries by a factor of $\log n \log \tau$, in practice we do not obtain a significant improvement in the empirical run\-time. When extracting a solution using the decision oracle, recall that for each query of the oracle we recursively divide the graph into smaller subgraphs. For each smaller subgraph, we build the multilinear sieve and thereby reduce the empirical runtime of each query. In addition, while the the expected number of queries is bounded by $\ensuremath{\mathcal{O}}\xspace(k \log n \log \tau)$ in worst case, this bound is not always met in practice. For a given instance, the number of queries required to extract a $k$-vertex subgraph varies depending on the source and the destination, resulting in high variance in the extraction time for extraction via self-reducibility. However, there is considerably less variance in the runtime of the fine-grained extraction approach. The experiments are executed on the compute\-node configuration using all cores. We report the run\-time of extraction for the \ensuremath{k\text{\sc-Restless\-Motif}}\xspace instances, but the run\-times are similar for the \ensuremath{k \text{\sc-Restless\-Path}}\xspace instances. \spara{Graph topology.} Here we study the effect of graph topology on run\-time of the algorithm. In Figure~\ref{fig:exp:extraction} (right), we report the run\-time of the algorithm for five independent $d$-regular random graph instances for each configuration of $n=10^2,\dots,10^5$, $d=100$, $\tau=100$, $\Delta=10$, $\delta: V \rightarrow \{\Delta\}$, and $k=10$. Power-law graphs with $n=10^2,\dots,10^6$ with fixed values of $d=100$, $k=10$, $\tau=100$, $\Delta=10$, $\delta:V \rightarrow \{\Delta\}$, $\alpha=-1.0$, and $w=100$. We observe no significant change in the run\-time with the change in the graph topology. The experiments are executed on the workstation using all cores. We report the run\-time for the \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace problem instances, but the run\-times are similar for other problem instances. \begin{figure}[] \centering \setlength{\tabcolsep}{0.01cm} \renewcommand{\arraystretch}{0.01} \begin{tabular}{c c c} {\bf ~~~~~Extracting a solution} & {\bf ~~~~Memory usage} & {\bf ~~~~Graph topology}\\ \includegraphics[width=0.32\linewidth]{fig/Xeon_edge_scaling_finegrain-extraction_runtime.pdf} & \includegraphics[width=0.32\linewidth]{fig/Xeon_edge_scaling_finegrain-extraction_memory.pdf} & \includegraphics[width=0.32\linewidth]{fig/Corei5_edge_scaling_finegrain-decision_graphtypes.pdf} \end{tabular} \caption{\label{fig:exp:extraction Extracting a solution and topology invariance. OR-extract is solution extraction using decision oracle and FG-extract is solution extraction using fine-grained oracle. } \end{figure} \spara{Experiments with real-world graphs.} Our next set of experiments reports the runtime of the algorithm for finding restless reachability and extracting a restless path in real-world datasets. The description of the datasets used for our experiments is available in Section~\ref{sec:exp:setup}. In Table~\ref{table:exp:realworld:1} and \ref{table:exp:realworld:2} we report the run\-time for finding restless reachability in real-worlds graphs with $k=5$ and $k=10$, respectively. For each dataset we report the maximum run\-time of five independent runs by choosing the source vertex $s \in V$ uniformly at random for each $k \in \{5,10\}$, for fixed value of the maximum resting time $\Delta=10$, and $\delta: V \rightarrow \{\Delta\}$, i.e., the resting time is constant for all the vertices except the source $s$, which has the maximum resting time $\delta(s) = \tau$. In Column~2 we report the run\-time for solving the \ensuremath{k \text{\sc -Restless\-Reach}}\xspace problem, while Column~3 reports the run\-time for solving the {\sc Restless\-Reach}\xspace problem by restricting the path length to $k-1$. Note that here we solve the \ensuremath{\textit{atm-} k \text{\sc -Restless\-Reach}}\xspace problem where we find the set of vertices that are reachable from a given source via a restless path with length at most $k-1$. Column~4 is the ratio of Column~3 and Column~2. Next, in Columns~5 and 6 we report the run\-time of extracting a solution using a decision oracle and a fine-grained oracle, respectively. Column~7 is the ratio of Column~6 and Column~5. Finally, in Column~8, we report the peak memory usage of the fine-grained extraction. All run\-times are in seconds. The experiments are executed on compute\-node configuration using all cores. We can solve restless reachability in each real-world graph dataset in Table~\ref{table:exp:datasets} in less than one minute by restricting the length of the restless path $k$ to~5, and in less than two hours using at most 14~Gb of memory for $k=10$. For instance, we can solve restless reachability by limiting $k$ to $10$ in a real-world graph dataset with more than 37 million directed edges and more than 19 thousand timestamps in less than one hour on a Haswell desktop using less than 6~Gb of memory. The reported run\-times are in seconds. From the results (see Column~3), we see that solving \ensuremath{\textit{atm-} k \text{\sc -Restless\-Reach}}\xspace takes less than twice the empirical running time than that of \ensuremath{k \text{\sc -Restless\-Reach}}\xspace, in most of the input graph instance. Extracting a solution using fine-grained extraction is effective for large graphs, given that $k$ is not too large. For instance, we obtain an 8-time speedup in computation using fine-grained extraction as compared to oracle extraction in a graph with more than hundred thousand vertices and more than eight hundred thousand edges with $k=10$. \begin{table}[t] \caption{Experiments with real-world datasets ($k=5$). For a description of the columns, see the main text. } \label{table:exp:realworld:1} \centering \footnotesize \setlength{\tabcolsep}{0.1cm} \begin{tabular}{l r r r r r r r} \toprule & \multicolumn{3}{c}{{\em Reachability}} & \multicolumn{3}{c}{{\em Extraction} ($k=5$)} & \\ \cmidrule(lr{1em}){2-4} \cmidrule(lr{1em}){5-7} & \multicolumn{1}{c}{$k=5$} & \multicolumn{1}{c}{$k \le 5$} & \multicolumn{1}{c}{Ratio} & \multicolumn{1}{c}{Fine-grained} & \multicolumn{1}{c}{Decision} & \multicolumn{1}{c}{Speedup} & \multicolumn{1}{c}{Memory} \\ Dataset & \multicolumn{1}{c}{(seconds)} & \multicolumn{1}{c}{(seconds)} & & \multicolumn{1}{c}{(seconds)} & \multicolumn{1}{c}{(seconds)} & & \multicolumn{1}{c}{(Gb)} \\ \midrule {\em {Copenhagen}}\\ \cmidrule(r{1em}){1-1} {\sf Calls} & 1.72 & 2.66 & 1.55 & 1.71 & 1.80 & 1.05 & 0.48 \\ {\sf SMS} & 1.91 & 2.59 & 1.36 & 1.84 & 1.88 & 1.02 & 0.48 \\ \midrule {\em {Socio-patterns}}\\ \cmidrule{1-1} {\sf LH10} & 8.18 & 13.06 & 1.60 & 8.24 & 8.27 & 1.00 & 3.28 \\ {\sf InVS13} & 25.78 & 39.93 & 1.55 & 25.42 & 25.45 & 1.00 & 6.95 \\ {\sf InVS15} & 39.21 & 59.38 & 1.51 & 42.30 & 38.36 & 0.91 & 13.18 \\ {\sf SFHH} & 6.91 & 10.36 & 1.50 & 7.18 & 8.45 & 1.18 & 1.47 \\ {\sf LyonSchool} & 22.39 & 32.56 & 1.45 & 22.58 & 27.33 & 1.21 & 1.70 \\ {\sf Thiers13} & 51.76 & 73.39 & 1.42 & 51.46 & 55.27 & 1.07 & 5.38 \\ \midrule {\em {Koblenz}}\\ \cmidrule(r{1em}){1-1} {\sf sqwikibooks} & 1.63 & 3.60 & 2.21 & 1.69 & 2.14 & 1.27 & 0.85 \\ {\sf pswiktionary} & 6.42 & 10.67 & 1.66 & 6.84 & 7.28 & 1.06 & 3.70 \\ {\sf sawikisource} & 9.96 & 17.21 & 1.73 & 13.60 & 16.63 & 1.22 & 6.58 \\ {\sf knwiki} & 21.42 & 31.50 & 1.47 & 23.68 & 25.22 & 1.06 & 12.27 \\ {\sf epinions} & 7.76 & 12.41 & 1.60 & 7.44 & 24.36 & 3.27 & 3.57 \\ \midrule {\em {Transport}}\\ \cmidrule(r{1em}){1-1} {\sf Kuopio} & 0.49 & 0.78 & 1.57 & 0.51 & 0.86 & 1.70 & 0.10 \\ {\sf Rennes} & 0.76 & 1.45 & 1.92 & 0.74 & 1.21 & 1.63 & 0.25 \\ {\sf Grenoble} & 0.88 & 1.41 & 1.60 & 0.86 & 1.25 & 1.45 & 0.29 \\ {\sf Venice} & 1.03 & 1.63 & 1.58 & 1.33 & 1.39 & 1.05 & 0.39 \\ {\sf Belfast} & 0.82 & 2.31 & 2.81 & 0.89 & 1.31 & 1.47 & 0.31 \\ {\sf Canberra} & 1.08 & 1.73 & 1.59 & 1.07 & 1.57 & 1.47 & 0.43 \\ {\sf Turku} & 0.86 & 1.51 & 1.75 & 0.95 & 1.31 & 1.38 & 0.33 \\ {\sf Luxembourg} & 0.86 & 1.19 & 1.38 & 0.97 & 1.20 & 1.24 & 0.24 \\ {\sf Nantes} & 1.27 & 1.96 & 1.54 & 1.28 & 1.42 & 1.11 & 0.43 \\ {\sf Toulouse} & 1.37 & 2.32 & 1.69 & 1.52 & 1.94 & 1.28 & 0.59 \\ {\sf Palermo} & 1.25 & 1.86 & 1.49 & 1.30 & 1.57 & 1.21 & 0.40 \\ {\sf Bordeaux} & 1.71 & 2.64 & 1.54 & 1.70 & 1.94 & 1.14 & 0.64 \\ {\sf Antofagasta} & 0.70 & 0.87 & 1.23 & 0.68 & 1.58 & 2.34 & 0.11 \\ {\sf Detroit} & 2.63 & 4.13 & 1.57 & 2.50 & 2.93 & 1.17 & 1.22 \\ {\sf Winnipeg} & 2.33 & 3.33 & 1.43 & 2.31 & 2.69 & 1.17 & 0.94 \\ {\sf Brisbane} & 3.92 & 5.62 & 1.43 & 3.77 & 4.12 & 1.09 & 1.76 \\ {\sf Adelaide} & 3.22 & 4.72 & 1.47 & 3.04 & 3.58 & 1.18 & 1.36 \\ {\sf Dublin} & 2.10 & 3.04 & 1.45 & 2.04 & 2.50 & 1.23 & 0.82 \\ {\sf Lisbon} & 3.36 & 5.27 & 1.57 & 3.20 & 3.69 & 1.15 & 1.47 \\ {\sf Prague} & 3.11 & 4.52 & 1.45 & 2.95 & 3.21 & 1.09 & 1.11 \\ {\sf Helsinki} & 3.69 & 5.06 & 1.37 & 3.49 & 3.97 & 1.14 & 1.46 \\ {\sf Athens} & 3.54 & 6.29 & 1.78 & 3.40 & 3.91 & 1.15 & 1.46 \\ {\sf Berlin} & 2.95 & 3.93 & 1.33 & 3.31 & 3.69 & 1.11 & 1.01 \\ {\sf Rome} & 4.59 & 6.01 & 1.31 & 4.44 & 4.99 & 1.13 & 1.70 \\ {\sf Melbourne} & 8.24 & 12.61 & 1.53 & 8.56 & 8.18 & 0.96 & 4.00 \\ {\sf Sydney} & 12.15 & 17.98 & 1.48 & 11.10 & 11.39 & 1.03 & 5.20 \\ {\sf Paris} & 7.98 & 10.72 & 1.34 & 7.54 & 7.44 & 0.99 & 2.33 \\ \bottomrule \end{tabular} \end{table} \begin{table}[t] \caption{Experiments with real-world datasets ($k=10$). For description of the columns, please see the main text. } \label{table:exp:realworld:2} \centering \footnotesize \setlength{\tabcolsep}{0.1cm} \begin{tabular}{l r r r r r r r} \toprule & \multicolumn{3}{c}{{\em Reachability}} & \multicolumn{3}{c}{{\em Extraction} ($k=10$)} & \\ \cmidrule(lr{1em}){2-4} \cmidrule(lr{1em}){5-7} & \multicolumn{1}{c}{$k=10$} & \multicolumn{1}{c}{$k \le 10$} & \multicolumn{1}{c}{Ratio} & \multicolumn{1}{c}{Fine-grained} & \multicolumn{1}{c}{Decision} & \multicolumn{1}{c}{Speedup} & \multicolumn{1}{c}{Memory} \\ Dataset & \multicolumn{1}{c}{(seconds)} & \multicolumn{1}{c}{(seconds)} & & \multicolumn{1}{c}{(seconds)} & \multicolumn{1}{c}{(seconds)} & & \multicolumn{1}{c}{(Gb)} \\ \midrule {\em {Copenhagen}}\\ \cmidrule(r{1em}){1-1} {\sf Calls} & 88.98 & 152.91 & 1.72 & 90.60 & 194.03 & 2.14 & 0.48 \\ {\sf SMS} & 89.32 & 153.67 & 1.72 & 88.36 & 195.87 & 2.22 & 0.48 \\ \midrule {\em {Socio-patterns}}\\ \cmidrule{1-1} {\sf LH10} & 411.13 & 719.49 & 1.75 & 417.43 & 532.08 & 1.27 & 3.28 \\ {\sf InVS13} &1\,292.91 &2\,342.52 & 1.81 &1\,309.36 &1\,613.37 & 1.23 & 6.95 \\ {\sf InVS15} &1\,871.23 &3\,414.07 & 1.82 &1\,966.12 &2\,155.92 & 1.10 & 13.18 \\ {\sf SFHH} & 314.48 & 569.10 & 1.81 & 318.29 & 581.37 & 1.83 & 1.47 \\ {\sf LyonSchool} &1\,284.53 &2\,294.68 & 1.79 &1\,298.16 &1\,849.85 & 1.42 & 1.70 \\ {\sf Thiers13} &2\,666.22 &4\,687.66 & 1.76 &2\,663.80 &3\,233.05 & 1.21 & 5.38 \\ \midrule {\em {Koblenz}}\\ \cmidrule(r{1em}){1-1} {\sf sqwikibooks} & 70.78 & 131.26 & 1.85 & 72.20 & 257.57 & 3.57 & 0.85 \\ {\sf pswiktionary} & 267.32 & 478.48 & 1.79 & 283.14 & 909.79 & 3.21 & 3.71 \\ {\sf sawikisource} & 464.38 & 856.73 & 1.84 & 495.80 &1\,450.61 & 2.93 & 6.59 \\ {\sf knwiki} & 909.25 &1\,659.58 & 1.83 & 969.38 &2\,995.04 & 3.09 & 12.28 \\ {\sf epinions} & 286.11 & 522.78 & 1.83 & 375.55 &3\,051.37 & 8.13 & 3.58 \\ \midrule {\em {Transport}}\\ \cmidrule(r{1em}){1-1} {\sf Kuopio} & 25.08 & 43.45 & 1.73 & 25.42 & 116.30 & 4.58 & 0.10 \\ {\sf Rennes} & 32.15 & 59.12 & 1.84 & 34.24 & 161.09 & 4.71 & 0.25 \\ {\sf Grenoble} & 38.38 & 68.99 & 1.80 & 39.15 & 155.41 & 3.97 & 0.29 \\ {\sf Venice} & 50.07 & 84.05 & 1.68 & 49.62 & 176.52 & 3.56 & 0.39 \\ {\sf Belfast} & 36.29 & 69.19 & 1.91 & 39.32 & 172.56 & 4.39 & 0.31 \\ {\sf Canberra} & 48.00 & 86.93 & 1.81 & 48.93 & 182.02 & 3.72 & 0.43 \\ {\sf Turku} & 39.46 & 75.04 & 1.90 & 43.81 & 158.19 & 3.61 & 0.33 \\ {\sf Luxembourg} & 37.15 & 65.73 & 1.77 & 39.68 & 140.88 & 3.55 & 0.24 \\ {\sf Nantes} & 51.82 & 87.37 & 1.69 & 52.35 & 150.44 & 2.87 & 0.43 \\ {\sf Toulouse} & 62.96 & 113.45 & 1.80 & 62.54 & 203.01 & 3.25 & 0.59 \\ {\sf Palermo} & 47.20 & 93.09 & 1.97 & 52.74 & 198.76 & 3.77 & 0.40 \\ {\sf Bordeaux} & 67.52 & 124.61 & 1.85 & 69.16 & 208.33 & 3.01 & 0.64 \\ {\sf Antofagasta} & 23.72 & 41.53 & 1.75 & 25.26 & 112.66 & 4.46 & 0.11 \\ {\sf Detroit} & 111.74 & 201.14 & 1.80 & 107.84 & 288.48 & 2.68 & 1.22 \\ {\sf Winnipeg} & 88.13 & 162.17 & 1.84 & 93.29 & 231.43 & 2.48 & 0.94 \\ {\sf Brisbane} & 147.66 & 268.12 & 1.82 & 153.42 & 320.82 & 2.09 & 1.76 \\ {\sf Adelaide} & 122.11 & 221.79 & 1.82 & 124.29 & 312.47 & 2.51 & 1.37 \\ {\sf Dublin} & 78.42 & 142.13 & 1.81 & 82.51 & 205.09 & 2.49 & 0.82 \\ {\sf Lisbon} & 134.25 & 246.37 & 1.84 & 137.01 & 332.89 & 2.43 & 1.47 \\ {\sf Prague} & 108.59 & 199.35 & 1.84 & 107.47 & 245.90 & 2.29 & 1.11 \\ {\sf Helsinki} & 130.68 & 231.65 & 1.77 & 136.54 & 319.97 & 2.34 & 1.46 \\ {\sf Athens} & 129.10 & 233.02 & 1.80 & 130.00 & 324.98 & 2.50 & 1.46 \\ {\sf Berlin} & 102.28 & 179.79 & 1.76 & 105.72 & 233.19 & 2.21 & 1.01 \\ {\sf Rome} & 159.08 & 287.87 & 1.81 & 164.57 & 368.35 & 2.24 & 1.70 \\ {\sf Melbourne} & 323.32 & 590.11 & 1.83 & 337.50 & 631.20 & 1.87 & 4.00 \\ {\sf Sydney} & 411.24 & 732.24 & 1.78 & 427.51 & 866.15 & 2.03 & 5.20 \\ {\sf Paris} & 223.02 & 403.70 & 1.81 & 224.21 & 477.10 & 2.13 & 2.33 \\ \bottomrule \end{tabular} \end{table} \spara{Reachability.} Our next set of experiments studies the restless reachability in socio-patterns dataset. In particular we solve the \ensuremath{\textit{atm-} k \text{\sc -Restless\-Reach}}\xspace problem where we find the set of vertices reachable from a given source via a restless path of length at most $k-1$. \emph{Reachability} is the ratio of the number of vertices that are reachable with a restless path to the total number of vertices. In Figure~\ref{fig:exp:reachability:1} we report the variance and mean of reachability as a time-series for five independent graph instances for each dataset with $\Delta=5$ (top-row) and $\Delta=20$ (bottom-row). More precisely, for a given dataset we generate five graph instances by choosing a source vertex uniformly at random and assign the resting times uniformly at random in the range $[\Delta]$. We limit the length of the restless path to $9$, i.e., $k = 10$ and solve the \ensuremath{\textit{atm-} k \text{\sc -Restless\-Reach}}\xspace problem. \iffalse \note{The results for $\Delta=5$ and $\Delta=10$ look very similar. Would it make sense to replace results for $\Delta=10$ with $\Delta=50$ or $\Delta=100$, so that one can appreciate the differences? } \fi We observe high variance in reachability among the independent source vertices for {\sf LH10}, {\sf InVS15}, {\sf LyonSchool}, and {\sf Thiers13} datasets, and smaller variance for {\sf InVS13} and {\sf SFHH}. We also see that in all datasets, except {\sf LH10}, reachability approaches its maximum value~1, within the total number of timestamps available in each dataset, however, this happens at different times for each dataset, and with a different pace. \iffalse Note that, we choose five source vertices uniformly at random for each dataset and the source vertices remain the same across all the experiments for a given dataset. For a given dataset, the resting time of each vertex remains the same across the experiments. \fi \begin{figure*}[t] \centering \includegraphics[width=1.0\linewidth]{fig/Corei5-datasets-reachability-varience-rt20-3.pdf} \caption{\label{fig:exp:reachability:1 Restless reachability in real-world datasets with $\Delta=5$ (top-row) and $\Delta=20$ (bottom-row) with $\delta:V \rightarrow [\Delta]$ assigned uniformly at random, and $k = 10$ (fixed). } \end{figure*} In Table~\ref{table:exp:realworld:3}, we report the runtime for solving the \ensuremath{\textit{atm-} k \text{\sc -Restless\-Reach}}\xspace problem in socio-patterns datasets. The reported runtime is the maximum of five independent runs by choosing the source vertex $s \in V$ uniformly at random with $k=10$ (fixed) and $\Delta=5, 10$, $\delta: V \rightarrow \{\Delta\}$ (fixed). The resting time is constant for all the vertices except the source $s$, which has the maximum resting time $\delta(s) = \tau$. For instance, we can solve \ensuremath{k \text{\sc -Restless\-Reach}}\xspace problem by limiting $k=10$ in a real-world graph dataset with more than 37 million directed edges and more than 19 thousand timestamps in less than one hour on workstation configuration using less than 6~Gb of memory. The reported runtimes are in seconds. \begin{table}[t] \caption{Computing restless reachability in socio-patterns dataset using the workstation configuration. We report runtime for solving \ensuremath{\textit{atm-} k \text{\sc -Restless\-Reach}}\xspace problem with $k=10$ (fixed).} \label{table:exp:realworld:3} \centering \footnotesize \setlength{\tabcolsep}{0.1cm} \begin{tabular}{l r r r r r} \toprule Dataset & $n$ & $m$ & $\tau$ & \multicolumn{1}{c}{$\Delta=5$} & \multicolumn{1}{c}{$\Delta=10$}\\ & & & & (seconds) & (seconds)\\ \midrule {\sf LH10} & 73 & 300\,252 & 12\,960 & 156.8\,s & 158.7\\ {\sf InVS13} & 95 & 788\,494 & 49\,679 & 357.1\,s & 386.5\\ {\sf InVS15} & 219 & 2\,566\,388 & 49\,679 & 657.2\,s & 733.2\\ {\sf SFHH} & 403 & 2\,834\,970 & 5\,328 & 245.0\,s & 346.3\\ {\sf LyonSchool} & 242 & 13\,188\,984 & 5\,887 & 853.6\,s & 1\,341.2\\ {\sf Thiers13} & 328 & 37\,226\,078 & 19\,022 & 2\,083.1\,s & 3\,399.5\\ \bottomrule \end{tabular} \end{table} \subsection{Case study: comparing immunization strategies} Our final set of experiments studies the change in restless reachability in the presence of a set of barrier vertices $S' \subseteq V$ called \emph{separators}, which must not be included in the restless path. In an epidemic model, the separators can be viewed as a subset of the population, all immune and/or vaccinated. It is known that finding a set of temporal separators with minimum size, which destroy all the restless paths between any two vertices, is $\sum_2^P$-hard~\cite{CasteigtsHMZ2019}. A promising heuristic to finding a minimum set of separators is choosing the vertices with high temporal-betweenness centrality. Unfortunately, computing the betweenness centrality in temporal graphs is intractable~\cite{buss2020algorithmic}. The experiments performed in this case study are to evaluate the effectiveness of our algorithm to answer queries for finding an effective immunization strategy in an epidemic model where the disease propagation is via a restless path. To demonstrate this we use two heuristics for finding separators: ($i$) choose vertices at random and ($ii$) choose vertices with maximum temporal degree. Note that these immunization strategies are simple and without theoretical guarantees. Towards this end, we would like to investigate effective approximation or heuristic schemes to find temporal separators, which reduce the fraction of vertices reachable from a given source vertex via a restless path in future work. \iffalse Our final set of experiments study the effect of vertices, which act as barriers for the restless paths, which we refer as \emph{separators}. In a real-world epidemic model, the separators can be viewed as people who are vaccinated and/or immune to the disease. We present experiments to study the change in restless reachability in the presence of immune vertices, which cannot be included in the restless path. \fi Given an instance $(G=(V,E), s, k)$ of the \ensuremath{k \text{\sc -Restless\-Reach}}\xspace problem and a set $S' \subseteq V$ of separators, we introduce a coloring function $c:V \setminus \{S' \cup s\} \rightarrow \{1\}$, $c(s) = 2$ and $c:S' \rightarrow \{3\}$ and $M=\{1^{\ell-1}, 2\}$ for $\ell \in [k]$. We query the {\sc FineGrainedOracle} with instance $(G'=(V, E\setminus \{u,s,i\}\in E), c,\ell,M)$ for each $\ell \in \{2,\dots,k\}$. By assigning color $3 \notin M$ to the separators in $S'$, we make sure that none of the separators are part of the restless path agreeing the multiset of colors in $M$. Note that here we solve the \ensuremath{\textit{atm-} k \text{\sc -Restless\-Reach}}\xspace problem, in other words we find the set of vertices which are reachable from the source via a restless path of length at most $k-1$. In Figure~\ref{fig:exp:immunization:1}, we report the variance of reachability in real-world graphs by choosing $5\%$ of the vertices uniformly a random (top-row) and $5\%$ of the vertices with maximum degree (second-row) as separators. Figure~\ref{fig:exp:immunization:2} reports the same experiments with $5\%$ replaced with $25\%$. For each dataset we generate five graph instances, choose source vertices at random and assign resting times uniformly at random in the range $[\Delta]$ for $\Delta=10$. Note that we use the same instances in the reachability experiments described above. Reachability is the ratio of number of reachable vertices to the total number of vertices excluding separators. From the experimental results we observe high variance in the reachability among independent source vertices and the rate of increase of the reachability with time varies depending on the source vertex. More importantly, even though we expect (empirically) that by choosing vertices with high degree as separators should decrease the reachability as compared to choosing the vertices at random, this is not true for all the datasets. We only observe this phenomenon in {\sf SFHH} and Thiers13 datasets for choosing $5$\% of the vertices as separators and in {\sf InVS15} and {\sf LyonSchool} datasets while choosing $25$\% of the vertices as separators. \begin{figure*}[t] \centering \includegraphics[width=1.0\linewidth]{fig/Xeon-datasets-reachability-varience-separators-random-max-deg.pdf} \caption{\label{fig:exp:immunization:1 Restless reachability in real-world datasets in the presence of $5\%$ separators. $\Delta=10$, $\delta: V \rightarrow [\Delta]$ assigned uniformly at random and $k=10$ (fixed). } \end{figure*} \begin{figure*}[t] \centering \includegraphics[width=1.0\linewidth]{fig/Xeon-datasets-reachability-varience-separators-random-max-deg-25.pdf} \caption{\label{fig:exp:immunization:2 Restless reachability in real-world datasets in the presence of $25\%$ separators. $k=10$, $\Delta=10$, $\delta : V \rightarrow [\Delta]$ assigned uniformly at random.} \end{figure*} In Figure~\ref{fig:exp:immunization:3}, we report the variance of reachability in real-world graphs by choosing $5\%$, $10\%$, and $25\%$ of the vertices uniformly a random (top-row) and $5\%$, $10\%$, and $25\%$ of the vertices with maximum degree (second-row) as separators. Again, for each dataset we generate five graph instances, choose source vertices at random and assign resting time uniformly at random in the range $[\Delta]$ for $\Delta=10$. Note that we use the same instances in the reachability experiments described above. We observe that reachability reduces with an increase in the number of separators, as expected. Again, even though it is expected (empirically) that choosing vertices with maximum degree to reduce the reachability significantly compared to choosing separators at random, surprisingly enough, this is not true for all datasets. For instance in {\sf LyonSchool} dataset choosing 10\% of the separators at random reduces the average reachability more than choosing vertices with maximum degree as separators. So the heuristic approach of choosing vertices with maximum degrees might not be effective across datasets. This presents us a interesting question of finding a small a set of separators in temporal graphs under resting time restrictions. Also note that the input graph datasets are small world graphs, meaning that the diameter of the underlying graph is small, so the vertices are highly connected (see Table~\ref{table:exp:datasets}). \begin{figure*}[t] \centering \includegraphics[width=1.0\linewidth]{fig/xeon_reducing_reachability_mean.pdf} \caption{\label{fig:exp:immunization:3 Restless reachability in real-world datasets in the presence of separators. $k=10$ (fixed), $\Delta=10$, $\delta:V \rightarrow [\Delta]$ assigned uniformly at random. } \end{figure*} \iffalse Even though by choosing vertices with maximum degree we reduce the reachability significantly in {\sf Thiers13} and {\sf SFHH} datasets, however, the effect is not similar across all the datasets. For instance in {\sf InVS13} dataset the change in reachability is not significant. However, in most datasets we observe change in the reachability time series, the rate of spread changes over time. Our experiments reveal that heuristic approaches such as selecting vertices with maximum degree as separators will not be very effective across all the datasets. \fi \section{Introduction} Graphs are used to model many real-world problems such as information propagation in social networks~\cite{bakshy2012role,jackson2005diffusion}, spreading of epidemics~\cite{anand2017tracking,rozenshtein2016reconstructing,pastor2015epidemic}, protein interactions~\cite{AlonPIFC2008,schwikowski2000network}, activity in brain networks~\cite{bullmore2009complex,de2010temporal,glerean2016reorganization}, and design of nano-structures using DNA~\cite{benson2015dna}. However, real-world problems often entail complex interactions whose semantics are not captured by usual simple graph models. As such, over the years, researchers have enriched graph models by introducing (i) node and edge attributes giving rise to \emph{attributed graphs}~\cite{perozzi2014focused,tong2007fast} or (ii) edge timestamps giving rise to \emph{temporal graphs}~\cite{holme2012temporal,michail2016introduction}. In particular, temporal graphs are used to model complex phenomena and network dynamics in a wide range of applications related to social networks, genealogical trees, transportation and telecommunication networks. As with any graph model, connectivity is a fundamental problem in temporal graphs. That is, the basic question when analyzing the structure of a given temporal graph is the question of whether two vertices are connected by a \emph{temporal path}~\cite{holme2012temporal,michail2016introduction}. A temporal path, or \emph{time-respecting path}, is a path in which consecutive edges have non-decreasing timestamps. An extension to connectivity is reachability, where the goal is to find the connectivity between all pairs of vertices~\cite{holme2005network}. Some variants of connectivity and reachability problems such as finding the path that minimizes the length or arrival time can be solved in polynomial time~\cite{cooke1966shortest,WuC2016,holme2005network}. However, recently Casteigts et al.~\cite{CasteigtsHMZ2019} showed that a variant of the connectivity problem with \emph{waiting/resting} time restrictions, known as \emph{restless temporal path} (or more simply \emph{restless path} if the context is clear) is \ensuremath{\mathbf{NP}}\xspace-hard. A restless path is a temporal path such that the time difference of consecutive edges is at most a resting time. In this paper we study a family of reachability problems in temporal graphs with waiting/resting time restrictions. In more detail, we study the following problems: \squishlist \item \emph{Restless path} (\ensuremath{\text{\sc Restless\-Path}}\xspace): Given a temporal graph, a source, and a destination, decide if there exists a restless path connecting the source and the destination. \item \emph{Short restless path} (\ensuremath{k \text{\sc-Restless\-Path}}\xspace): Given a temporal graph, a source, a destination, and an integer~$k$, decide if there exists a restless path of length $k-1$ connecting the source and the destination. \item \emph{Short restless motif} (\ensuremath{k\text{\sc-Restless\-Motif}}\xspace): Given a vertex-colored temporal graph, a source, a destination, and a multiset of colors with size $k$, decide if there exists a restless path connecting the source and the destination such that the vertex colors of the path agree with the multiset colors. \item \emph{Restless reachability} ({\sc Restless\-Reach}\xspace): Given a temporal graph and a set of source vertices, find the set of vertices for which there exists a restless path connecting a source to the vertex. \item \emph{Short restless reachability} (\ensuremath{k \text{\sc -Restless\-Reach}}\xspace): Given a temporal graph, a set of source vertices, and an integer~$k$, find the set of vertices for which there exists a restless path of length $k-1$ connecting a source to the vertex. \item \emph{Short restless motif reachability} (\ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace): Given a vertex-colored temporal graph, a set of source vertices, and a multiset of colors with size $k$, find the set of vertices for which there exists a restless path connecting a source to the vertex such that colors of vertices in the path agree with the multiset colors. \squishend To motivate the study of restless reachability problems in temporal graphs we present three application scenarios: ($i$) modeling epidemic spreading; ($ii$) finding signaling pathways in brain networks; and ($iii$) tour recommendation for travelers. \smallskip \noindent {\bf Example 1.} We can model the problem of estimating infections in an epidemic outbreak as a {\sc Restless\-Reach}\xspace problem. We associate each vertex in the graph to a person and each temporal edge to a social interaction between two persons at a specific timestamp. The \emph{resting time} of a vertex can be viewed as time until which the virus/disease can propagate from that vertex. After exceeding the resting time, we assume that the virus/disease becomes inactive at the vertex and/or stops propagating. Given the source of an infection, we would like to find out the set of people who may also be infected with the disease. Additionally, epidemiologists would be interested in a tool that allows them to evaluate different immunization strategies, such as, computing efficiently the spread of the disease when a selected subset of the population has been immunized to the disease, e.g., vaccinated or quarantined. \smallskip \noindent {\bf Example 2.} Another application of restless reachability is to find signaling pathways in brain networks. Here we assume that brain regions are represented as vertices, and edges between the regions represent physical proximity, for example, two regions that are physically next to each other or having high signal correlation in an electro-encephalogram (EEG) are connected with an edge. Using functional magnetic resonance imaging ({f{\sc\large mri}}\xspace) we can record the \emph{active} brain regions at different timestamps --- the frequency of the scans is approximately one second \cite{kujala2018brain,thompson2017static}. We introduce a timestamp on an edge if two regions with a static edge are active in consecutive {f{\sc\large mri}}\xspace scans. Finally, we introduce resting time for each region: any incoming signal can be forwarded to another region with in the resting time duration. Given the source of signal origin we would like to find all the regions to which the signal was successfully transmitted. The problem can be abstracted as a {\sc Restless\-Reach}\xspace problem.% \smallskip \noindent {\bf Example 3.} Consider a tour recommendation scenario where a traveler is interested in visiting a set of places such as a historic museum, an art gallery, a caf{\'e}, or other. However each location has a maximum time-limit that the traveler is willing to spend. Given a start and an end location we would like to find a travel itinerary satisfying the constraints specified by the traveler. This problem can be modeled as a \ensuremath{k\text{\sc-Restless\-Motif}}\xspace problem, where each location can be considered as a vertex, the color associated with the vertex represent the type of a location, for example, museum, art gallery, etc., the temporal edges between the vertices represent the transportation links, and the resting time duration associated with each vertex represents the maximum time a traveler is willing to spend at a location. \smallskip All problems considered in this work are \ensuremath{\mathbf{NP}}\xspace-hard and as such it is likely that they admit no polynomial-time algorithm. In such cases, it is typical to resort to heuristics or approximation algorithms which still run in reasonable time but compromise the quality of the solution. In contrast, we consider exact algorithms for solving restless reachability problems in both temporal and vertex-colored temporal graphs. To also ensure fast runtime, our algorithms are exponential in the length of the path sought. More precisely, we show that when the path length is small enough our solution scales to massive graphs with up to one billion temporal edges. To further motivate our approach, we note that Casteigts et al.~\cite{CasteigtsHMZ2019} studied the \ensuremath{\text{\sc Restless\-Path}}\xspace problem from a complexity-theoretic point of view. For instance, they proved that the problem remains \ensuremath{\mathbf{NP}}\xspace-hard on highly structured graphs such as complete graphs with exactly one edge removed. Despite several negative results, the authors pinpoint two parameters, say $p$, for which the problem admits an algorithm running in time $f(p)\,n^{\ensuremath{\mathcal{O}}\xspace(1)}$, where $f(p)$ is some computable function depending solely on the parameter $p$. Namely, these parameters are the \emph{feedback edge number} (FEN) and the \emph{timed feedback vertex number} (TFVN). For the latter, the algorithm they describe runs roughly in time $6^p\,p!\,n^{\ensuremath{\mathcal{O}}\xspace(1)}$, where $p$ is the TVFN of the input $n$-vertex temporal graph.% \footnote{In the field of parameterized algorithms, when devising algorithms for \ensuremath{\mathbf{NP}}\xspace-hard problems, it is not unusual to ignore the exact form of any polynomial factors in the runtime and concentrate on the likely unavoidable exponential dependency on the parameter under consideration. That is, when the exact polynomial factor of the algorithm is not worked out (or omitted as non-essential) it is often represented as merely $|x|^{\ensuremath{\mathcal{O}}\xspace(1)}$ meaning $|x|^c$ for some $c \geq 1$, where $x$ is the input and $|x|$ is its size.} In order for these algorithms to be scalable,% \footnote{As the problem is \ensuremath{\mathbf{NP}}\xspace-hard, the function $f(p)$ is necessarily exponential unless \ensuremath{\mathbf{P}}\xspace = \ensuremath{\mathbf{NP}}\xspace.} the corresponding parameter values should be small in practice on relevant instances. Unfortunately, as we show in Section~\ref{sec:exp:setup}, this is not the case. Therefore, it appears that the only known parameterized algorithm for the problem that has hope of being fast in practice is one that pushes the unavoidable exponential dependency into the length of the path. Our key contributions in this paper are as follows: \squishlist \item We present a generating function for generating restless walks, and an algorithm based on constrained multilinear sieving~\cite{BjorklundKK2016} for solving \ensuremath{k\text{\sc-Restless\-Motif}}\xspace and \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace in time $\ensuremath{\mathcal{O}}\xspace(2^k k m \Delta)$ and $\ensuremath{\mathcal{O}}\xspace(n\tau)$ space, where $n$ is the number of vertices, $m$ is the number of edges, $\tau$ is the maximum timestamp, $k-1$ is the path length, and $\Delta$ is the maximum resting time. Furthermore, we show that our algorithm solves \ensuremath{k \text{\sc-Restless\-Path}}\xspace and \ensuremath{k \text{\sc -Restless\-Reach}}\xspace in $\ensuremath{\mathcal{O}}\xspace(2^k k m \Delta)$ time using $\ensuremath{\mathcal{O}}\xspace(n\tau)$ space. For the discussion to follow, we call this algorithm a \emph{decision oracle} as it merely returns a {\sc\large yes}/{\sc\large no} answer with no explicit solution. \item We develop the decision oracle into a \emph{fine-grained decision oracle} capable of reporting the set of vertices that are reachable via a restless path from given source vertices along with the set of timestamps at which the vertices are reachable. Further, we exploit this to extract optimal solutions (i.e., solutions in which the maximum timestamp on the restless path is minimized) for \ensuremath{k\text{\sc-Restless\-Motif}}\xspace and \ensuremath{k \text{\sc-Restless\-Path}}\xspace. Notably, our solution improves upon the earlier work of Thejaswi et al.~\cite{Thejaswi2020pattern,thejaswi2020finding} by reducing the number of queries by a factor of $\log \tau$. Further, for extracting a solution, we reduce the number of queries from the work of Bj{\"o}rklund et al.~\cite{BjorklundKK-esa2014} from $\ensuremath{\mathcal{O}}\xspace(k \log n)$ to $k$. In total, our extraction algorithm runs in $\ensuremath{\mathcal{O}}\xspace(2^k k m \Delta)$ time. \item As a consequence of our fine-grained decision oracle, our algorithm can answer more detailed queries. In particular, it can answer whether a given vertex $u$ is reachable from source $s$ at timestamp $i$ with a restless path of length $\ell$. Such a fine-grained oracle can be used to solve multiple variants of the restless path problem, such as finding a restless path that minimizes the path length, the arrival time, or the total resting time. Another key strength of our algorithm is its adaptability to multiple variants of the restless path problem. For instance, the algorithm is not limited to a single source, but can be extended to include multiple source vertices. \item We prove that our algorithms for \ensuremath{k\text{\sc-Restless\-Motif}}\xspace and \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace are optimal under plausible complexity-theoretic assumptions. More precisely, we prove that there exists no $\ensuremath{\mathcal{O}}\xspace^*((2-\epsilon)^k)$-time algorithm\footnote{The notation $\ensuremath{\mathcal{O}}\xspace^*$ hides the factors polynomially bounded in the input size.} for \ensuremath{k\text{\sc-Restless\-Motif}}\xspace or \ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace for any $\epsilon > 0$, assuming the so-called Set Cover Conjecture~\cite{cygan2016problems} (see Subsection~\ref{sec:algo:infeasibility} for a precise definition). \item With an open-source implementation we demonstrate that our algorithm scales to graphs with up to ten million edges on a commodity desktop equipped with an 4-core Haswell CPU. When scaled to a computing server with $2 \times 12$-core Haswell CPU, the algorithm scales to graphs with up to one billion temporal edges~\cite{restless-paths-code}. As a case study, we model disease spreading in social gatherings as a \ensuremath{k \text{\sc -Restless\-Reach}}\xspace problem and perform experiments to study the propagation of the disease using the co-presence datasets from socio-patterns~\cite{Genois2018}. We also perform experiments to check the change in the disease spreading pattern with the presence of people with immunity. \squishend The rest of this paper is organized as follows. In Section~\ref{sec:related} we review the related work and put our approach in perspective. We introduce the necessary notation in Section~\ref{sec:terminology} and we formally define the reachability problems for temporal graphs and vertex-colored temporal graphs in Section~\ref{sec:problems}. Afterwards, our algorithmic solution is presented in Section~\ref{sec:algorithm}. Our empirical evaluation on a large collection of synthetic and real-world graphs is discussed in Section~\ref{sec:experiments}, and finally, Section~\ref{sec:conclusion} offers a short conclusion and directions for future work. \section*{Conflict of interest} The authors declare that they have no conflict of interest. \bibliographystyle{ACM-Reference-Format} \input{paper.bbl} \end{document} \endinput \section{Problems} \label{sec:problems} In this section we define the problems that we consider in this paper. While we define the problems on temporal directed graphs, we note that our algorithmic approach can be extended to undirected graphs by replacing each undirected edge with two directed edges in opposite directions. In such case, the asymptotic complexity of the algorithm remains the same. \subsection{Restless path problems} \mpara{Restless path problem (\ensuremath{\text{\sc Restless\-Path}}\xspace).} Given a temporal graph $G=(V,E)$, a function $\delta:V \rightarrow \ensuremath{\mathbb{N}_{+}}\xspace$, a source $s \in V$, and a destination $d \in V$, the problem asks if there exists a restless path from $s$ to $d$ in~$G$. \mpara{Short restless path problem (\ensuremath{k \text{\sc-Restless\-Path}}\xspace).} Given a temporal graph $G=(V,E)$, a function $\delta:V \rightarrow \ensuremath{\mathbb{N}_{+}}\xspace$, a source $s \in V$, a destination $d \in V$, and an integer $k \leq n$, the problem asks if there exists a restless path of length $k-1$ from $s$ to $d$ in~$G$. \mpara{Short restless motif problem (\ensuremath{k\text{\sc-Restless\-Motif}}\xspace).} Given a temporal graph $G=(V,E)$ with a coloring function $c:V \rightarrow C$ where $C$ is a set of colors, a function $\delta:V \rightarrow \ensuremath{\mathbb{N}_{+}}\xspace$, a source $s \in V$, a destination $d \in V$, and a multiset $M$ of colors, $|M|=k$, the problem asks if there exists a restless path from $s$ to $d$ in~$G$ such that the vertex colors of the path agree with $M$. \change{An illustration of restless path problems is available in Figure~\ref{fig:restless-paths}.} \smallskip All these three problems are \ensuremath{\mathbf{NP}}\xspace-hard (the hardness of the first two can be found in the paper of Casteigts et al.~\cite{CasteigtsHMZ2019}). For the last claim, observe that the \ensuremath{k \text{\sc-Restless\-Path}}\xspace problem is a special case of the \ensuremath{k\text{\sc-Restless\-Motif}}\xspace problem where all the vertices in the graph are colored with a single color and the query multiset is $M=\{1^k\}$. Since \ensuremath{k \text{\sc-Restless\-Path}}\xspace is \ensuremath{\mathbf{NP}}\xspace-hard, it follows that \ensuremath{k\text{\sc-Restless\-Motif}}\xspace is \ensuremath{\mathbf{NP}}\xspace-hard, as well. \subsection{Restless reachability problems} \mpara{Restless reachability problem ({\sc Restless\-Reach}\xspace).} Given a temporal graph $G=(V,E)$, a function $\delta:V \rightarrow \ensuremath{\mathbb{N}_{+}}\xspace$, and a source vertex $s \in V$, the problem asks to find the set of vertices $D \subseteq V$ such that for each $d \in D$ there exists a restless path from $s$ to $d$ in~$G$. Clearly, the problem generalizes \ensuremath{\text{\sc Restless\-Path}}\xspace and is thus computationally~hard. \mpara{Short restless reachability problem (\ensuremath{k \text{\sc -Restless\-Reach}}\xspace).} Given a temporal graph $G=(V,E)$, a function $\delta:V \rightarrow \ensuremath{\mathbb{N}_{+}}\xspace$, a source vertex $s \in V$, and an integer $k \leq n$, the problem asks to find the set of vertices $D \subseteq V$ such that for each $d \in D$ there exists a restless path of length $k-1$ from $s$ to $d$ in~$G$. Given that \ensuremath{k \text{\sc-Restless\-Path}}\xspace is hard, \ensuremath{k \text{\sc -Restless\-Reach}}\xspace remains hard, as well. \mpara{Short restless motif reachability problem (\ensuremath{k\text{\sc-Restless\-Motif\-Reach}}\xspace).} Given a temporal graph $G=(V,E)$ with coloring function $c: V \rightarrow C$ where $C$ is a set of colors, a function $\delta:V \rightarrow \ensuremath{\mathbb{N}_{+}}\xspace$, and a multiset $M$ of colors such that $|M|=k$, the problem asks to find the set of vertices $D \subseteq V$ such that for each $d \in D$ there exists a restless path from $s$ and $d$ in $G$ such that the vertex colors of the path agree with multiset $M$. Again, a routine observation shows that this problem is computationally hard. \change{An illustration of restless reachability problems is presented in Figure~\ref{fig:restless-reachability}.} \begin{figure*} \tikzset{every picture/.style={scale=0.52}} \begin{tabular}{c c c} \input{tikz/tikz-restless-path} & \input{tikz/tikz-short-restless-path} & \input{tikz/tikz-short-restless-motif} \\ \change{A restless path} & \change{A short restless path} & \change{A short restless motif} \end{tabular} \caption{\label{fig:restless-paths} \change{Illustration of restless path problems. A temporal graph on vertices $V=\{v_1,\dots,v_7\}$ with source $s=v_1$, destination $d=v_6$ and resting time of vertices $\delta(v_1)=\dots=\delta(v_7)=2$. Arrows represent the direction of edges and the integer value on each edge corresponds to its timestamp. On the left, an example of a restless path from $v_1$ to $v_6$ of length $5$. On the center, an example of a restless path from $v_1$ to $v_6$ when the length of the path is restricted to $4$ i.e., $k=5$. On the right, an example of a short restless (path) motif from $v_1$ to $v_6$ such that the vertex colors of the path agree with the multiset of colors in $M$. Restless paths are highlighted in bold (blue).}} \end{figure*} \begin{figure*} \tikzset{every picture/.style={scale=0.9}} \begin{tabular}{c c c} \input{tikz/tikz-restless-reach} & \input{tikz/tikz-short-restless-reach} & \input{tikz/tikz-short-restless-motif-reach} \\ \change{Restless reachability} & \change{Short restless reachability} & \change{Short restless motif} reachability \end{tabular} \caption{\label{fig:restless-reachability} \change{Illustration of restless reachability problems. A temporal graph on vertices $V=\{v_1,\dots,v_9\}$ with source $s=v_1$ and resting time of vertices $\delta(v_1)=\dots=\delta(v_9)=2$. Arrows represent the direction of edges and the integer value on each edge correspond to its timestamp. On the left, an example of restless reachability where vertices of $V$ except for $v_5$, highlighted in red, are reachable from source $s=v_1$ via a restless path. On the center, an example of short restless reachability when the length of the path is restricted to $2$ i.e., $k=3$, only $v_4$ and $v_6$ are reachable from $s$ via restless path of length $2$. On the right, an example of short restless motif reachability such that the vertex colors of the path agree with the multiset of colors in $M$. Only $v_9$ is reachable from $s$ via a restless path agreeing multiset of colors in $M$.}} \end{figure*} \section{Related work} \label{sec:related} In this section we report the research which is relevant to our work. \mpara{Static graphs.}\change{ Graph reachability in static graphs is the problem of verifying if there exists a path between a pair of vertices. Fundamental algorithms like {\em breadth first search} ({\sc bfs}) solve the problem in linear time. Alternatively, we can precompute the answer for each possible vertex pair by an all-pairs shortest path algorithm, after which each query can be answered in constant time. However, for large graphs with the number of vertices $n$ in the billions both approaches are problematic though with different trade-offs. First, linear time achieved by {\sc bfs} can be too slow in practice though its memory requirements are manageable. Second, to achieve constant-time queries, the memory trade-off is prohibitive as there are roughly $n^2$ pairs of vertices to consider. As such, more scalable techniques seek to find a small representation of the input graph, and exploit the transitive-closure property or index construction techniques such as tree cover, chain cover, 2-hop, 3-hop and landmark based indexing to reduce the running time and memory requirements~\cite{simon1988improved,agrawal1989efficient,chen2008efficient,cohen2003reachability,jin20093hop,thorup2005approximate}. For more details, we refer the reader to the survey of Yu and Cheng~\cite{yu2010graph}.} \mpara{Temporal graphs.} Path problems in temporal graphs are well-studied within different communities, including algorithms, data mining, and complex networks. The problem variants that seek to find a path that minimizes different objectives such as path length, arrival time, or duration, as well as finding top-$k$ shortest temporal paths are solvable in polynomial time~\cite{GeorgeKS2007,GuptaAH2011,WuCHKLX2014,WuC2016,xuan2003computing}. In recent years, there has been an emphasis on more expressive temporal path problems due to their applicability in various fields~\cite{anand2017tracking,bullmore2009complex,rozenshtein2016reconstructing,von2009public}. The problem of finding a temporal path under waiting time restrictions was introduced by Dean~\cite{dean2004algorithms}, who studied a polynomial-time solvable variant of the problem. More recently, Casteigts et al.~\cite{CasteigtsHMZ2019} proved that \ensuremath{\text{\sc Restless\-Path}}\xspace is \ensuremath{\mathbf{NP}}\xspace-hard and also that \ensuremath{k \text{\sc-Restless\-Path}}\xspace is \ensuremath{\mathbf{W}[1]}\xspace-hard parameterized by either the {\em feedback vertex number} or the {\em pathwidth} of the input graph. Himmel et al.~\cite{himmel2019efficient} considered the restless walk problem where several visits to a vertex are allowed and presented polynomial-time algorithms. Estimating reachability with waiting-time constraints has been studied by Badie-Modiri et al.~\cite{Badie2020efficient}. The complexity of finding small separators that separate two given vertices in a temporal graph was studied by Zschoche et al.~\cite{zschoche2020complexity}. Furthermore, Fluschnik et al.~\cite{fluschnik2020temporal} used temporal separators to classify temporal graphs. Network reachability in temporal graphs without waiting time restrictions has been studied and a practical implementation that can scale to graphs with up to tens of thousands of vertices was presented by Holme~\cite{holme2005network}. The author studied a variant of the problem that reports connectivity between all pairs of vertices, whereas our work considers reachability from a set of sources to the other vertices in the graph. Sengupta et al.~\cite{sengupta2019arrow} presented approximation techniques based on random walks to estimate reachability in both static and temporal graphs. \mpara{Constrained graph reachability.}\change{ Constrained path problems ask us to find a path between a pair of vertices with additional constraints imposed on the path. For instance, a solution path can be restricted to avoid a subset of vertices and/or forced to visit a subset of vertices. In vertex-weighed graphs, some constrained path problems try to optimize the length of the path while restricting the total weight on vertices to a budget, these problem variants are known to be \ensuremath{\mathbf{NP}}\xspace-hard (see the work of~\citet{festa2015constrained} or~\citet[Chapter~2]{irnich2005shortest}). Here, the {\em length} of the path is defined as the number of edges in the path. Note that, the set of vertices and edges can be interchanged by constructing the line graph of the input graph with only a polynomial increase in the graph size. Thus, most algorithms for vertex-labeled graphs can be applied to solve the corresponding edge-labeled problem variants and vice versa. For related work, we refer the reader to the work of Festa~\cite{festa2015constrained}. \citet{wang2021constrained} and \citet{yuan2019constrained} studied constrained path problems in {\em time-dependent} graphs i.e., the travel time of edges varies over time. \citet{yuan2019constrained} show that computing a constrained shortest path over a time interval in time-dependent graphs is \ensuremath{\mathbf{EXPSPACE}}\xspace-hard and present heuristics to solve the problem. A basic question in edge-labeled static graphs is to verify if a pair of vertices is reachable using only edges which correspond to a subset of labels. This problem is solvable in polynomial time by filtering the input graph to contain only edges corresponding to the subset of labels under consideration. As such, a path between two vertices is obtained by {{\sc\large bfs}}\xspace. However, answering such queries for all subsets of the label set has an exponential dependency on the number of labels. Many approaches including transitive closure, tree cover, 2-hop cover, and landmark indexing strategies used to verify reachability have been extended to solve label-constrained reachability problems~\cite{bonchi2014distance,peng2020answering,jin2010computing,peng2021answering}. For instance, Peng et al.~\cite{peng2020answering} show that a 2-hop indexing approach scales to graphs with $68$ million nodes and $2.5$ billion edges when the number of labels is at most~eight.} \mpara{Epidemic modeling.} Due to epidemic outbreaks ranging from {\sc\large sars}, {\sc\large mers}, and Ebola to most recently {\sc\large covid}-19, there has been considerable interest in studying disease-spreading models. Indeed, human-contact networks can be modeled as temporal graphs, which preserve the network dynamics with respect to time, thus, abstracting the analysis of the epidemic outbreaks as fundamental problems in temporal graphs~\cite{eubank2004modeling,pastor2015epidemic,prakash2010virus}. For instance, Rozenshtein et al.~\cite{rozenshtein2016reconstructing} modeled the problem of reconstructing the epidemic spreading with partial information as a Steiner tree problem in temporal graphs. Additionally, the problem of identifying potential pathways of disease transmission has been successfully modeled using temporal graphs~\cite{anand2017tracking,ferretti2020quantifying}. Epidemic outbreaks can be modeled as diffusion processes in temporal and dynamic graphs. Likewise, many models used to study information diffusion, information cascades and marketing recommendations in social media can be adapted to solve related problems in epidemic modeling~\cite{jackson2005diffusion,prakash2013fractional,tong2010vulnerability,zhang2016dynamics}. Finding effective immunization strategies has been an important area of research due to its real-world impact in minimizing the scale of an epidemic outbreak and the problem is analogous to finding a fraction of vertices in a social network to maximize the influence~\cite{kempe2003maximizing}. As such, the approaches used to solve influence maximization problems can be adapted to solve the problem of outbreak minimization~\cite{cheng2020outbreak}. To summarize, these approaches provide us a way to understand the disease propagation in epidemic outbreaks~\cite{ferretti2020quantifying}, the transmission of diseases across generations~\cite{anand2017tracking}, as well as immunization strategies that are effective to minimize the scale of epidemic outbreaks~\cite{prakash2013fractional,prakash2010virus}. \mpara{Multilinear sieving.} Algebraic algorithms based on multilinear sieving for solving path problems in static graphs are due to Koutis and Williams~\cite{koutis-icalp08,williams-ipl,koutis-williams-icalp09}. Bj{\"o}rklund et al.~\cite{BjorklundHKK2017} improved the technique using narrow sieves to get a breakthrough result for the Hamiltonian path problem by showing that it admits an algorithm running in $\ensuremath{\mathcal{O}}\xspace^*(1.66^n)$ time. The sieving technique was extended to find trees and connected subgraphs by Bj{\"o}rklund et al.~\cite{BjorklundKK2016}, who generalized the approach using a constrained variant of the sieve to find paths and subgraphs that agree with a multiset of colors. A practical implementation of the sieve was provided by Bj{\"o}rklund et al.~\cite{BjorklundKKL2015}. Furthermore, its parallelizability to vector-parallel architectures and scalability to large subgraph sizes was shown by Kaski et al.~\cite{KaskiLT2018}. Note that these algorithms only handle static graphs. More recently, Thejaswi et al.~\cite{Thejaswi2020pattern} extended the sieving technique to solve a family of pattern-detection problems in temporal graphs. They also presented a vertex-localized variant of the sieve and a memory-efficient implementation scaling to temporal graphs with one billion edges~\cite{thejaswi2020finding}. \mpara{Recent advancements.} The {\sc Restless\-Reach}\xspace and \ensuremath{k \text{\sc -Restless\-Reach}}\xspace problems that we study in this paper generalize the problems of \ensuremath{\text{\sc Restless\-Path}}\xspace and \ensuremath{k \text{\sc-Restless\-Path}}\xspace problems, respectively. The latter problems, which ask for the existence of a restless path between a source and a destination, are studied by Casteigts et al.~\cite{CasteigtsHMZ2019}, who established their \ensuremath{\mathbf{NP}}\xspace-hardness and developed fixed-parameter tractable algorithms. More recently, the authors presented algorithms with running time $\ensuremath{\mathcal{O}}\xspace(2^k n^{\ensuremath{\mathcal{O}}\xspace(1)})$ and $\ensuremath{\mathcal{O}}\xspace(2^n n^{\ensuremath{\mathcal{O}}\xspace(1)})$ for the \ensuremath{k \text{\sc-Restless\-Path}}\xspace and \ensuremath{\text{\sc Restless\-Path}}\xspace problems, respectively, where $n$ is the number of vertices in the input temporal graph and $k$ the length of the path. It should be noted that their algorithm only reports the existence of a restless path between a source and a destination with a {\sc\large yes}/{\sc\large no} answer but does not return an explicit solution. In many practical scenarios, such as where further analysis of the path is required, this is insufficient. In comparison to the work of Casteigts et al.~\cite{CasteigtsHMZ2019}, our approach can detect and extract an optimal (i.e., one minimizing the maximum timestamp) restless temporal path in time $\ensuremath{\mathcal{O}}\xspace(2^k k m \Delta)$ and $\ensuremath{\mathcal{O}}\xspace(2^n n m \Delta)$ for the \ensuremath{k \text{\sc-Restless\-Path}}\xspace and \ensuremath{\text{\sc Restless\-Path}}\xspace problems, respectively, where $n$ is the number of vertices, $m$ is number of temporal edges, and $\Delta$ is the maximum resting time. Furthermore, our method can be used to answer reachability queries, i.e., finding the set of vertices that are reachable from a set of sources, in a single computation and without having to iterate over each vertex. In addition, our method solves a general variant of the restless path problem with color constraints on the vertices. \section*{Reviewer 1} \reviewer{Some technical details, however, are not clearly justified. For instance, the way to randomly substituting values from the Galois Field is not reasoned with sufficient details. How to determine the value of the parameter, b, which is critically related to the complexity of the methods?} \answer{We have included an overview of the polynomial evaluation scheme in Section 5.4 providing more details. The value of $b$ is determined from the Galois field that we operate, i.e., it is freely chosen by the user. Here, the value of $b$ is the number of bits used to generate field variables, i.e., $\{2,4,8,16,\dots\}$, and the polynomial used to generate the (pseudo) random variables. As explained in the paper, by choosing $b=64$ (which is what we do for our experiments), the probability of making an error is tiny (see Subsection~6.3 for precise statements). However, explaining the details of Galois fields is beyond the scope of our article, especially since it requires to additionally introduce the related terminology and literature. For interested readers we suggest to check related work by \cite{koutisW2016}, \cite{BjorklundKK2016}, and \cite{cygan2015parameterized}[Chapter~10].} \reviewer{My primary concern relating to this work is that, the authors seemingly omit a rich body of related work for reachability queries in big graphs, which, together with its variants, has been intensively studied in the past 15 years in the database community. There are many noteworthy work that can be easily found in recent years in SIGMOD, VLDB, and ICDE. There are 2-hop, 3-hop labelling approaches, landmark-based approaches, graph indexing approaches, and alike. Similar ideas have been examined repeatedly to solve the reachability problem, label-constrained reachability problem, and alike, static, dynamic, and different types of graphs. Although these methods cannot be directly applied to solve the restless path problem, a minor modification of such methods that respects the time constraints seems feasible for the proposed problem as well (In the experimental studies, the authors use a naive baseline based on DFS, and adapt it with minor modifications by respecting the time constraints in the proposed problems. To this end, I will feel surprise if existing reachability query work CANNOT work after the same, or similar, modifications). Therefore, the authors omit careful justifications and systematic reasoning on the clear differences between the proposed work with the existing rich body of work related to reachability queries;} \answer{Comments related to literature survey has been addressed. We have tried to adapt many commonly-used algorithms to estimate reachability, but most of the approaches do not work in practice (which is evident given the complexity of the restless path problem). We have added a detailed discussion and careful justification on why many existing reachability query methods fail to solve restless reachability problems (see Section~6.3).} \reviewer{Real networks or graphs are typically dynamically changing all the time, in terms of both structures and graph contents. The authors are expected to provide some technical discussion on if and how the proposed methods can fit into real-world, dynamic graphs;} \answer{We do not know a straightforward approach to extend our methods to solve problems in dynamic graphs. This is an interesting direction for future work.} \reviewer{In experimental studies, the baseline method that is based on temporal DFS is rather weak. The authors need consider state-of-the-art work for reachability queries, and compare with these work (with minor modifications that respect time constraints) for fair comparison;} \answer{We have included a section (Section~6.3) where we describe in detail many algorithmic approaches that could potentially serve as a baseline. We list the shortcomings of these approaches and point out why they fail to solve the restless reachability problems.} \reviewer{Sec. 6.4 is poorly written. There are lots of typos and errors.} \answer{We have polished the text, and fixed the typos and errors.} \reviewer{A rich body of related work for reachability queries, label-constraint reachability queries are missing. In the past decade, the reachability problem has been extensively studied in the database community. However, the authors totally miss systemic discussion and comparison with these work.} \answer{We have now addressed this concern.} \section*{Reviewer 2} \reviewer{My primary concern is the length of the paper. It is supposed to be a technique paper whose main contribution is the new method. While in my opinion, this paper is like a combination of a survey paper and a technical paper with over 40 pages. I am uncertain about the policy of TKDD whether such a length is allowed for publication. Please make sure to check this with the editor.} \answer{We have done our best to be brief, but we cannot compromise on completeness and rigor. We also note that the journal does not have a strict page limit (or rather it suggests that up to 50 pages is allowed).} \reviewer{The authors summarized the different settings of restless reachability problems on page 4. It will be easier for readers to understand the meanings of these problems if the corresponding illustration figures are provided here.} \answer{We thank the reviewer for the comment. We have included illustrations, which we agree that improve readability.} \reviewer{It seems that the authors present too much background knowledge at the beginning, which makes Sec 5 (Algorithm) starting on page 9. I suggest the authors reduce some of the background introduction.} \answer{The introduction in Section~5 has been written in sufficient detail, by taking into consideration that non-expert readers who are not well versed in the topic should be able to follow our work. In general many reviewers have suggested that the approach based on multilinear sieving is difficult to understand without sufficient background. For this reason we would like to keep the background section as it is.} \reviewer{To highlight the novelty/contribution of this paper, the authors should describe more about the difference of your approach with previous solutions in Sec 5.1.} \answer{The idea presented in Section~5.1 is an intuition of algebraic algorithms in general and the approach dates back to Lov\'{a}sz (computing perfect matching), Tutte (Tutte polynomial), and Schwartz-Zippel (polynomial identity testing). Most pattern-detection algorithms use a similar reduction, i.e., reduce the pattern-detection problem to the problem of deciding the existence of a multilinear monomial ($k$-path, motif search, Hamiltonian path, etc.). In particular we make use of polynomial identity testing to solve the restless path problem; this is explained in Section~5.4.} \reviewer{Line 475 is somewhat confusing. I cannot separate the items and footnotes exactly.} \answer{ We assume that this comment is about difficultly to separate variables $x$ and $y$ and corresponding subscripts. We have introduced space between variables to improve readability. } \reviewer{Please provide more details of the experimental settings, such as the size of datasets, length of the path, different settings, etc. An illustration table to show such details is welcome at the beginning of the experiment section.} \answer{We have addressed the comment by updating Table~3.} \reviewer{Please highlight the best results in Table 2 and explain how to analyze its content in the caption for easier understanding.} \answer{Details of dataset statistics is available in main text (see Section~6.2, dataset statistics).} \section*{Reviewer 3} \reviewer{The only concern is that the baseline is set up by authors and there may be other competitive baseline approaches.} \answer{We thank the reviewer for the comment. We have now added Section~6.3 for a detailed discussion regarding baselines. Please see also our answers to Reviewer~1.} \bibliographystyle{ACM-Reference-Format} \section{Terminology} \label{sec:terminology} In this section we introduce our notation and basic terminology. A list of symbols used in this paper is available in Table~\ref{table:symbols}. \mpara{Static graphs.} A {\em (static) undirected graph} $G$ is a tuple $(V,E)$ where $V$ is a set of {\em vertices} and $E$ is a set of unordered pairs of vertices called {\em edges}. A {\em (static) directed graph} $G$ is a tuple $(V,E)$ where $V$ is a set of vertices and $E$ is a set of ordered pair of vertices called edges. A {\em (static) walk} between any two vertices is an alternating sequence of vertices and edges $u_1 e_1 u_2 \dots e_{k} u_{k}$ such that there exists an edge $e_i=(u_i, u_{i+1}) \in E$ for each $i \in [k-1]$.% \footnote{For a positive integer $k$ we write $[k]=\{1,\dots,k\}$} We call the vertices $u_1$ and $u_{k}$ the \emph{start} and \emph{end} vertices of the walk, respectively. We refer to walk $W$ as $(s,d)$-walk for $u_1=s$ and $u_{k}=d$. The \emph{length} of a static walk is the number of edges in the walk. A \emph{(static) path} is a static walk with no repetition of vertices. \mpara{Undirected temporal graphs.} An \emph{undirected temporal graph} $G$ is a tuple $(V,E)$, where $V$ is a set of vertices and $E$ is a set of undirected temporal edges. An \emph{undirected temporal edge} is a tuple $(u,v,j)$ where $u, v \in V$ and $j \in [\tau]$ is a \emph{timestamp}, where $\tau$ is the \emph{maximum timestamp} in $G$. Note that, by definition, two undirected edges $(u,v,j)$ and $(v,u,j)$ are equivalent. A vertex $u$ is adjacent to vertex $v$ and vice versa at timestamp $i$ in an undirected graph $G$ if there exists an undirected edge $(u,v,i) \in E$. A {\em temporal walk} $W$ is an alternating sequence of vertices and temporal edges $u_1 e_1 u_2 e_2 \dots e_{k-1} u_{k}$ such that $e_{i} \in E$ for all $i \in [k-1]$ and for any two edges $e_i=(u_i,u_{i+1},j_i)$, $e_{i+1}=(u_{i+1},u_{i+2},j_{i+1})$ in $W$, it is $j_i \leq j_{i+1}$. We say the walk $W$ \emph{reaches} vertex $u_k$ at time $j_{{k-1}}$. The vertices $u_1$ and $u_{k}$ are called \emph{source} and \emph{destination} vertices of $W$, respectively. The vertices $\{u_2,\dots,u_{k-1}\}$ are called \emph{in-vertices} (or equivalently, \emph{internal vertices}) of $W$. We refer to the temporal walk $W$ as $(s,d)$-temporal walk with source $s=v_1$ and destination $d=v_{k}$. The vertex set and edge set of walk $W$ is denoted as $V(W)$ and $E(W)$, respectively. The {\em length} of a temporal walk is the number of edges in the temporal walk. A {\em temporal path} is a temporal walk with no repetition of vertices. \mpara{Directed temporal graphs.} A \emph{directed temporal graph} $G$ is a tuple $(V,E)$, where $V$ is a set of vertices and $E \subseteq V \times V \times [\tau]$ is a set of directed temporal edges at discrete time steps, where $\tau$ is the \emph{maximum timestamp}. A \emph{directed temporal edge} is a tuple $(u,v,j)$ where $u, v \in V$ and $j \in [\tau]$ is a \emph{timestamp}. A directed edge $(u,v,j)$ is referred as an \emph{outgoing} or \emph{departing} edge for $u$ and an \emph{incoming} or \emph{arriving} edge for $v$ at time $j$. A vertex $u$ is an \emph{in-neighbor} to $v$ at time $j$ if $(u,v,j) \in E$, similarly a vertex $v$ is an \emph{out-neighbor} to $u$ at time $j$ if $(u,v,j) \in E$. The set of in-neighbors to $v$ at time $j$ is denoted by $N_j(v)= \{u \mid (u,v,j) \in E\}$ and the set of out-neighbors to $u$ at time $j$ is denoted by $N'_j(u)=\{v \mid (u,v,j) \in E\}$. Unless stated otherwise, by a temporal graph we always mean a directed temporal graph. Similarly, by a temporal walk we always mean a directed temporal walk, and by a temporal path we always mean a directed temporal path. To distinguish a temporal graph from a static graph, we sometimes explicitly call a graph {\em non-temporal} or {\em static}. \mpara{Restless walk.} A \emph{restless temporal walk}, or simply \emph{restless walk}, is a temporal walk such that for any two consecutive edges $e_{i}=(u_{i},\allowbreak u_{i+1},\allowbreak j_{i})$ and $e_{i+1}=(u_{i+1},u_{i+2},j_{i+1})$, it holds that $j_{i+1}-j_i \leq \delta(u_{i+1})$, where the function $\delta: V \rightarrow [\Delta]$ defines a \emph{vertex-dependent waiting time}, with $\Delta \in \ensuremath{\mathbb{N}_{+}}\xspace$ being the {maximum waiting time}. In other words, in a restless temporal walk, it is not allowed to wait more than a vertex-dependent amount of time in each vertex. A \emph{restless path} is a restless walk with no repetition of vertices. \mpara{Coloring.} Let $C$ to be a set of \emph{colors}. A \emph{vertex-colored} temporal graph $G=(V,E)$ is a temporal graph with a vertex-coloring function $c: V \rightarrow C$, which maps each vertex $u \in V$ to a subset of colors in $C$. Let $M$ be a multi\-set of colors and $W$ be a walk. The walk $W$ is \emph{properly colored} (or is said to \emph{agree} with $M$) if there exists a bijective mapping $f:V(W) \rightarrow M$ such that $f(u) \cap c(u) \neq \emptyset$ for all $u \in V(W)$. \mpara{Polynomials.} We assume that our temporal graph contains $n$ vertices and $m$ temporal edges, and for simplicity we write $V = \{u_1,\dots,u_n\}$ and $E=\{e_1,\dots,e_m\}$. We introduce a variable $x_{u_i}$ for each $ u_i \in V$ and a variable $y_{e_j}$ for each $e_j \in E$. Let $\mathcal{P}$ be a \emph{multi\-variate polynomial} such that each monomial $\pazocal{P} \in \mathcal{P}$ is of the form $x_{u_1}^{f_1} \dots x_{u_n}^{f_n} y_{e_1}^{g_1} \dots y_{e_m}^{g_m}$. A~\emph{monomial} $\pazocal{P}$ is \emph{multilinear} if $f_i, g_j \in \{0,1\}$ for all $i \in [n]$ and $j \in [m]$. The \emph{degree} (or \emph{size}) of $P$ is the sum of the degrees of all the variables in $\pazocal{P}$. Let $C$ be a set of colors and $c: V \rightarrow C$ be a vertex-coloring function. Let $M$ be a \emph{multi\-set} of colors. For each $s \in C$, let $\mu(s)$ denote the number of occurrences of color $s$ in $M$, noting that $\mu(s) = 0$ if $s \notin M$. We say that a monomial $x_{u_1}^{f_1} \dots x_{u_n}^{f_n} y_{e_1}^{g_1} \dots y_{e_m}^{g_m}$ is \emph{properly colored} if for each $s \in C$ it holds that $\mu(s) = \sum_{i \in c^{-1}(s)} d_i$, in other words, the number of occurrences of color $s$ is equal to the total degree of $x$-variables representing the vertices with color $s$.
{'timestamp': '2021-12-20T02:19:31', 'yymm': '2010', 'arxiv_id': '2010.08423', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08423'}
arxiv
\section{Introduction} Domain-specific languages play an important part in our modern software ecosystem. Domain-specific languages are commonly used to generate lexical analyzers (e.g., Lex~\cite{lesk1975lex}, re2c~\cite{bumbulis1993re2c}) and parsers (e.g., Yacc~\cite{johnson1975yacc}, ANTLR~\cite{parr1995antlr}). In high-performance computing, DSLs are used to generate numerical kernels (e.g., SPIRAL~\cite{franchetti2018spiral}, TCE~\cite{hirata2003tensor}, LGen~\cite{spampinato2014basic}, Linnea~\cite{barthels2020automatic}, TACO~\cite{kjolstad2017tensor}, Devito~\cite{lange2016devito}), and many code bases use custom code generators (e.g., the codelet generator in FFTW~\cite{frigo1998fftw}, Kranc in the Einstein Toolkit~\cite{husa2006kranc}). Unfortunately, these DSLs are often difficult to integrate into a larger software project. At its root, one significant source of difficulty is due to the need to provide the input to the DSL's translator in one or more source files separate from the source files containing the bulk of the project's source code. The input to the DSL, however, needs to be somehow integrated with the code is the rest of the project. The DSL-generated code provides and/or uses interfaces provided by the rest of the source code, sometimes making use of non-trivial types defined elsewhere in the project. Some DSL's (e.g., Lex, Yacc) allow the programmer to embed code in a host, general-purpose programming language (e.g., C/C++) into the DSL's input source files. While relatively convenient, and often necessary for performance, this increases the number of, and complexity of, dependencies between the DSL source and the rest of the project. Practically, integration of DSLs into project build systems requires effort, and sometimes, specialized skills. Most importantly, programmers often try to keep related functions and/or components together in the same source file to make the source code easier to understand. While being forced to keep the DSL's input in files separate from the rest of the project source code may seem to be a trivial inconvenience, it's not. A majority, 60-90\%, of software-development costs are associated with reading and navigation source code as part of maintenance tasks~\cite{erlikh2000leveraging}. Consistent with our experience, when examining how programmers use their editors to perform these kinds of tasks, 35\% of their time, on average, is spent navigating between dependencies~\cite{ko2005eliciting}. Thus, the productivity of using DSLs can be significantly improved by reducing logically-undesirable partitioning of source code between different files. In this paper, we describe a new technique for integrating DSLs into C++ source code: the syntax plugin. The implementation is built on the Clang C++ compiler~\cite{lattner2008llvm}. Clang can compile C++ code to executable form using the LLVM compiler infrastructure~\cite{lattner2004llvm}, but can also directly perform source-code analysis~\cite{kremenek2008finding} and rewriting. While performing any of these tasks, Clang can make use of user-provided plugins. However, no existing plugin interface provides the ability to integrate DSLs as described here, and so as described below, a new plugin interface was designed and implemented. While we do not quantitatively evaluate productivity gains, or other factors affecting developer willingness to use DSLs, in this paper, it is our sense that the presented technique increases developer productivity and otherwise lowers barriers to adopting DSLs inside of C++ code bases. The implementation of Clang with support for syntax plugins is available from: \url{https://github.com/hfinkel/llvm-project-csp} The remainder of this paper is organized as follows: Section~\ref{sec:cp} reviews Clang's plugin support, Section~\ref{sec:sp} describes the implementation of the syntax-plugin infrastructure within Clang, Section~\ref{sec:taco} describes how syntax plugins enable embedding TACO into C++, Section~\ref{sec:qcor} describes embedding programming languages for quantum computing into C++, Section~\ref{sec:taprol} describes embedding a DSL for tensor computation into C++, and Section~\ref{sec:con} concludes with a discussion of future directions. \section{Background: Clang Plugins} \label{sec:cp} Clang plugins are loaded from shared libraries provided on Clang's command line and are integrated into Clang's source-code processing. Figure~\ref{fig:cmdlplugin} shows the relevant command-line arguments. \begin{figure} \begin{lstlisting} clang++ -c source.cpp \\ -fplugin=/path/to/somePlugin.so \end{lstlisting} \caption{An example showing how Clang can be invoked so that it loads (from a shared library named \texttt{somePluginLib.so}) and uses a plugin.} \label{fig:cmdlplugin} \end{figure} A Clang plugin takes the form of a set of classes, each of which derives from some appropriate \textit{Handler} class, and each of which is registered using an appropriate static object. Clang provides several kinds of handlers~\cite{ClangPlu29}: \begin{itemize} \item \texttt{PragmaHandler} - Used by a plugin to provide new kinds of pragmas. \item \texttt{ParsedAttrInfo} - Used by a plugin to provide new kinds of attributes. \item \texttt{PluginASTAction} - Used by a plugin to provide an \textit{AST listener}, an object that can observe AST-node creation events. \end{itemize} As illustrated in Figure~\ref{fig:pluginex}, a single plugin can have multiple handlers, including multiple kinds of handlers, and use all of them together in order to provide its functionality. \begin{figure} \begin{lstlisting} #include "clang/Frontend/FrontendPluginRegistry.h" ... // other includes. using namespace clang; namespace { class ExampleASTConsumer : public ASTConsumer { CompilerInstance &Instance; public: ExampleASTConsumer(CompilerInstance &Instance) : Instance(Instance) {} bool HandleTopLevelDecl(DeclGroupRef DG) override { // Do something to handle a new declaration. return true; } void HandleTranslationUnit(ASTContext& context) override { // Do something to handle the completion of // the translation unit. } }; class ExampleASTAction : public PluginASTAction { protected: std::unique_ptr<ASTConsumer> CreateASTConsumer( CompilerInstance &CI, llvm::StringRef) override { return std::make_unique<PrintFunctionsConsumer>(CI); } bool ParseArgs( const CompilerInstance &CI, const std::vector<std::string> &args) override { // Handle custom plugin command-line arguments. return true; } void PrintHelp(llvm::raw_ostream& ros) { ros << "A help message goes here\n"; } }; class ExamplePragmaHandler : public PragmaHandler { public: ExamplePragmaHandler() : PragmaHandler("an_example") { } void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer, Token &PragmaTok) override { // Handle an encountered: // #pragma an_example more tokens } } // anonymous namespace static FrontendPluginRegistry::Add<ExampleASTAction> X("example-plugin", "an example sketch"); static PragmaHandlerRegistry:: Add<ExamplePragmaHandler> Y("example-plugin-cntrl","enable something"); \end{lstlisting} \caption{An example showing how Clang plugins are structured. This example sketches a plugin using the \texttt{PragmaHandler} interface to provide a new pragma and the \texttt{PluginASTAction} to observe relevant AST-node creation events.} \label{fig:pluginex} \end{figure} It is worth noting that this interface is tied directly to Clang's AST data structures. This means that the plugins are not only specific to Clang, but also, in practice, tied to the particular version of Clang against which the plugin was compiled. Programming the plugin requires knowledge of the data structures used by Clang's lexical analysis and parsing infrastructure, along with Clang's AST. For a more-complete example, we refer the reader to \texttt{examples/AnnotateFunctions} in Clang's source repository~\cite{clangannotex}. \section{Clang Syntax Plugins} \label{sec:sp} None of the existing plugin interfaces allow the plugin to alter the fundamental syntax accepted by Clang's parser. Here we explore a plugin interface that allows for exactly that: within a specifically-tagged function, the function body may contain code that is not valid C++ code. The code in the function body must still obey certain rules, but only a few: \begin{itemize} \item The code must admit a valid C++ tokenization. Those tokens might not form a valid fragment of C++ code, but the code must be describable as C++ tokens. \item The code, like all of the token stream, is subject to C++ macro expansion. That must be acceptable for the plugin's use cases. \item The code must use balanced C++ delimiters - the implementation must be able to find the '\}' character matching the \{ starting the function body, and it does so using C++ token-capturing rules, without consulting the plugin. \end{itemize} The task of the plugin, when handling an appropriately-tagged function, is to generate a replacement stream of text containing a valid fragment of C++ code. This text stream effectively \textit{replaces} the tagged function definition. Thus, the DSL takes its input and transforms it into some other C++ code that is processed by Clang in the usual way. The whole interface, illustrated in Figure~\ref{fig:shex} is fairly simple, consisting of only two functions: \begin{itemize} \item \texttt{GetReplacement} - Takes the token stream and provides the replacement stream of C++ code. \item \texttt{AddToPredefines} - Adds to the stream of C++ code parsed at the beginning of the translation unit. Useful for adding \#include directives and declarations required by any replacement code. \end{itemize} \begin{figure} \begin{lstlisting} #include "clang/Frontend/FrontendPluginRegistry.h" ... // other includes. using namespace clang; namespace { class ExampleSyntaxHandler : public SyntaxHandler { public: ExampleSyntaxHandler() : SyntaxHandler("example") { } void GetReplacement(Preprocessor &PP, Declarator &D, CachedTokens &Toks, llvm::raw_string_ostream &OS) override { // The plugin might handle the token stream // directly. It might convert it back into a // string. This is common when interfacing // with some pre-existing tool or library // that expects a source string or file. std::string All; for (auto &Tok : Toks) All += PP.getSpelling(Tok); ... // Write any local declarations or // definitions needed by the // replacement code. OS << getDeclText(PP,D) << "{\n"; ... // Write the replacement function body. OS <<"}\n"; } void AddToPredefines(llvm::raw_string_ostream &OS) override { OS << "#include <something.h>\n"; ... // other definitions } }; } // anonymous namespace static SyntaxHandlerRegistry:: Add<ExampleSyntaxHandler> X("syn-example", "example syntax handler"); \end{lstlisting} \caption{An example showing a Clang syntax handler.} \label{fig:shex} \end{figure} The syntax handler registers the name of the syntax, and the implementation looks for functions with the C++ attribute \texttt{[[clang::syntax(\textit{name})]]}. After the function declaration is parsed, the tokens forming the function body are collected, translated by the plugin, and then the replacement stream is injected into Clang's input in much the same way as an include file is processed. It was discovered that in most non-trivial use cases, the replacement code in the function body required the declaration or definition of other types and functions. Not everything could appear strictly within the body of the function. This presented an implementation challenge: given that the original function declaration has already been parsed and added to the AST by the time the replacement text is generated, and that Clang's AST design makes it difficult to remove the function declaration that has already been processed, how can new declarations and definitions be injected prior to the replaced function body? Strictly speaking, this is not something Clang's AST supports. However, we were able to elide the ordering problem with the following technique: \begin{itemize} \item The original function declaration is completed with a body containing only a call to \texttt{\_\_builtin\_unreachable()}. \item The original function declaration cannot be removed, but it can be renamed, and name in the original function declaration is prefixed with '\_\_' and a non-conflicting string. \item A utility function, \texttt{getDeclText} is provided so that the plugin can easily regenerate the original function declaration after providing whatever other definitions and declarations should proceed it. \end{itemize} Note that the plugin's \texttt{GetReplacement} function is passed the function's \texttt{Declarator} object. This provides access to the function name, type, parameters, and other properties. It is often the case that knowing the names and types of the function parameters makes it easier to support the direct use of those parameters in the DSL source code. The next few sections provide examples of syntax plugins that we have developed, and show how they can provide convenient integration of different kinds of DSLs into C++. \input{tacoplugin} \input{qcor} \input{taprol} \section{Conclusion} \label{sec:con} The syntax plugin infrastructure allows for the efficient, productive integration of DSLs into C++ code bases. Several examples were provided, ranging from quantum computing to sparse and multi-dimensional linear algebra. Moreover, this work demonstrates the utility of extending C++ compilers with powerful plugin interfaces in order to enable novel use cases and provide more-pleasant development environments. In the future, we expect additional DSLs, or maybe even other general-purpose languages (e.g., Python), to be embedded into C++ using syntax plugins. As the technology becomes more wide spread, debuggers, profilers, and other programming-environment tools will need to be enhanced to understand syntax plugins. The syntax-plugin interface itself might grow to add more capabilities. For example, it might be demonstrated that injecting DSL code in more places than just function bodies is useful. Finally, support syntax plugins should be added to the mainline Clang project, and hopefully, similar interfaces will also be added to other C++ implementations. The overall result will be that programmers will be able to increase their productivity by using DSLs without some of the trade offs that currently entails. \section*{Acknowledgment} This work has been supported by the US Department of Energy (DOE) Office of Science Advanced Scientific Computing Research (ASCR) Quantum Computing Application Teams (QCAT), Quantum Algorithms Team (QAT), and Accelerated Research in Quantum Computing (ARQC). This research was also supported by the Exascale Computing Project (17-SC-20-SC), a collaborative effort of the U.S. Department of Energy Office of Science and the National Nuclear Security Administration. ORNL is managed by UT-Battelle, LLC, for the US Department of Energy under contract no. DE-AC05-00OR22725. This research used resources of the Argonne Leadership Computing Facility, which is a DOE Office of Science User Facility supported under Contract DE-AC02-06CH11357. This research used resources of the Oak Ridge Leadership Computing Facility, which is a DOE Office of Science User Facility supported under Contract DE-AC05-00OR22725. We would also like to acknowledge the Laboratory Directed Research and Development (LDRD) funding from the Oak Ridge National Laboratory (award 9463). \bibliographystyle{IEEEtran} \section{Quantum Programming in C\texttt{++}} \label{sec:qcor} Quantum computation has emerged as a potential avenue for the continued scalability of high-performance scientific computing. Current quantum processing units (QPUs) developed by vendors such as IBM, Rigetti, and Google are available for experimentation over the cloud, and a number of interesting toy-model simulations have been demonstrated. These novel processing units provide a small number of qubits, limited connectivity, and are subject to decoherence and other noise sources that limit the overall utility for large scale simulations. However, as quantum architectures continue to advance, one could imagine the future integration of robust QPUs with classical heterogeneous compute resources via a typical co-processor or accelerated computing model. There is therefore a need for research into, and the development of, quantum-classical software infrastructures, languages, and compilers enabling hybrid quantum-classical algorithmic expression. C\texttt{++} has proven ubiquitous in the high-performance computing research space for its performance, portability, and multi-paradigm expressibility. Future CPU-QPU models will require tight integration and fast-feedback capabilities enabling quantum sub-program execution based on qubit measurement results. C\texttt{++} is well-positioned to provide the necessary language and programming model that will enable this tight integration. We therefore seek to extend C\texttt{++} with support for quantum programming, enabling integration of standard C\texttt{++} language utilities with common, popular methods for the expression of quantum code at varying levels of abstraction. \begin{figure}[b!] \centering \includegraphics[width=.45\textwidth]{quantum_kernel_uml.png} \caption{The class diagram for the \texttt{QuantumKernel} template class.} \label{fig:qkernel_uml} \end{figure} \begin{figure}[t!] \lstset {language=C++} \begin{lstlisting} // Programmer code (A.) [[clang::syntax(quantum)]] void ansatz(qreg q, double x) { X(q[0]); Ry(q[1], x); CX(q[1], q[0]); } [[clang::syntax(quantum)]] void do_nothing(qreg q, double x) { ansatz(q, x); ansatz::adjoint(q,x); } [[clang::syntax(quantum)]] void use_ctrl(qreg q, double x) { // qreg of size 3 ansatz::ctrl(q[2], q, x); } ---------- ansatz translates to ------------------ // SyntaxHandler-generated code for ansatz() (B.) void ansatz(qreg q, double x) { void internal_ansatz_call(qreg, double); internal_ansatz_call(q, x); } class ansatz : public QuantumKernel<ansatz, qreg, double> { public: ansatz(qreg q, double x) : QuantumKernel<ansatz, qreg, double>(q,x) {} virtual ~ansatz() { auto [q,x] = args_tuple; // ------------------------------------------- // Generated from Token Analysis auto provider = xacc::getIRProvider(); auto i0 = provider->createInstruction("X",{0}); auto i1 = provider->createInstruction("Ry",{1}, {x}); auto i2 = provider->createInstruction("CX",{1,0}); _parent_kernel->addInstructions({i0,i1,i2}); // ------------------------------------------- auto qpu = xacc::getAccelerator("ibm:ibmq_viqo"); qpu->execute(q, _parent_kernel); } } void internal_ansatz_call(qreg q, double x) { class ansatz temporary_instance(q, x); } ----------- used as function call ---------------- // Using the quantum kernel (C.) int main() { // allocate 2 qubits auto q = qalloc(2); // execute the quantum code ansatz(q, 1.57079632679); // show results q.print(); return 0; } \end{lstlisting} \caption{Code snippet demonstrating quantum kernel programming (A.), its representation after SyntaxHandler processing (B.), and how programmers might invoke the quantum kernel (C.).} \label{fig:sh_code} \end{figure} Here we describe how we leverage the new Clang SyntaxHandler plugin to process functions written in quantum domain specific languages and translate them to appropriate C++ functions composed of valid API calls. Specifically, we leverage the XACC quantum programming framework which provides a collection of C++ libraries enabling the standard quantum programming, compilation, and execution workflow \cite{xacc}. XACC enables a robust API for quantum circuit composition, compilation, and hardware-agnostic execution, with support for QPUs provided by IBM, Rigetti, D-Wave, IonQ, and Honeywell. Ultimately the goal of our SyntaxHandler is to translate general quantum functions in a way that leverages XACC but also provides convenient, automatically-generated related circuits. This model should promote general quantum circuit expressibility, kernel composability, and higher-levels of quantum code abstraction. Figure \ref{fig:qkernel_uml} provides the QuantumKernel class description, the underlying object model that we leverage to represent quantum kernel functions. Our custom SyntaxHandler translates these functions into sub-type definitions of this class. QuantumKernel is templated on the derived type and the kernel function argument types. It exposes constructors that take kernel function arguments as input, and stores them in a protected \texttt{args\_tuple} class attribute. QuantumKernels keep reference to an XACC CompositeInstruction (intermediate representation of a compiled quantum circuit) and the goal of sub-types is to construct this \texttt{\_parent\_kernel} CompositeInstruction dependent on the original quantum kernel definition (before SyntaxHandler processing). QuantumKernel exposes static public methods for automatically generating related circuits for common use cases such as controlled unitary operation and adjoint, or reversal, of the current quantum code. The goal of sub-types is to implement the class destructor such that the internal CompositeInstruction is constructed (representing the quantum code) and to submit or execute that CompositeInstruction on the targeted quantum backend. Note that this process makes use of the input \texttt{args\_tuple} for this quantum circuit generation. This feature enables quantum kernel invocation via temporary class instance construction followed by immediate destruction, but also allows internal development libraries to leverage the full class API for more complex use cases. Figure \ref{fig:sh_code} demonstrates how users can program and use quantum kernel functions and how the SyntaxHandler can translate these invalid function definitions into valid C\texttt{++} code. The workflow put forward by our \texttt{SyntaxHandler::GetReplacement()} begins by converting the vector of Clang Tokens into individual, constituent statements (e.g. in the simplest case, combine Tokens to form a string, stopping at all semicolons). Each of these statements is analyzed to produce an equivalent XACC instruction creation API call that leverages the \texttt{xacc::IRProvider} factory pattern. The SyntaxHandler then sets up the new code to add these instructions to the \texttt{QuantumKernel::\_parent\_kernel} and submit it to the backend \texttt{xacc::Accelerator} for execution (for more information on these XACC data types see \cite{xacc}). This new code string made up of XACC API calls is then added to the destructor call of a newly described QuantumKernel sub-type generated by the SyntaxHandler. This sub-type is of the same name as the original kernel function, and the correct template parameters for the QuantumKernel are configured based on the original function arguments. The original function is re-written to contain a forward declaration to an internal function call that is then immediately called. This function is defined after the class is defined to make use of the temporary instance construction-destruction model of the quantum kernel construction and execution. Since the quantum kernel function is actually a class sub-type of the QuantumKernel after processing of the SyntaxHandler, \texttt{ctrl} and \texttt{adjoint} methods are also available for use within further quantum kernel function definitions (see the second and third functions in section (A.) of the code snippet in Figure \ref{fig:sh_code}). \begin{figure}[b!] \begin{quantikz} \lstick{$\ket{0}$} & \gate{H} & \ctrl{1} & \gate{H} & \meter{} & \rstick{$\bra{\psi} U \ket{\psi} $} \qw \\ \lstick{$\ket{\psi}$} & \ghost{H}\qw & \gate{U} & \qw \end{quantikz} \caption{Quantum circuit implementing the Hadamard test.} \label{fig:htest_circ} \end{figure} \begin{figure}[t!] \lstset {language=C++} \begin{lstlisting} // Hadamard Test, Compute <psi | U | psi>, // Here U = X (pauli x matrix) __qpu__ void x_gate(qreg q) { X(q[1]); } __qpu__ void hadamard_test_x(qreg q) { // Create the superposition on the first qubit H(q[0]); // Apply U = X on second qubit x_gate(q); // apply ctrl-U = C-X, // use QuantumKernel::ctrl x_gate::ctrl(q[0], q); // add the last hadamard H(q[0]); // measure Measure(q[0]); } int main() { // allocate 2 qubits auto q = qalloc(2); // run the hadamard test hadamard_test_x(q); // Get the number of times 1 and 0 were seen auto count1 = q.counts().find("1")->second; auto count0 = q.counts().find("0")->second; // Compute <psi|X|psi> std::cout << "<X> = " << << std::fabs((count1 - count0) / (double)(count1 + count0)) << "\n"; } // Compile with // clang++ -fplugin=/path/to/quantum-syntax.so ... \end{lstlisting} \caption{Code snippet demonstrating a simple Hadamard test. This example demonstrate kernel composability and the utility of the QuantumKernel auto-generated \texttt{ctrl} method.} \label{fig:htest} \end{figure} As a final example of the programmability of a typical benchmark problem in quantum computing leveraging a programming model that uses this novel Clang SyntaxHandler, we present an example known as the Hadamard test. The goal of this test is, given some unitary matrix $U$ and some initial quantum state $\ket{psi}$, compute the expected value of $U$ with respect to that state, $\bra{\psi} U \ket{\psi}$. The quantum circuit for achieving this is shown in Figure \ref{fig:htest_circ}, where one prepares a superposition state on the first qubit (via the application of a Hadamard, H), then prepares a second qubit register into the state $\ket{\psi}$, operates a controlled-$U$ application from the first qubit onto that second qubit register, and finally applies a second Hadamard followed by measurement. The expected value can be computed as the difference between the probability of seeing the $\ket{1}$ and $\ket{0}$ states. We present a program in Figure \ref{fig:htest} that implements this problem for $U=\sigma_x$ and $\ket{\psi}=\ket{1}$. We define one quantum kernel function that represents that unitary $U$ application, \texttt{x\_gate}, and another that runs the Hadamard test itself, \texttt{hadamard\_test\_x}. As one can see, this kernel function starts by applying the first Hadamard gate on the first qubit. We then create $\ket{\psi}=U\ket{0}$ by calling to the \texttt{x\_gate} kernel. Next we leverage the auto-generated \texttt{ctrl} method coming from the QuantumKernel super-class to apply the controlled unitary operation. Finally we add another Hadamard and measure the first qubit. In \texttt{main} we allocate 2 qubits, run the Hadamard test, and compute $\bra{\psi} U \ket{\psi}$, printing it to \texttt{std::cout}. \section{TacoPlug: Embedding Linear Algebra in C/C++} \label{sec:taco} Linear algebra, and specifically linear algebra with sparse inputs, is a fundamental class of algorithms used in scientific computing~\cite{asanovic2006landscape}. Simple expressions involving matricies or tensors, in order to enable efficient execution on modern, parallel architectures with complex memory hierarchies, must be implemented using a complex series of loop nests. Moreover, the best representation for a given sparse matrix depends on its sparsity pattern and the operations one must perform on it. These factors make linear algebra a good match for DSLs, and motivated the creation of TACO, the Tensor Algebra Compiler~\cite{kjolstad2017tensor}. TACO transforms tensor algebra expressions in index notation, along with information on the desired representations of the tensors, into efficient C/C++ code. The relative simplicity of the input to TACO also makes it an excellent candidate for embedding into C++. A function computing a expression on some input matrices or tensors can have its body given directly in the natural mathematical notation. Specifically, we have: \begin{itemize} \item Direct support for tensor index-notation syntax in C/C++. \item Tensors kernels that can be expressed in different formats. \item Support for custom data structures thereby providing easy integration with existing C/C++ applications. \end{itemize} \begin{figure} \centering \begin{subfigure}[b]{\linewidth} \centering \begin{lstlisting} // Custom data structure for some struct <name> typedef struct <name> { .... // Plugin requires to and from conversion // routines to use custom data structures // with TACOPlug. taco_tensor_t* (* <name>2taco)(struct <name> *); void (* taco2<name>) (taco_tensor_t*,struct <name>* ); } <name>; \end{lstlisting} \caption{Code illustrating support for custom tensor data structures.} \label{fig:tp_cds} \end{subfigure} \begin{subfigure}[b]{\linewidth} \centering \begin{lstlisting} [[clang::syntax(taco)]] void matrix_vector_mul (vector *y,csr *A,vector *x, std::string format= " -f=A:ds:0,1 -f=x:d -f=y:d") { y(i) = A(i,j) * x(j) } \end{lstlisting} \caption{Code illustrating how programmers use TACOPlug to define a function.} \label{fig:tp_decl} \end{subfigure} \begin{subfigure}[b]{\linewidth} \centering \begin{lstlisting} matrix_vector_mul(&vector_y, &matrix_csr_A, &vector_x); \end{lstlisting} \caption{Code illustrating how programmers call the function processed by TACOPlug.} \label{fig:tp_call} \end{subfigure} \hfill \caption{Example TACOPlug Usage} \label{fig:tp_usage} \end{figure} \begin{figure} \centering \begin{subfigure}[b]{\linewidth} \centering \begin{lstlisting} // Generated by TACO: int __taco_comput_1(taco_tensor_t *, taco_tensor_t *,taco_tensor_t *); int __taco_assm_1(taco_tensor_t *, taco_tensor_t *,taco_tensor_t *); // Assembly Code. int __taco_assm_1 (taco_tensor_t *y, taco_tensor_t *A, taco_tensor_t *x) { int y1_dimension = (int)(y->dimensions[0]); .... y->vals = (uint8_t*)y_vals; return 0; } // Compute Code. int __taco_comput_1(taco_tensor_t *y, taco_tensor_t *A, taco_tensor_t *x) { .... #pragma omp parallel for schedule(runtime) for (int32_t i = 0; i < A1_dimension; i++) { double tjy_val = 0.0; for (int32_t jA = A2_pos[i]; jA < A2_pos[(i + 1)]; jA++) { int32_t j = A2_crd[jA]; tjy_val += A_vals[jA] * x_vals[j]; } y_vals[i] = tjy_val; } return 0; } \end{lstlisting} \caption{Example code generated by TACO.} \label{fig:tp_cgen} \end{subfigure} \begin{subfigure}[b]{\linewidth} \centering \begin{lstlisting} void mat_vec_mul(vector *y, csr *A, vector *x, std::string format= "-f=A:ds:0,1 -f=y:d -f=x:d"){ taco_tensor_t * __taco_y = y->vector2taco (y); taco_tensor_t * __taco_A = A->csr2taco (A); taco_tensor_t * __taco_x = x->vector2taco (x); __taco_assm_1(__taco_y,__taco_A,__taco_x); __taco_comput_1(__taco_y,__taco_A,__taco_x); y->taco2vector(__taco_y,y); __taco_cleanup_taco(__taco_y); __taco_cleanup_taco(__taco_A); __taco_cleanup_taco(__taco_x); } \end{lstlisting} \caption{Example code generated by TACOPlug.} \label{fig:tp_cgenp} \end{subfigure} \hfill \caption{Example TACO/TACOPlug-Generated Code} \label{fig:tp_allgc} \end{figure} \subsection{TACO - Existing Interfaces} TACO generates kernels for sparse and dense tensor expressions using a mathematical index notation. The tensor index notation used by TACO is a variation of the work done in by Ricci Curbastro and Levi Civita \cite{Ricci1901}. TACO provides a C++ library interface, which might also be considered a kind of \textit{embedded} DSL, to express tensor index notation using operator overloading and templating. Figure~\ref{fig:tensor_index_notation} shows a tensor index notation for a sparse matrix-vector multiplication. The equivalent code using TACO's C++ library interface is shown in Figure~\ref{fig:taco_dsl}. As can be seen, the mathematical notation is more succinct than that required by the library interface. TACO also provides a command-line tool that consumes a succinct notation that is closely related to the associated mathematical notation. A sparse matrix-vector multiplication is shown in Figure~\ref{fig:tensor_command_line}. In Figure~\ref{fig:tensor_command_line}, the first argument, \texttt{y(i) = A(i,j) * x (j)}, is the actual tensor-algebra index notation, \texttt{-f=A:ds:0,1} describes the tensor format of \texttt{A}; \texttt{ds} describes a CSR tensor, \texttt{0,1} describes the data layout of the tensor. See~\cite{Chou2018} for a more-detailed description of the input format and the supported options. TACO generates assembly code and compute code. The assemble code allocates memory to store the result of the tensor-algebra computation while the compute code performs the actual computation. TACO uses a unique data structure, taco\_tensor\_t, to store the value and coordinate information of the sparse tensor format. The code generated by TACO performs computation directly on this data structure. The compile call on the object \texttt{y} in Figure~\ref{fig:taco_dsl} generates code as required, compiles the code into a shared library, and dynamically loads it with dlopen. \subsection{TACOPlug Syntax} TACOPlug provides support for tensor-index notation in C/C++ using TACO. Figure~\ref{fig:tp_decl} shows TACOPlug's function-declaration syntax. The function body is the tensor index notation describing the computation. The tensor names used in the notation must have corresponding function parameters with the same name. The final argument in the function declaration must be a string variable with a default string specifying the format of the computation. It is necessary to describe the format of each tensor because TACO supports code generation for many combinations of different tensor formats. The format specification follows closely the format specification accepted by the TACO command-line tool. \subsection{TACOPlug Code Generation} TACOPlug uses the syntax-handler interface to allow the definition of functions computing sparse-matrix using TACO's sucinct syntax. The function declaration body is parsed to get the actual tensor-index notation and the format specification of the computation. TACOPlug performs a check to ensure that there is an actual parameter for each tensor in the notation. After a successful type check, the tensor-index notation and format specification is sent directly to TACO for code generation. TACO generates compute and assembly code which can be seen in Figure~\ref{fig:tp_cgen}. A unique number is appended to each compute and assembly functions generated by TACO to ensure that all declarations are unique. \subsection{Supporting Custom Data Structures} TACO generates code that uses taco\_tensor\_t, therefore for TACOPlug to work with functions taking other data structures, those data structures must have associated conversion procedures to and from taco\_tensor\_t. Specifically, there must be to be \textit{to} and \textit{from} function pointers present in the struct. Figure~\ref{fig:tp_cds} shows a sample custom data structure. The asymptotic cost of converting to and from taco\_tensor\_t for sparse and dense tensors is $O(n)$ where $n$ is the mode of the tensor. TACOPlug automatically calls conversion routines for non-taco\_tensor\_t parameter types. Support for custom data structures is essential for integration of TACOPlug with exiting applications. \begin{figure} \centering \begin{subfigure}[b]{\linewidth} \centering \begin{equation*} y(i) = A(i,j) * x (j) \end{equation*} \caption{Tensor Index Notation} \label{fig:tensor_index_notation} \end{subfigure} \begin{subfigure}[b]{\linewidth} \centering \begin{lstlisting} taco "y(i) = A(i,j) * x (j)"\\ -f=A:ds:0,1 -f=x:d -f=y:d \end{lstlisting} \caption{Taco Command Line} \label{fig:tensor_command_line} \end{subfigure} \begin{subfigure}[b]{\linewidth} \centering \begin{lstlisting} Format csr({Dense,Sparse}); Format dv({Dense}); Tensor<double> A; Tensor<double> x({A.getDimension(1)}, dv); Tensor<double> y({A.getDimension(0)}, dv); IndexVar i,j; y(i) = A(i,j) * x (j); y.compile(); y.assemble(); y.compute(); \end{lstlisting} \caption{Taco DSL} \label{fig:taco_dsl} \end{subfigure} \hfill \caption{Sparse Matrix Vector Multiplication } \label{fig:three graphs} \end{figure} \section{TAProL-Plug: Embedding Tensor Network Theory in C++} \label{sec:taprol} TAProL (Tensor Algebra Programming Language) is a concise mathematical-notation DSL for expressing numerical tensor algebra algorithms dealing with tensor networks (it is part of the ExaTN library~\cite{exatn}). It supports basic tensor operations, like tensor scaling, tensor addition, tensor product, tensor contraction, as well as higher-level tensor operations, like tensor decompositions. The latter are formalized via the tensor network theory, where a tensor network approximates a given higher-order tensor as a specifically structured contraction of lower-order tensors. The specific form of the tensor contraction used, that is, the topology of the tensor network, determines its class, with the most widely used classes being the tensor train (TT) or, equivalently, matrix product state (MPS)~\cite{mps}, projected entangled pair state (PEPS)~\cite{peps}, tensor tree network (TTN)~\cite{ttns}, or, equivalently, the hierarchical Tucker decomposition, and multiple entanglement renormalization ansatz (MERA)~\cite{mera}, to name a few. Low-rank tensor decompositions and factorizations based on the tensor networks have been successfully utilized for approximating quantum many-body wavefunctions in condensed matter physics~\cite{mera}, quantum chemistry~\cite{ttns_chan} and quantum computing~\cite{mps_tnqvm}. Recently they have also been used for the tensor completion problem~\cite{tensor_completion} as well as neural network layer regularization in machine learning~\cite{dnn_tn_regular}. \begin{figure}[t!] \centering \begin{lstlisting} [[clang::syntax(taprol)]] void test(std::vector<std::complex<double>>& t2_data, std::shared_ptr<talsh::Tensor> talsh_t2, std::shared_ptr<talsh::Tensor> talsh_x2, double& norm_x2) { //Declaring the TAProL entry point: entry: main; //Opening a TAProL scope (optional): scope main group(tensor_workload); //Declaring linear spaces of some dimension: space(complex): space0 = [0:255], space1 = [0:511]; //Declaring subspaces of declared linear spaces: subspace(space0): s0 = [0:127], s1 = [128:255]; subspace(space1): r0 = [0:283], r1 = [284:511]; //Associating index labels with declared subspaces: index(s0): i, j, k, l; index(r0): a, b, c, d; //Initializing a tensor to zero: Z2(a, b, i, j) = {0.0, 0.0}; //Initializing a tensor by a registered functor: H2(a, i, b, j) = method("ComputeHamiltonian"); //Initializing a tensor by external C++ data: T2(a, b, i, j) = t2_data; //Contracting two tensors: Z2(a, b, i, j) += H2(a, k, c, i) * T2(b, c, k, j); //Contracting three tensors (tensor network): Z2(a, b, i, j) += H2(c, k, d, l) * T2(c, d, i, j) * T2(a, b, k, l); //Scaling a tensor by a scalar: Z2(a, b, i, j) *= 0.25; //Adding a tensor to another tensor: T2(a, b, i, j) += Z2(a, b, i, j); //Decomposing tensor T2 into two factors: A(a, b, c) = {0.0, 0.0}; B(i, j, c) = {0.0, 0.0}; A(a, b, c) * B(i, j, c) = T2(a, b, i, j); //Exporting tensor T2 back to C++: talsh_t2 = T2; //Computing the 2-norm of tensor Z2: X2() = {0.0, 0.0}; X2() += Z2+(a, b, i, j) * Z2(a, b, i, j); norm_x2 = norm1(X2); //Exporting scalar X2 back to C++: talsh_x2 = X2; //Saving scalar X2: save X2: tag("Z2_norm2"); //Destroying tensors X2 and Z2: ~X2; ~Z2; //Destroying other tensors (alternative): destroy A, B, T2, H2; end scope main; } \end{lstlisting} \caption{TAProL code example} \label{fig:taprolplug} \end{figure} The TAProL code consists of a mix of declarative and executive statements (see Fig. \ref{fig:taprolplug}). Declarative statements are used to declare linear spaces, their subspaces, and indices associated with those subspaces. These spaces/subspaces are used for defining tensors (each tensor dimension is associated with a declared subspace). The executive statements define either simple or composite tensor operations. Simple tensor operations are tensor initialization, tensor scaling, tensor addition, tensor product, binary tensor contraction, etc. Tensor initialization has a number of variants. In particular, one can initialize a tensor from externally provided data stored in a C++ std::vector container. Additionally, one can also initialize or transform a tensor using a user-defined C++ functor, thus enabling custom unary operations on TAProL tensors written in C++. Composite tensor operations include (a) arbitrary tensor contractions of three or more tensors (contraction of a tensor network), and (b) tensor decompositions, which are the opposites of the tensor contractions (see Fig. \ref{fig:taprolplug}). To export a TAProL tensor back to the C++ realm, one can use a pre-defined C++ class talsh::Tensor provided by the ExaTN library. For further convenience, TAProL statements can be organized into scopes (TAProL analogs of routines) inside a C++ function. During the compilation, the TAProL clang syntax plugin translates the TAProL code into the calls to the ExaTN library C++ API. Simple tensor operations are scheduled for asynchronous execution via a dynamic task graph during program execution. Composite tensor operations are first decomposed into simple tensor operations which are subsequently added into the task graph during program execution as well. The parallel runtime of the ExaTN library attempts to automatically decompose and distribute tensor operations among all computing devices across a given set of compute nodes. The runtime also automatically tracks all data dependencies, thus allowing the user to write serial programs that will be transparently parallelized by the ExaTN library runtime. This enables the execution of tensor algebra workloads on a computer of any scale, from laptops to leadership HPC systems.
{'timestamp': '2020-10-19T02:19:24', 'yymm': '2010', 'arxiv_id': '2010.08439', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08439'}
arxiv
\section{Introduction} \label{sec:introduction} Multivariate circular observations arise commonly in all those fields where a quantity of interest is measured as a direction or when instruments such as compasses, protractors, weather vanes, sextants or theodolites are used \citep{Mardia1972}. Circular (or directional) data can be seen as points on the unit circle and represented by angles, provided that an initial direction and orientation of the circle have been chosen. These data might be successfully modeled by using appropriate wrapped distributions such as the Wrapped Normal on the unit circle. The reader is pointed to \citet{MardiaJupp2000}, \citet{JammalamadakaSenGupta2001} and \citet{Batschelet1981} for modeling and inferential issues on circular data. When data come in a multivariate setting, we might extend the univariate wrapped distribution by using a component-wise wrapping of multivariate distributions. The multivariate Wrapped Normal ($WN_p$) is obtained by component-wise wrapping of a $p$-variate Normal distribution ($N_p$) on a $p-$dimensional torus \citep{JohnsonWehrly1978, Baba1981}. Wrapping can be explained as the geometric translation of a distribution with support on $\mathbb{R}$ to a space defined on a \textit{circular} object, e.g., a unit circle \citep{MardiaJupp2000}. Let $\vect{X} \sim N_p(\vect{\mu}, \Sigma)$, where $\vect{\mu}$ is the vector mean and $\Sigma$ is the variance-covariance matrix. Then, the distribution of $\vect{Y} = \vect{X} \ \textrm{mod} \ 2\pi$ is denoted as $WN_p(\vect{\mu},\Sigma)$ with distribution function \begin{equation*} F(\vect{y})= \sum_{\vect{j} \in \mathbb{Z}^p} [\Phi_p(\vect{y} + 2 \pi \vect{j}; \Omega)- \Phi_p(2 \pi \vect{j}; \Omega) ] \ , \end{equation*} and density function \begin{equation*} f(\vect{y})= \sum_{\vect{j} \in \mathbb{Z}^p} \phi_p(\vect{y} + 2 \pi \vect{j}; \Omega) \ , \end{equation*} with $\vect{y} \in(0,2\pi]^p$, $\vect{j}\in\mathbb{Z}^p$, $\Omega=(\vect{\mu},\Sigma)$, where $\Phi_p(\cdot)$ and $\phi_p(\cdot)$ are the distribution and density function of $\vect{X}$, respectively, and the modulus operator \textrm{mod} is applied component-wise. An appealing property of the wrapped Normal distribution is its closure with respect to convolution \citep{Baba1981, JammalamadakaSenGupta2001}. Likelihood based inference about the parameters of the $WN_p(\vect{\mu},\Sigma)$ distribution can be trapped in numerical and computational hindrances since the log-likelihood function \begin{equation*} \label{equ:loglik} \ell(\Omega) = \sum_{i=1}^n \log \left[ \sum_{\vect{j} \in \mathbb{Z}^p} \phi_p(\vect{y}_i + 2 \pi \vect{j}; \Omega) \right] \, \end{equation*} involves the evaluation of an infinite series. \citet{Agostinelli2007} proposed an Iterative Reweighted Maximum Likelihood Estimating Equations algorithm in the univariate setting, that is available in the \texttt{R} package \texttt{circular} \citep{AgostinelliLund2017}. Algorithms bases on the Expectation-Maximization (EM) method have been used by \citet{Fisher1994} for parameter estimation for autoregressive models of Wrapped Normal distributions and by \citet{Coles1998}, \citet{Ravindran2011} and \citet{Ferrari2009} in a Bayesian framework according to a data augmentation approach to estimate the missing unobserved wrapping coefficients. An innovative estimation strategy based on EM and Classification EM algorithms has been discussed in \citet{nodehi2018estimation}. In order to perform maximum likelihood estimation, the wrapping coefficients are treated as latent variables. Let $\vect{y}_1, \ldots, \vect{y}_n$ be a i.i.d. sample from a multivariate Wrapped Normal distribution $\vect{Y} \sim WN_p(\vect{\mu}, \Sigma)$ on the $p$-torus with mean vector $\vect{\mu}$ and variance-covariance matrix $\Sigma$. We can think of $\vect{y}_i = \vect{x}_i \mod 2\pi$ where $\vect{x}_i$ is a sample from $\vect{X}_i \sim N_p(\vect{\mu}, \Sigma)$. The EM algorithm works with the complete log-likelihood function given by \begin{equation} \label{equ:completeloglik} \ell_C(\Omega) = \sum_{i=1}^n \log\left[ \sum_{\vect{j} \in \mathbb{Z}^p} v_{i\vect{j}} \phi(\vect{y}_i + 2 \pi \vect{j}; \Omega)\right] \ , \end{equation} that is characterized by the missing unobserved wrapping coefficients $\vect{j}$ and $v_{i\vect{j}}$ is an indicator of the $i$th unit having the $\vect{j}$ vector as wrapping coefficients. The EM algorithm iterates between an Expectation (E) step and a Maximization (M) step. In the E-step, the conditional expectation of (\ref{equ:completeloglik}) is obtained by estimating the $v_{i\vect{j}}$ with the posterior probability that $\vect{y}_i$ has $\vect{j}$ as wrapping coefficients based on current parameters' values, i.e. \begin{equation*} v_{i\vect{j}} = \frac{\phi(\vect{y}_i + 2 \pi \vect{j}; \Omega)}{\sum_{\vect{h} \in \mathbb{Z}^p} \phi(\vect{y}_i + 2 \pi \vect{h}; \Omega)} \ , \qquad \vect{j} \in \mathbb{Z}^p, \quad i=1,\ldots,n \ . \end{equation*} In the M-step, the conditional expectation of (\ref{equ:completeloglik}) is maximized with respect to $\Omega$. The reader is pointed to \citet{nodehi2018estimation} for computational details about such maximization problem and updating formulas for $\Omega$. An alternative estimation strategy is based on the CEM-type algorithm. The substantial difference is that the E-step is followed by a C-step (where C stands for classification) in which $v_{i\vect{j}}$ is estimated as either 0 or 1 and so that each observation $\vect{y}_i$ is associated to the most likely wrapping coefficients $\vect{j}_i$ with $\vect{j}_i = \arg\max_{\vect{h} \in \mathbb{Z}^p} v_{i\vect{h}}$. When the sample data is contaminated by the occurrence of outliers, it is well known that maximum likelihood estimation, also achieved through the implementation of the EM or CEM algorithm, is likely to lead to unreliable results \citep{farcomeni2016robust}. Then, there is the need for a suitable robust procedure providing protection against those unexpected anomalous values. An attractive solution would be to modify the likelihood equations in the M-step by introducing a set of weights aimed to bound the effect of outliers. Here, it is suggested to evaluate weights according to the weighted likelihood methodology \citep{markatou1998}. Weighted likelihood is an appealing robust technique for estimation and testing \citep{agostinelli2001test}. The methodology leads to a robust fit and gives the chance to detect possible substructures in the data. Furthermore, the weighted likelihood methodology works in a very satisfactory fashion when combined with the EM and CEM algorithms, as in the case of mixture models \citep{greco2018weighted, greco2020weighted}. The remainder of the paper is organized as follows. Section \ref{back} gives brief but necessary preliminaries on weighted likelihood. The weighted CEM algorithm for robust fitting of the multivariate Wrapped Normal model on data on a $p-$dimensional torus is discussed in Section \ref{sec:estimation}. Section \ref{sec:simulations} reports the results of some numerical studies, whereas a real data example is discussed in Section \ref{sec:examples}. Concluding remarks end the paper. \section{Preliminaries on weighted likelihood} \label{back} Let $\vect{y}_1, \cdots, \vect{y}_n$ be a random sample of size $n$ drawn from a r.v. $\vect{Y}$ with distribution function $F$ and probability (density) function $f$. Let $\mathcal{M} = \{ M(\vect{y}; \vect{\theta}), \vect{\theta} \in \Theta \subseteq \mathbb{R}^d, d \geq 1, \vect{y} \in \mathcal{Y} \}$ be the assumed parametric model, with corresponding density $m(\vect{y};\vect{\theta})$, and $\hat F_n$ the empirical distribution function. Assume that the support of $F$ is the same as that of $M$ and independent of $\vect{\theta}$. A measure of the agreement between the {\it true} and assumed model is provided by the Pearson residual function $\delta(\vect{y})$, with $\delta(\vect{y})\in [-1,+\infty)$, \citep{lindsay1994, markatou1998}, defined as \begin{equation} \label{pearson} \delta(\vect{y}) = \delta(\vect{y}; \vect{\theta}, F) = \frac{f(\vect{y})}{m(\vect{y}; \vect{\theta})} - 1 \ . \end{equation} The finite sample counterpart of (\ref{pearson}) can be obtained as \begin{equation} \label{residualfs} \delta_n(\vect{y}) = \delta(\vect{y}; \vect{\theta}, \hat F_n) = \frac{\hat f_n(\vect{y})}{m(\vect{y}; \vect{\theta})} - 1 \ , \end{equation} where $\hat f_n(\vect{y})$ is a consistent estimate of the true density $f(\vect{y})$. In discrete families of distributions, $\hat{f}_n(\vect{y})$ can be driven by the observed relative frequencies \citep{lindsay1994}, whereas in continuous models one could consider a non parametric density estimate based on the kernel function $k(\vect{y};\vect{t},h)$, that is \begin{equation} \label{eqn:parametric-density} \hat f_n(\vect{y})=\int_\mathcal{Y}k(\vect{y};\vect{t},h)d\hat F_n(\vect{t}) \ . \end{equation} Moreover, in the continuous case, the model density in (\ref{residualfs}) can be replaced by a smoothed model density, obtained by using the same kernel involved in non-parametric density estimation \citep{basu1994minimum, markatou1998}, that is \begin{equation*} \hat m(\vect{y}; \vect{\theta})=\int_\mathcal{Y}k(\vect{y};\vect{t},h)m(\vect{t};\vect{\theta}) \ d\vect{t} \ \end{equation*} leading to \begin{equation} \label{residualfs2} \delta_n(\vect{y}) = \delta(\vect{y}; \vect{\theta}, \hat F_n) = \frac{\hat f_n(\vect{y})}{\hat m(\vect{y}; \vect{\theta})} - 1 \ . \end{equation} By smoothing the model, the Pearson residuals in (\ref{residualfs2}) converge to zero with probability one for every $\vect{y}$ under the assumed model and it is not required that the kernel bandwidth $h$ goes to zero as the sample size $n$ increases. Large values of the Pearson residual function correspond to regions of the support $\mathcal{Y}$ where the model fits the data poorly, meaning that the observation is unlikely to occur under the assumed model. The reader is pointed to \cite{basu1994minimum}, \cite{markatou1998}, \cite{agostinelli2019weighted} and references therein for more details. Observations leading to large Pearson residuals in (\ref{residualfs2}) are supposed to be down-weighted. Then, a weight in the interval $[0,1]$ is attached to each data point, that is computed accordingly to the following weight function \begin{equation} \label{weight} w(\delta(\vect{y})) = \frac{\left[A(\delta(\vect{y})) + 1\right]^+}{\delta(\vect{y}) + 1} \ , \end{equation} where $w(\delta)\in[0,1]$, $[\cdot]^+$ denotes the positive part and $A(\delta)$ is the Residual Adjustment Function (RAF, \cite{basu1994minimum}). The weights $w(\delta_n(\vect{y}))$ are meant to be small for those data points that are in disagreement with the assumed model. Actually, the RAF plays the role to bound the effect of large Pearson residuals on the fitting procedure. By using a RAF such that $|A(\delta)| \le |\delta|$ outliers are expected to be properly downweighted. The weight function (\ref{weight}) can be based on the families of RAF stemming from the Symmetric Chi-squared divergence \citep{markatou1998}, the Generalized Kullback-Leibler divergence \citep{park+basu+2003} \begin{equation} \label{eq:raf-gkl} A_{gkl}(\delta, \tau)=\frac{\log (\tau\delta+1)}{\tau}, \ 0\leq \tau \leq 1; \end{equation} or the Power Divergence Measure \citep{cressie+1984, cressie+1988} \begin{equation*} A_{pdm}(\delta, \tau) = \left\{ \begin{array}{lc} \tau \left( (\delta + 1)^{1/\tau} - 1 \right) & \tau < \infty \\ \log(\delta + 1) & \tau \rightarrow \infty \ . \end{array} \right . \end{equation*} The resulting weight function is unimodal and declines smoothly to zero as $\delta(\vect{y})\rightarrow -1$ or $\delta(\vect{y})\rightarrow\infty$. Then, robust estimation can be based on a Weighted Likelihood Estimating Equation (WLEE), defined as \begin{equation} \label{equ+wlee} \sum_{i=1}^n w(\delta_n(\vect{y}_i); \vect{\theta}, \hat{F}_n) s(\vect{y}_i; \vect{\theta}) = 0 \ , \end{equation} where $s(\vect{y}_i;\vect{\theta})$ is the individual contribution to the score function. Therefore, weighted likelihood estimation can be thought as a root solving problem. Finding the solution of (\ref{equ+wlee}) requires an iterative weighting algorithm. The corresponding weighted likelihood estimator $\hat{\vect{\theta}}^w$ (WLE) is consistent, asymptotically normal and fully efficient at the assumed model, under some general regularity conditions pertaining the model, the kernel and the weight function \citep{markatou1998, agostinelli2001test, agostinelli2019weighted}. Its robustness properties have been established in \citet{lindsay1994} in connection with minimum disparity problems. It is worth to remark that under very standard conditions, one can build a simple WLEE matching a minimum disparity objective function, hence inheriting its robustness properties. In finite samples, the robustness/efficiency trade-off of weighted likelihood estimation can be tuned by varying the smoothing parameter $h$ in equation (\ref{eqn:parametric-density}). Large values of $h$ lead to Pearson residuals all close to zero and weights all close to one and, hence, large efficiency, since $\hat f_n(\vect{y})$ is stochastically close to the postulated model. On the other hand, small values of $h$ make $\hat f_n(\vect{y})$ more sensitive to the occurrence of outliers and the Pearson residuals become large for those data points that are in disagreement with the model. On the contrary, the shape of the kernel function $k(\vect{y};\vect{t},h)$ has a very limited effect. For what concerns the tasks of testing and setting confidence regions, a weighted likelihood counterparts of the classical likelihood ratio test, and its asymptotically equivalent Wald and Score versions, can be established. Note that, all share the standard asymptotic distribution at the model, according to the results stated in \citep{agostinelli2001test}, that is $$ \Lambda(\vect{\theta})=2\sum_{i=1}^nw_i\left[\ell(\hat{\vect{\theta}}^w; \vect{y}_i)-\ell(\vect{\theta}; \vect{y}_i)\right]\stackrel{p}{\rightarrow}\chi^2_p \ , $$ with $w_i= w(\delta_n(\vect{y}_i); \hat{\vect{\theta}}^w, \hat{F}_n) $. Profile tests can be obtained as well. \section{A weighted CEM algorithm} \label{sec:estimation} As previously stated in the Introduction, \citet{nodehi2018estimation} provided effective iterative algorithms to fit a multivariate Wrapped normal distribution on the $p-$dimensional torus. Here, robust estimation is achieved by a suitable modification of their CEM algorithm, consisting in a weighting step before performing the M-step, in which data-dependent weights are evaluated according to (\ref{weight}) yielding a WLEE (\ref{equ+wlee}) to be solved in the M-step. The construction of Pearson residuals in (\ref{residualfs2}) involves a multivariate Wrapped Normal kernel with covariance matrix $h \Lambda$. Since the family of multivariate Wrapped Normal is closed under convolution, then the smoothed model density is still Wrapped Normal with covariance matrix $\Sigma+h\Lambda$. Here, we set $\Lambda = \Sigma$ so that $h$ can be a constant independent of the variance-covariance structure of the data. The weighted CEM algorithm is structured as follows: \begin{itemize} \item[0] {\bf Initialization}, Starting values can be obtained by maximum likelihood estimation evaluated over a randomly chosen subset. The subsample size is expected to be as small as possible in order to increase the probability to get an outliers' free initial subset but large enough to guarantee estimation of the unknown parameters. A starting solution for $\mu$ can be obtained by the circular means, whereas the diagonal entries of $\Sigma$ can be initialized as $-2\log(\hat{\rho}_r)$, where $\hat{\rho}_r$ is the sample mean resultant length and the off-diagonal elements by $\rho_c(\vect{y}_r, \vect{y}_s) \sigma_{rr}^{(0)} \sigma_{ss}^{(0)}$ ($r \neq s$), where $\rho_c(\vect{y}_r, \vect{y}_s)$ is the circular correlation coefficient, $r=1,2,\ldots,p$ and $s=1,2,\ldots,p$, see \citet[][pag. 176, equation 8.2.2]{JammalamadakaSenGupta2001}. In order to avoid the algorithm to be dependent on initial values, a simple and common strategy is to run the algorithm from a number of starting values using the bootstrap root searching approach as in \citet{markatou1998}. A criterion to choose among different solutions will be illustrated in Section \ref{sec:examples}. \item[1] {\bf E-step}. Based on current parameters' values, first evaluate posterior probabilities $$v_{i\vect{j}} = \frac{\phi(\vect{y}_i + 2 \pi \vect{j}; \Omega)}{\sum_{\vect{h} \in \mathbb{Z}^p} \phi(\vect{y}_i + 2 \pi \vect{h}; \Omega)} \ , \qquad \vect{j} \in \mathbb{Z}^p, \quad i=1,\ldots,n \ ,$$ \item[2] {\bf C-step} Set $\vect{j}_i = \arg\max_{\vect{h} \in \mathbb{Z}^p} v_{i\vect{h}}$, where $v_{i\vect{j}}=1$ for $\vect{j}=\vect{j}_i$, and $v_{i\vect{j}}=0$ otherwise. \item[3] {\bf W-step} (Weighting step) Based on current parameters' values, compute Pearson residuals according to (\ref{residualfs2}) based on a multivariate Wrapped Normal kernel with bandwidth $h$ and evaluate the weights as \begin{equation*} w_i=w(\delta_n(\vect{y}_i), \Omega, \hat F_n). \end{equation*} \item[4] {\bf M-step} Update parameters' values by computing a weighted mean and variance-covariance matrix with weights $w_i$, used to compute estimates, by maximizing the classification log-likelihood conditionally on $\hat{\vect{j}}_i$ $(i = 1,\ldots,n)$, given by \begin{align*} \hat{\vect{\mu}}_i &= \frac{\sum_{i=1}^n w_i \hat{\vect{x}}_i}{\sum_{i=1}^n w_i}, \\ \Sigma_{ij} &= \frac{\sum_{i=1}^n (\hat{\vect{x}}_i - \hat{\vect{\mu}}_i)^\top (\hat{\vect{x}}_j - \hat{\vect{\mu}}_j)w_i}{\sum_{i=1}^n w_i}. \end{align*} Note that, at each iteration the classification algorithm provides also an estimate of the original unobserved sample obtained as $\hat{\vect{x}}_i = \vect{y}_i + 2 \pi \hat{\vect{j}}_i$, $i = 1, \ldots, n$. \end{itemize} \section{Numerical studies} \label{sec:simulations} The finite sample behavior of the proposed weighted CEM has been investigated by some numerical studies based on 500 Monte Carlo trials each. Data have been drawn from a $WN_p(\vect{\mu},\Sigma)$. We set $\vect{\mu}=0$, whereas in order to account for the lack of affine equivariance of the Wrapped Normal model \citep{nodehi2018estimation}, we consider different covariance structures $\Sigma$ as in \citet{AgostinelliEtAll2015}. In particular, for fixed condition number $CN = 20$, we construct a random correlation matrix $R$. Then, we convert the correlation matrix $R$ into the covariance matrix $\Sigma = D^{1/2} R D^{1/2}$, with $D=\textrm{diag}(\sigma\vect{1}_p)$, where $\sigma$ is a chosen constant and $\vect{1}_p$ is a $p$-dimensional vector of ones. Outliers have been obtained by shifting a proportion $\epsilon$ of randomly chosen data points by an amount $k_\epsilon$ in the direction of the smallest eigenvalue of $\Sigma$. We consider sample sizes $n=50,100,500$, dimensions $p=2,5$, contamination level $\epsilon=0, 5\%, 10\%, 20\%$, contamination size $k_\epsilon=\pi/4, \pi/2, \pi$ and $\sigma=\pi/8, \pi/4, \pi/2$. For each combination of the simulation parameters, we are going to compare the performance of CEM and weighted CEM algorithms. The weights used in the W-step are computed using the Generalized Kullback-Leibler RAF in equation (\ref{eq:raf-gkl}) with $\tau = 0.1$. According to the strategy described in \cite{agostinelli2001test}, the bandwidth $h$ has been selected by setting $\Lambda = \Sigma$, so that $h$ is a constant independent of the scale of the model. Here, $h$ is obtained so that any outlying observation located at least three standard deviations away from the mean in a componentwise fashion, is attached a weight not larger than 0.12 when the rate of contamination in the data has been fixed equal to $20\%$. The algorithm has been initialized according to the root search approach described in \cite{markatou1998} based on $15$ subsamples of size $10$. The weighted CEM is assumed to have reached convergence when at the $(k+1)$th iteration $$ \max \left(\sqrt{2(1-\cos(\hat{\vect{\mu}}^{(k)}-\hat{\vect{\mu}}^{(k+1)}))}, \max|\hat{\Sigma}^{(k)}-\hat{\Sigma}^{(k+1)} | \right) <10^{-6}. $$ The algorithm has been implemented so that $\mathbb{Z}^p$ is replaced by the Cartesian product $\times_{s=1}^p \vect{\mathcal{J}}$ where $\vect{\mathcal{J}} = (-J, -J+1, \ldots, 0, \ldots, J-1, J)$ for some $J$ providing a good approximation. Here we set $J=3$. The algorithm runs on \texttt{R} code \citep{cran} available from the authors upon request. Fitting accuracy has been evaluated according to \begin{itemize} \item[(i)] the average angle separation \begin{equation*} \operatorname{AS}(\hat{\vect{\mu}}) = \frac{1}{p} \sum_{i=1}^p (1 - \cos(\hat{\vect{\mu}}_i - \vect{\mu}_{i})) \ , \end{equation*} which ranges in $[0, 2]$, for the mean vector; \item[(ii)] the divergence \begin{equation*} \Delta(\hat{\Sigma}) = \operatorname{trace}(\hat{\Sigma} \Sigma^{-1}) - \log(| \hat{\Sigma} \Sigma^{-1} |) - p \ , \end{equation*} \end{itemize} for the variance-covariance matrix. Here, we only report the results stemming from the challenging situation with $n=100$ and $p=5$. Figure \ref{fig:one} displays the average angle separation whereas Figure \ref{fig:two} gives the divergence to measure the accuracy in estimating the variance-covariance matrix for the weighted CEM (in green) and CEM (in red). The weighted CEM exhibits a fairly satisfactory fitting accuracy both under the assumed model (i.e. when the sample at hand is not corrupted by the occurrence of outliers) and under contamination. The robust method outperforms the CEM method, especially in the estimation of the variance-covariance components. The algorithm results in biased estimates for both the mean vector and the variance-covariance matrix only for the large contamination rate $\epsilon=20\%$, with small contamination size and a large $\sigma$. Actually, in this data constellation outliers are not well separated from the group of genuine observations. A similar behavior has been observed for the other sample sizes. Complete results are made available in the Supplementary Material. \begin{figure} \begin{center} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-5-100-1-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-5-100-1-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-5-100-1-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-5-100-2-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-5-100-2-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-5-100-2-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-5-100-3-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-5-100-3-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-5-100-3-3} \\ \end{center} \caption{Distribution of average angle separation for $n=100$ and $p=5$ using weighted CEM (in green) and the CEM (in red). The contamination rate $\epsilon$ is given on the horizontal axis. Increasing contamination size $k_\epsilon$ from left to right, increasing $\sigma$ from top to bottom.} \label{fig:one} \end{figure} \begin{figure} \begin{center} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-5-100-1-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-5-100-1-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-5-100-1-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-5-100-2-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-5-100-2-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-5-100-2-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-5-100-3-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-5-100-3-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-5-100-3-3} \\ \end{center} \caption{Distribution of the divergence measure for $n=100$ and $p=5$ using the weighted CEM (in green) and the CEM (in red). The contamination rate $\epsilon$ is given on the horizontal axis. Increasing contamination size $k_\epsilon$ from left to right, increasing $\sigma$ from top to bottom.} \label{fig:two} \end{figure} \section{Real data example: Protein data} \label{sec:examples} The data under consideration \citep{Najibi2017} contain bivariate information about $63$ protein domains that were randomly selected from three remote Protein classes in the Structural Classification of Proteins (SCOP). In the following, we consider the data set corresponding to the 39-th protein domain. A bivariate Wrapped Normal has been fitted to the data at hand by using the weighted CEM algorithm, based on a Generalized Kullback-Leibler RAF with $\tau=0.25$ and $J=6$. The tasks of bandwidth selection and initialization have been resolved according to the same strategy described above in Section~\ref{sec:simulations}. The inspection of the data suggests the presence of at least a couple of clusters that make the data non homogeneous. Figure \ref{fig:three} displays the data on a flat torus together with fitted means and $95\%$ confidence regions corresponding to three different roots of the WLEE (that are illustrated by different colors): one root gives location estimate $\vect{\mu}_1=(1.85, 2.34)$ and a positive correlation $\rho_1=0.79$; the second root gives location estimate $\vect{\mu}_2=(1.85, 5.86)$ and a negative correlation $\rho_2=-0.80$; the third root gives location estimate $\vect{\mu}_3=(1.61, 0.88)$ and correlation $\rho_3=-0.46$. The first and second roots are very close to maximum likelihood estimates obtained in different directions when unwrapping the data: this is evident from the shift in the second coordinate of the mean vector and the change in the sign of the correlation. In both cases the data exhibit weights larger than 0.5, except in few cases, corresponding to the most extreme observations, as displayed in the first two panels of Figure \ref{fig:four}. In none of the two cases the bulk of the data corresponds to an homogeneous sub-group. On the contrary, the third root is able to detect an homogeneous substructure in the sample, corresponding to the most dense region in the data configuration. Almost half of the data points is attached a weight close to zero, as shown in the third panel of Figure \ref{fig:four}. This findings still confirm the ability of the weighted likelihood methodology to tackle such uneven patterns as a diagnostic of hidden substructures in the data. In order to select one of the three roots we have found, we consider the strategy discussed in \cite{agostinelli2006}, that is, we select the root leading to the lowest fitted probability \begin{equation*} \mathrm{Prob}_{\hat\Omega}\left(\delta_n(\vect{y}; \hat{\Omega}, \hat F_n)<-0.95\right) \ . \end{equation*} This probability has been obtained by drawing 5000 samples from the fitted bivariate Wrapped Normal distribution for each of the three roots. The criterion correctly leads to choose the third root, for which an almost null probability is obtained, wheres the fitted probabilities for the first and second root are 0.204 and 0.280, respectively. \begin{figure}[!ht] \begin{center} \includegraphics[width=0.9\textwidth,height=0.5\textheight]{ellipse} \end{center} \caption{Protein data. Fitted means ($+$) and $95\%$ confidence regions corresponding to three different roots from weighted CEM ($J=6$).} \label{fig:three} \end{figure} \begin{figure}[!ht] \begin{center} \includegraphics[width=0.9\textwidth, height=0.5\textheight]{weightsL6} \end{center} \caption{Protein data. Weights corresponding to three different roots from weighted CEM.} \label{fig:four} \end{figure} \section{Conclusions} \label{sec:conclusions} In this paper an effective strategy for robust estimation of a multivariate Wrapped normal on a $p-$dimensional torus has been presented. The method inherits the good computational properties of a CEM algorithm developed in \cite{nodehi2018estimation} jointly with the robustness properties stemming from the employ of Pearson residuals and the weighted likelihood methodology. In this respect, it is particularly appealing the opportunity to work with a family of distribution that is close under convolution and allows to parallel the procedure one would have developed on the real line by using the multivariate normal distribution. The proposed weighted CEM works satisfactory at least in small to moderate dimensions, both on synthetic and real data. It is worth to stress that the method can be easily extended to other multivariate wrapped models. \section*{Additional Numerical results} \label{sm:sec:numericalstudy} Figure \ref{fig:sm:1}, Figure \ref{fig:sm:3} and Figure \ref{fig:sm:5} show the angle separation whereas Figure \ref{fig:sm:2}, Figure \ref{fig:sm:4} and Figure \ref{fig:sm:6} display the measure of accuracy in estimating the variance-covariance components for $p=2$ and $n = 50, 100, 500$, respectively. \begin{figure} \begin{center} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-50-1-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-50-1-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-50-1-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-50-2-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-50-2-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-50-2-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-50-3-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-50-3-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-50-3-3} \\ \end{center} \caption{Distribution of angle separation for $n=50$ and $p=2$ using weighted CEM (in green) and the CEM (in red). The contamination rate $\epsilon$ is given on the horizontal axis. Increasing contamination size $k_\epsilon$ from left to right, increasing $\sigma$ from top to bottom.} \label{fig:sm:1} \end{figure} \begin{figure} \begin{center} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-50-1-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-50-1-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-50-1-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-50-2-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-50-2-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-50-2-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-50-3-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-50-3-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-50-3-3} \\ \end{center} \caption{Distribution of the divergence measure for $n=50$ and $p=2$ using the weighted CEM (in green) and the CEM (in red). The contamination rate $\epsilon$ is given on the horizontal axis. Increasing contamination size $k_\epsilon$ from left to right, increasing $\sigma$ from top to bottom.} \label{fig:sm:2} \end{figure} \begin{figure} \begin{center} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-100-1-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-100-1-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-100-1-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-100-2-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-100-2-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-100-2-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-100-3-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-100-3-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-100-3-3} \\ \end{center} \caption{Distribution of angle separation for $n=100$ and $p=2$ using weighted CEM (in green) and the CEM (in red). The contamination rate $\epsilon$ is given on the horizontal axis. Increasing contamination size $k_\epsilon$ from left to right, increasing $\sigma$ from top to bottom.} \label{fig:sm:3} \end{figure} \begin{figure} \begin{center} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-100-1-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-100-1-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-100-1-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-100-2-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-100-2-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-100-2-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-100-3-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-100-3-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-100-3-3} \\ \end{center} \caption{Distribution of the divergence measure for $n=100$ and $p=2$ using the weighted CEM (in green) and the CEM (in red). The contamination rate $\epsilon$ is given on the horizontal axis. Increasing contamination size $k_\epsilon$ from left to right, increasing $\sigma$ from top to bottom.} \label{fig:sm:4} \end{figure} \begin{figure} \begin{center} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-500-1-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-500-1-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-500-1-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-500-2-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-500-2-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-500-2-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-500-3-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-500-3-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-2-500-3-3} \\ \end{center} \caption{Distribution of angle separation for $n=500$ and $p=2$ using weighted CEM (in green) and the CEM (in red). The contamination rate $\epsilon$ is given on the horizontal axis. Increasing contamination size $k_\epsilon$ from left to right, increasing $\sigma$ from top to bottom.} \label{fig:sm:5} \end{figure} \begin{figure} \begin{center} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-500-1-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-500-1-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-500-1-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-500-2-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-500-2-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-500-2-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-500-3-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-500-3-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-2-500-3-3} \\ \end{center} \caption{Distribution of the divergence measure for $n=500$ and $p=2$ using the weighted CEM (in green) and the CEM (in red). The contamination rate $\epsilon$ is given on the horizontal axis. Increasing contamination size $k_\epsilon$ from left to right, increasing $\sigma$ from top to bottom.} \label{fig:sm:6} \end{figure} Figure \ref{fig:sm:7} show the angle separation whereas Figure \ref{fig:sm:8} display the measure of accuracy in estimating the variance-covariance components for $p=5$ and $n = 500$, respectively. \begin{figure} \begin{center} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-5-500-1-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-5-500-1-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-5-500-1-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-5-500-2-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-5-500-2-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-5-500-2-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-5-500-3-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-5-500-3-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{cosmu-5-500-3-3} \\ \end{center} \caption{Distribution of angle separation for $n=500$ and $p=5$ using weighted CEM (in green) and the CEM (in red). The contamination rate $\epsilon$ is given on the horizontal axis. Increasing contamination size $k_\epsilon$ from left to right, increasing $\sigma$ from top to bottom.} \label{fig:sm:7} \end{figure} \begin{figure} \begin{center} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-5-500-1-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-5-500-1-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-5-500-1-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-5-500-2-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-5-500-2-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-5-500-2-3} \\ \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-5-500-3-1} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-5-500-3-2} \includegraphics[height=0.3\textheight, width=0.3\textwidth]{div1-5-500-3-3} \\ \end{center} \caption{Distribution of the divergence measure for $n=500$ and $p=5$ using the weighted CEM (in green) and the CEM (in red). The contamination rate $\epsilon$ is given on the horizontal axis. Increasing contamination size $k_\epsilon$ from left to right, increasing $\sigma$ from top to bottom.} \label{fig:sm:8} \end{figure}
{'timestamp': '2020-10-19T02:19:35', 'yymm': '2010', 'arxiv_id': '2010.08444', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08444'}
arxiv
\section{Introduction} The growing importance of effective security monitoring solutions calls for appropriate measures of their effectiveness. The operation of Security Operation Centers (SOCs) is the recommended best practice to which large and medium-size enterprises rely for the detection, notification, and ultimately response to cybersecurity incidents~\cite{kokulu2019matched,muniz2015security}. Yet, the average time for detecting an attack ranges between several weeks to years~\cite{verizon2018}. In a recent study, Kokulu et al.~\cite{kokulu2019matched} interviewed security analysts and mangers, who explicitly identify the issue of \textit{measuring} SOC performance as one of the main obstacles towards effective detection and response operations. The problem of measuring security (performance) is a long-standing and difficult one~\cite{herley2017sok}. Measuring the performance of \SOC{}s is no exception. Whereas numerous performance metrics exist (e.g., number of detected incidents, time to detection, time to response, etc.)~\cite{shah2018understanding}, it is still unclear how to obtain reliable and reproducible measures over those metrics. As incoming attacks are, by definition, unknown, a ground truth on which to base the measurements cannot be easily defined; on the other hand, performing measurements in \textit{in-vitro} settings limits the representativeness of those measurements in real-world settings~\cite{shah2018methodology,kokulu2019matched}. However, the problem of measuring the performance of infrastructures and systems dedicated to the detection of \textit{rare} events of unknown magnitude is not new. For example, the \textit{LIGO} (\textit{Laser Interferometer Gravitational-Wave Observatory}) infrastructure has been built with the goal of detecting perturbations in the spacetime continuum caused by `rippling effects' of large-scale events, such as the collapse of a binary blackhole system. Despite the completely different settings and event generation processes, the challenges faced by the LIGO interferometer and SOCs are quite similar: both must detect unknown, unpredictable, and arbitrarily `small' manifestations of an event, and both must know whether the detection procedure is accurate while operating in the absence of a ground-truth on the events that ought be detected. This paper presents \texttt{SAIBERSOC}, a practical and deployable solution for SOC performance evaluation based on the same working principle as the LIGO infrastructure~\cite{PhysRevD.81.102001}: to generate and automatically inject `events' (in our case, cyber-attacks) into the detection infrastructure at random instants in time, with the purpose of evaluating, in a controlled fashion, the performance of the detection system. The \SAIBERSOC{} methodology and tool can be employed by researchers and security operatives alike to evaluate the impact of various factors on SOC performance, such as analyst training, experience , and skill composition, or the relative change in effectiveness of the deployed analysis and visualization tools as the SOC configuration and processes change. \SAIBERSOC{} automatically generates the injected attacks relying on the MITRE ATT\&CK Framework\cite{mitre_attck} and is structured over four components providing automated methods for attack definition, generation, injection, and analysis. The \SAIBERSOC{} tool is publicly available as free and open source software (see subsection~\ref{subsec:saibersoc-tool}). To evaluate the effectiveness of the method at the core of \SAIBERSOC{}, we design and run an experiment employing $n=124$ students enrolled in a security course of a medium-sized technical university in Europe. The experiment relies on a real SOC infrastructure (normally monitoring network events at the M\&CS department of the university) where students operate as SOC analysts. In particular, we measure detection accuracy in terms of both attack \textit{identification} and \textit{investigation}, injecting two attacks based on the \MIRAI{}~\cite{mirai-botnet} and \EXIM{}~\cite{exim-cve} scenarios over two SOC configurations (\BADSOC{} and \GOODSOC{}). Our evaluation shows that the \SAIBERSOC{} methodology correctly identifies and can quantify the relative change in detection accuracy across SOC configurations and, importantly, does not \enquote{overshoot} or reveal differences where there should be none. \smallskip This paper develops as follows: \hyperref[sec:background]{Section~\ref{sec:background}} provides a background on SOC operations and discusses relevant literature. \hyperref[sec:method]{Section~\ref{sec:method}} describes the proposed methodology and section~\ref{sec:validationmethodology} the experimental validation strategy. Experimental results follow in section~\ref{sec:experimentresults}. \hyperref[sec:discussion]{Section~\ref{sec:discussion}} discusses our results and presents the \SAIBERSOC{} software implementation in detail. Finally, section~\ref{sec:conclusion} concludes the paper. \section{Background and Related Work} \label{sec:background} \subsection{Attack frameworks} Defensive operations against increasingly sophisticated attacks require a deep understanding of how adversaries conduct offensive operations, how threats unfold and how security breaches escalate into major incidents. The MITRE PRE-ATT\&CK\cite{mitre_pre-attck}, MITRE ATT\&CK \cite{mitre_attck}, and Cyber Kill Chain\cite{lockheed_martin} frameworks aim at building a knowledge base of adversary TTPs (Tactics, Techniques, and Procedures) from real-world observations, grouping them in a taxonomy of attack stages to describe the anatomy of any attack. The extensive and detailed enumeration of the attack techniques provided by the frameworks and stages can be, roughly, grouped in four phases: \textit{Reconnaissance}, \textit{Exploitation}, \textit{Delivery} and \textit{Control} (Table~\ref{tab:phases}). \textit{Reconnaissance} groups data gathering operations performed by the adversary, ranging from subject information for the development of social engineering attacks, to probing the network surface of the infrastructure to derive paths of compromise. During \textit{Exploitation}, the attacker evaluates the measured attack surface (vulnerabilities, misconfigured software, phishing opportunities) and creates or acquires the attacks (vulnerability exploits, phishing artefacts, malware, ...) to perform information leak, lateral movement (e.g., inside the organization), command execution, and/or privilege escalation. \textit{Delivery} covers the vectors adopted from the adversary to drop malicious software that will act as a foothold for further actions. This includes spear phishing and supply chain compromise. \textit{Control} includes the techniques adopted by the adversary to control the system and reliably execute commands on it, compromising system integrity, confidentiality and availability. This can be achieved via remote management interfaces, custom software and web services. \begin{table}[t] \centering \caption{Attack phases} \label{tab:phases} \Description{Overview of the four phases `Reconnaissance', `Exploitation', `Delivery', and `Control'} \begin{tabular}{p{0.22\columnwidth} p{0.7\columnwidth}} \toprule \textbf{Phase} & \textbf{Description} \\\midrule Reconnaissance & Techniques to research, identify and select targets using active or passive reconnaissance. \\ Exploitation & Techniques employed by attackers to gain initial control over (vulnerable) target systems. \\ Delivery & Techniques resulting in the transmission of the weaponized object to the targeted environment. \\ Control & Techniques used by attackers to communicate with controlled systems in a target network. \\\bottomrule \end{tabular} \end{table} \subsection{Security monitoring operations} Tools and procedure to support security analysts in incident response and network monitoring (such as Network Intrusion Detection Systems (NIDS) and Security Information and Event Management (SIEM)) are at the core of modern security monitoring in operational settings. \textit{Security Operation Centers} (SOCs) are the center of monitoring operations in medium or large organizations, either internally or outsourced to service providers~\cite{muniz2015security,kokulu2019matched}. SOCs are organized hierarchically in (generally three) tiers~\cite{muniz2015security}, where analysts with different skills and expertise monitor the network activity and take action against a threat. Tier~1 is the first frontier where alerts are investigated by analysts, identifying possible threats among the non-significant ones and prioritizing them. Identified threats are escalated to Tier~2, where more qualified analysts with forensics and incident response skills correlate the information with threat intelligence to identify threat actors. Tier~2 is in charge to determine a strategy for containment, remediation and recovery. If the threat targets business critical operations, Tier~3 analysts identify and develop tailored responses to the identified threats and attack patterns. In general, incident investigation can be split in two phases~\cite{muniz2015security}: \textit{Attack identification}, where Tier 1 analysts evaluate incoming alerts to identify possible attacks; \textit{Attack investigation}, where Tier~1 and Tier~2 analysts investigate the identified attack over its phases (ref. Table~\ref{tab:phases}) to, for example, identify victims, attack timing, payloads, and propagation. Once these two phases are complete, the attack is reported and responded to, depending on the service level agreement at which the SOC operates. The large amount of alerts and potential security events detected in a SOCs make it impossible, operationally to `investigate everything'~\cite{shah2018understanding}: the more relevant are the alerts generated by a SOC (e.g., through accurate use-cases), the fewer `false positives' a (Tier~1) analyst will have to investigate before passing the baton on to higher tiers (i.e., Tier~2~and~3). However, \textit{measuring} how SOC operations respond to changes in the SOC configuration (e.g., a refined use-case, a different alert investigation process, new rulesets, etc.) remains an open and critical challenge~\cite{kokulu2019matched}, in terms of analyst competences as well as for metric definition and measurement \cite{shah2018understanding,shah2018methodology,zimmerman2014ten,ganesan2017optimal}. \subsection{SOC performance evaluation} Albeit attempts have been made in trying to tackle these problems, the scientific literature proposing methods to measure SOC performance is still limited. Effectiveness of a SOC depends on both the qualities of the tools adopted, their configurations and capabilities, and on skills of the personnel. For what concerns the correlation between human capabilities and a SOC's performance, a few studies have been made\cite{sundaramurthy2016turning, sundaramurthy2014tale}. In \cite{sundaramurthy2014tale}, Sundaramurthy et al., they trained three students to work as SOC analysts and embedded them in three different SOCs. While working as operational components, they were required to produce reports on their observations and meet with an anthropologist involved in the research. By comparing reports and interviews, is was possible to draw conclusions on the aspects that may be more promising to the effectiveness of a SOC and which not, in terms of its architecture, experience of analysts, nature and degree of their interactions, workflow for incident reports and the quality of work itself for the employee. Kokulu et al.~\cite{kokulu2019matched} investigate through interviews to both SOC analysts and SOC managers about technical and non-technical issues of a SOC; from their interviews emerge how often SOCs fail to provide substantial support against specific types of attacks, overloading analysts with low-quality threat intelligence, long reports and logs, and more. Albeit evidences are supported by interviews, the authors point out that metrics to measure security quantitatively and qualitatively are rudimentary \cite{kokulu2019matched}. Jacobs et al.~\cite{jacobs_towards_2014} propose a method to systematically and quantitatively evaluate \SOC{}'s maturity by identifying a set of capabilities that a \SOC{} embodies, i.e. log analysis, event correlation, incident management, threat identification and reporting, scoring each of them \cite{jacobs_classification_2013} \cite{jacobs_towards_2014}. The SOC aspects analyzed derive from a number of industrial security management and control frameworks, including ISO 27000 series \cite{iso_2019} and SANS Critical Controls and each of them is scored with respect to their maturity; however, the score attribution is left as an expert-driven task, rather than a data-driven measurement. A simulation-optimization approach is proposed by Shah et al. \cite{shah2018methodology}, where they identified some of the causes that negatively affect the throughput of a SOC in terms of efficiency. They propose the \textit{Time to Analyze Alert} (TTA) metric to evaluate the efficiency of a SOC by measuring the time that goes from the alert generation to its analysis. By monitoring SOC's TTA, Shah et al. are able to generate advice for the SOC Manager, suggesting live corrective actions towards a desired benchmark. In subsequent work Shah et al.\cite{shah2018understanding} also model the problem as a simulation-optimization problem and evaluated it from data derived from a simulated SOC, to obtain a set of metrics that allow the optimization of some of a SOC capabilities; however, a procedure to test the resulting SOC performance in real-world scenarios remains to be identified and tested. \smallskip \textbf{Research gap.} Whereas current research has focused mostly on the identification of metrics~\cite{shah2018understanding} and procedures~\cite{jacobs_towards_2014,shah2018methodology,shah2018understanding} to evaluate SOC performance, an empirical method capable of capturing the complexity of a SOC operation (including alert configuration, analyst capabilities, etc.) has yet to be proposed and validated~\cite{kokulu2019matched}. \section{The \SAIBERSOC{} solution} \label{sec:method} To address this gap, we propose \SAIBERSOC{}, a method and solution to perform systematic SOC performance evaluations through automated attack injection. Our solution is composed of four Architectural Components (\texttt{AC-\{1..4\}}) constituting of a library of (attack) traces (\arch{1}), and components to generate (\arch{2)}, inject (\arch{3}), and report (\arch{4}) the synthetic attacks. \begin{figure}[t] \centering \includegraphics[width=0.73\columnwidth]{img/flow_diagram.pdf} \begin{minipage}{0.9\columnwidth} \footnotesize \smallskip The platform uses (network) traces characterizing the \enquote{building blocks} of an attack (\arch{1}), and (re-)combines them to generate new attacks (\arch{2}). The generated attacks are then injected into the network (\arch{3}). The SOC analysts perform and report on the investigation results, which can be checked (\arch{4}) against the known ground-truth (derived from the attacks generated in \arch{2}). \end{minipage} \caption{Schematic depiction of the \SAIBERSOC{} solution} \label{fig:schema} \Description[Schematic overview of how the four components interact in relation to the Security Operations Center.]{Component `AC-1 Attack Traces' is a library of network traffic captures maintained by experts. In component `AC-2 Attack Generation' the network traces get merged. Experts monitor and supervise rules for merging network traces to ensure that the output is a realistic attack. The output of this component is the assembled attack ready to be replayed on the network, as well as a ground-truth that describes the assembled attack. In phase `AC-3 Attack Injection' the assembled attack is injected somewhere into a network monitored by the Security Operations Center. The Security Operations Center, unable to distinguish injected attack simulation traffic from regular network traffic, will investigate and report on the injected attack. In component `AC-4 Reporting' the report generated by an analyst in the Security Operations Center is compared to the automatically generated ground truth from `AC-2 Attack Generation'.} \end{figure} \SAIBERSOC{} can be used to inject attacks into a \SOC{} during operation, or alternatively in a \enquote{virtual} \SOC{} testing environment where all network traffic is replaced by pre-recorded background traffic. Once the attack has been detected, the \SOC{} analysts perform the investigation following their normal procedure. The type of injected attack as well as its timing, targets and sources, and velocity are unknown to the \SOC{} analysts. Finally, the analyst's attack report is automatically evaluated against the ground truth obtained from the attack assembly phase. A more detailed description of the \SAIBERSOC{} architecture can be found in subsection~\ref{subsec:architecture}, we present our software implementation in subsection~\ref{subsec:saibersoc-tool}. \subsection{Solution requirements} To guide the development of the proposed solution, we pose a list of requirements that a real-world \SOC{} performance evaluation framework should fulfill. A summary of the identified requirements is provided in Table~\ref{tab:requirements}. \begin{table*}[t] \centering \caption{Architectural requirements. Table~7 in the Appendix details the mapping to the architectural components.} \label{tab:requirements} \Description[Mapping between requirements `R' and architectural components `AC' that must meet the respective requirement.]{Architectural components `AC-1', `AC-2', and `AC-4' must fulfill requirement `R-1 Independence' (the proposed solution should be independent of the specific SOC implementation and monitored environment). Architectural components `AC-1' and `AC-2' must fulfill requirement `R-2 Versatility' (the framework must work with all types of attack scenarios in scope of the SOC, regardless of their complexity). Architectural components `AC-2' and `AC-3' must fulfill requirement `R-3 Realism' (the attack injection must be seamlessly integrated to the operative environment of the analyst. This includes IP addresses, local software configurations, and network setups). Architectural components `AC-2' and `AC-4' must fulfill requirement `R-4 Tracability' (the framework must be able to link all SOC reactions i.e., a report to the initial stimulus or attack that caused it.).} \begin{tabular}{l l p{0.56\textwidth} c c c c} \toprule \require{ID} & \textbf{Requirement} & \textbf{Description} & \arch{1} & \arch{2} &\arch{3} &\arch{4} \\ \midrule \require{1} & Independence & The proposed solution should be independent of the specific SOC implementation and monitored environment. & \checkmark & \checkmark & & \checkmark \\ \require{2} & Versatility & The framework must work with all types of attack scenarios in scope of the \SOC{}, regardless of their complexity. & \checkmark & \checkmark & & \\ \require{3} & Realism & The attack injection must be seamlessly integrated to the operative environment of the analyst. This includes IP addresses, local software configurations, and network setups. & & \checkmark & \checkmark & \\ \require{4} & Traceability & The framework must be able to link all \SOC{} reactions (i.e., a report) to the initial stimulus or attack that caused it. & & \checkmark & & \checkmark \\ \bottomrule \end{tabular} \end{table*} \noindent\textbf{Independence (\require{1})} To measure and compare \SOC{} performance, the framework must apply to all \SOC{}s, regardless of how they are implemented. Further, the results must be reproducible, regardless of who uses the framework. Those are fundamental requirements for any measure or assessment~\cite{pfleeger2010measuring}. Therefore, a solution must be able to work with various \SOC{} configurations and implementations. \noindent\textbf{Versatility (\require{2})} To be able to create meaningful measures covering the whole scope of the \SOC{}, all aspects of a potential attack must be covered. Thus, a metric should cover the complete value-space to assure meaningful results reflecting real-world performance~\cite{kokulu2019matched}. Because attackers continuously adapt their behavior, a solution must be capable to simulate past, current, as well as future attacks in realistic ways to be able to measure real-world security. \noindent\textbf{Realism (\require{3})} Real-world security is influenced by numerous factors, sometimes in unpredictable ways. For example, wrong presumptions about context or human behavior in unforeseen situations leads to alleged security measures and therefore a false sense of security\cite{chiasson_quantifying_2015,adams2005bridging}. This can be avoided by assessing real-world performance, i.e., a setup that is as close as possible) to reality. In case of a \SOC{} this means measuring a real \SOC{} (including software and configuration), realistic work environments, and realistic attacks. It is therefore imperative that the evaluation is performed under real or realistic operational conditions (e.g., the analysts do not know the attacks in advance, and the injected attacks are realistic). \noindent\textbf{Traceability (\require{4})} The framework must be able to link \SOC{} reactions i.e., reports, to the attacks that caused those reactions in the \SOC{}. Only if both input and output are known, a meaningful evaluation of the \SOC{} performance can be made by comparing the \textit{expected} output to the realized output. \subsection{The \SAIBERSOC{} solution architecture} \label{subsec:architecture} Figure~\ref{fig:schema} provides a schematic depiction of the architecture behind the proposed \SAIBERSOC{} solution. Table~\ref{tab:requirements} reports the mapping of the architectural components to the identified requirements. A running example of implementation of the proposed workflow is reported in Table~\ref{tab:example} in the appendix and discussed below. \subsubsection{Attack Traces (\arch{1})} \label{subsubsec:attack-module-database} All attack simulations or scenarios deployed in \SAIBERSOC{} are constructed by combining multiple pre-defined attack traces. An attack trace consists of a set of network packets (e.g., stored in a \textit{pcap} file) that reproduces the network traffic generated by an attack during a specific attack phase. These traces can be extended to non-network events (e.g., \textit{syslog} activity to reproduce events at the host level). To structure traces in attack phases, we rely on the ATT\&CK Framework\cite{mitre_attck} to create and store a library of different attack traces reflecting different phases of ongoing attacks (see Table~\ref{tab:phases}). The MITRE CALDERA\cite{caldera} and Atomic Red Team\cite{atomic} already maintain some form of an attack-database with attacker actions mapped to the ATT\&CK Framework\cite{mitre_attck}. \paragraph{Impl. example:} with reference to the example reported in Table~\ref{tab:example}, \arch{1} generates a set of traces characterizing events in each phase of the ATT\&CK framework; for example, \textit{portscan(src\_ip, dst\_ip)} will reproduce network traffic (to be parameterized with \textit{src\_ip, dst\_ip} associated to the \textit{Reconnaissance} phase of the MITRE ATT\&CK framework (ref. Table~\ref{tab:phases}). Similarly, \textit{expl\_cve()} will reproduce traces corresponding to the exploitation of a known vulnerability (e.g., as derived from an exploit on ExploitDB~\cite{exploitdb}. \subsubsection{Attack Generation (\arch{2})} \label{subsubsec:scenario-builder} Multiple attack traces are combined to generate fully-fledged attack simulations. Attacks are composed following the ATT\&CK framework\cite{mitre_attck} (i.e., reconnaissance happens before exploit delivery, which happens before command and control communication, which happens before data exfiltration). The CALDERA framework is already capable of automatically generating meaningful attacks from attack traces\cite{caldera}. In this step, the generic attack traces are matched to the specific environment monitored by the SOC (e.g., IP ranges, exploits vs vulnerable systems, etc.). This process can be automated by relying on asset information available to any SOC during normal operation. The result of this phase is a \textit{ready-to-inject} attack simulation. The \enquote{ground-truth} of the simulation (e.g., attacker's IP addresses(es)) can be extracted from the parameterized attack traces composing the attack. Once re-parameterized (i.e., victim IP addresses matching the range of a monitored network and system functionality), attack scenarios can be reused the \SOC{} or organization's network. \paragraph{Impl. example:} with reference to Table~\ref{tab:example}, a sequence of (attack) traces is selected and parameterized. In this example, the IP of the attacker and the receiving victim system(s) are identified (\textit{src\_ip,dst\_ip}), as well as the exploited vulnerability (\textit{cve}), and protocols used for the command and control (\textit{proto}). The parametrized attack traces are then composed following the MITRE ATT\&CK framework phases; the parameters of the attack are used to generate the ground truth against which the analysts' reports will be checked in \arch{4}. \subsubsection{Attack Injection (\arch{3})} \label{subsubsec:attack-scenario-injector} Attack simulations retrieved from \arch{2} are injected in the network traffic monitored by the \SOC{}. This can be either executed on the live infrastructure, or on a virtual \enquote{shadow network} separate from the operative environment. In the latter setting, the entire (virtual) network traffic is recorded and later forwarded to the Network Intrusion Detection sensors employed by the \SOC{}. The attack simulation can be merged seamlessly into (real-world) traffic streams either on a \SOC{} sensor or on network infrastructure devices (i.e., network switches or routers). To make simulations as realistic as possible, (optional) background traffic that was previously recorded on site can be mixed with the attack simulation. Attack simulations can be injected, recorded, and replayed at any point in time (i.e., record network traffic from virtual environment instead of passing to the \SOC{} immediately). The \SOC{} will then raise the respective events and alerts as if the injected traffic was real traffic to (or from) the monitored infrastructure. \paragraph{Impl. example:} In the example in Table~\ref{tab:example} traffic is recorded and replayed into a \SOC{} sensor as scheduled by executing the parametrized traces (e.g., \textit{exploit\_cve(cve,src\_ip,dst\_ip)}) (i.e., 12pm). The attack injection raises corresponding \SOC{} alerts, then evaluated by the analyst during incident identification and investigation. \subsubsection{Reporting (\arch{4})} \label{subsubsec:report-evaluator} The attack reports produced by \SOC{} analysts in response to the attack simulation are matched against the ground truth (obtained from \arch{2}) in \arch{4}. Because the exact details of the simulated attacks are known in advance, report(s) that mention specific details unique to the injected attack can be identified automatically. Using simple string matching and the knowledge-base of the SIEM, it is possible to check whether the final \SOC{} report details the incident events and sources correctly. \paragraph{Impl. example:} A \SOC{} analyst investigated the generated SOC alerts and reported the incident through a standardized template (e.g., \textit{src\_ip, cve}, \ldots). Comparing the analyst report with the ground truth may indicate that the current \SOC{} configuration lacks detection capabilities (e.g., undetected exploitation), or that raised alerts systematically misdirect the analyst (e.g., due to poorly defined threats or use cases). \section{Experimental validation} \label{sec:validationmethodology} Before presenting the \SAIBERSOC{} tool implementing the described architecture and solution, we validate the methodology behind it by testing it experimentally. To do so, we devise an experiment involving $n=124$ MSc students attending the 'Security in Organizations' course of a medium-sized European Technical University and an operative SOC infrastructure deployed at the Department level. \smallskip \textbf{Goal of the experiment}: \textit{to evaluate whether the proposed solution is capable of detecting (small) differences in SOC performance.} \smallskip Experimental subjects worked in groups of two and took the role of \textit{Tier 1} security analysts to investigate (injected) attacks. Subjects were randomly assigned to the experimental treatment (consisting in a small tweak in the SOC configuration) and asked to report the results of their analysis by filling in a report template. \subsection{Experimental infrastructure} The experiment is based on a real SOC used for research and education operating at the Mathematics and Computer Science department of the university. The SOC is operated over open-source technology and based on Security Onion\cite{onion} and Elastic Stack\cite{elastic} for event correlation and analysis. During regular operation the SOC monitors real incoming and outgoing network traffic in the department. The chosen network sensors (NIDS) are Suricata\cite{suricata} for security monitoring, and Bro/Zeek\cite{zeek} for network flow logs. The SOC is currently limited to the monitoring of network traffic and is operated with the involvement and cooperation of the security team of the university. \subsection{Experimental subjects} Subjects were recruited from a security in organization MSc course held at the university operating the SOC. The course is mandatory for all students graduating in the security track of the MSc program in Computer Science and open to students from others tracks (security=14; computer science=56; other=64; tot=124). Students were asked to form groups of two to participate in the experiment and were randomly assigned to the respective treatment groups (next subsection). The final size of the experiment pool is n=63; the term `experiment subject' in the remainder of the paper will refer to the student groups and not to the single students. \subsection{Experimental variables} \label{subsec:experimental-variables} \paragraph{Independent variable} To reproduce realistic SOC configurations we setup two analysis environments, namely \GOODSOC{} and \BADSOC{}. To test the effectiveness of the proposed solution, we introduce only a small change between the two configurations. To maintain the change realistic, we (1) define it around the university environment in which the SOC operates, and (2) base it only on the (de-)activation of a set of predefined rules that \textit{do not} match the use-cases of the university. \footnote{This setup has been checked against a set of use-cases provided by the university for SOC operation.} Namely, as the university is an open environment, default rulesets triggering alerts related to violation of generic policies such as use of TOR or p2p are out of the scope of the SOC. We therefore define the following two experimental conditions: \smallskip \noindent\textbf{\BADSOC{}}: baseline SOC configuration consisting of the default set of rules defined by the detection software (Suricata);\hfill\break \textbf{\GOODSOC{}}: baseline SOC configuration \textit{minus} alerts related to policy violation events. \smallskip \noindent In the \BADSOC{} configuration 19731 out of 27125 present Suricata~\cite{suricata} rules were active by default. By deactivating 2753 rules (14\%), 16978 active rules remain). The disabled rules\footnote{All rules prefixed with either \enquote{ET POLICY}, \enquote{ET INFO}, \enquote{ET CHAT}, \enquote{GPL CHAT}, \enquote{ET TOR}, or \enquote{SURICATA} were disabled (see \enquote{\href{https://gitlab.tue.nl/saibersoc/acsac2020-artifacts/-/blob/master/experiment/scripts/better-soc.sh}{\texttt{better-soc.sh}}} in the \href{https://gitlab.tue.nl/saibersoc/acsac2020-artifacts/}{artifact repository}).} inform about policy violations (including the use of chat/instant messaging software and usage of the TOR network\cite{tor}). \paragraph{Outcome variables} In output of the experiment we evaluate the accuracy of the assessments made by the experiment subjects. We collect analyst output through a survey compiled by all subjects at the end of the experiment. To evaluate the subject's output under different experimental conditions, we consider the following variables: (1) the total number of reports submitted by each group: these may be related to the real injected attacks, or to other suspicious events detected by the subjects; (2) the number of submitted reports dealing with one of the simulated attacks; (3) the correctness of the submitted reports when compared against the ground truth. \subsection{Expected outcome and evaluation criteria} If the proposed solution is effective in detecting changes in SOC performance triggered by (small) changes in the SOC configuration, we would expect that \GOODSOC{} (i.e., the configuration producing fewer alerts not related to the university's use cases), lead to more accurate reports when compared to \BADSOC{}. Reflecting normal SOC operation procedures~\cite{muniz2015security}, we split our evaluation over the analysis phases of \textit{Attack identification} and \textit{Attack investigation}. \smallskip \textbf{Outcome expectation.} As the modification between \BADSOC{} and \GOODSOC{} should only reduce the number of false alerts displayed to the analyst, leaving alerts relevant to an attack unaffected, we expect the \SAIBERSOC{} method to highlight that: \medskip \noindent (1) \GOODSOC{} outperforms \BADSOC{} for the \textit{attack identification} phase; \smallskip \noindent (2) no significant difference between \GOODSOC{} and \BADSOC{} emerges for the \textit{attack investigation} phase. \smallskip To evaluate the accuracy of the \textit{Attack identification}, we evaluate the number of correct entries reported by the subjects in relation to: IP(s) of the attacker, IP(s) of the victims. To evaluate the accuracy of \textit{Attack investigation}, we evaluate reported information on the reconnaissance, exploitation, and delivery and control activities (ref. Table~\ref{tab:phases}). As we are interested in testing the effectiveness of the proposed solution, we are not concerned with quantifying whether our \GOODSOC\ configuration is \textit{significantly better than} our \BADSOC\ configuration; differently, we are interested in evaluating whether the (albeit small) \textit{change in the \GOODSOC\ configuration can be spotted by the proposed experimental procedure} in terms of a difference in performance. To evaluate these differences, we employ a mix of non-parametric statistical tests including Fisher's Exact Test (for differences in counts across conditions), and Wilcoxon rank-sum tests (for differences in outcome distributions). The significance level is set at $\alpha=0.05$. \subsection{Experiment Preparation} This section details the experiment setup and preparation for the scenario injection, and the attack reporting. \smallskip \emph{Attack traces.} We use the previously identified attack phases in Table~\ref{tab:phases} for our proof-of-concept implementation, namely \textit{Reconnaissance}, \textit{Exploitation}, and \textit{Delivery} and \textit{Control} phases. For each of these phases we collect or reconstruct the respective network traces from public resources. For the \textit{Reconnaissance} phase we collect data using \texttt{nmap}\cite{nmap} scans against selected targets; in the \textit{Exploitation} phase we rely on PoC exploits and brute-force attacks available on public resources, such as ExploitDB\cite{exploitdb} and Metasploit\cite{metasploit}. \textit{Delivery} and \textit{Control} include the download of malicious software from both ExploitDB and suspect IP addresses, and communication with IPs known to be involved in botnet C2C infrastructures. \smallskip \emph{Attack generation.} Using the previously identified attack traces, we build two different attack scenarios; these attacks are built by assembling the previous network captures created and provided with consistency among individual actions by editing the IP addresses involved. Resulting attacks reproduce the \textit{modus operandi} implemented by two real-world attacks (namely, \textit{Mirai} and \textit{Exim}). \smallskip \textbf{Scenario 1: Mirai.} This scenario is inspired by the Mirai botnet\cite{mirai-botnet}. The attacker gains access by successfully guessing SSH credentials. In the end of the scenario, the victim scans the internal network. As this scenario employs blacklisted IP addresses and domain names related to the Mirai botnet, it raises multiple (high priority) alerts in the \SOC{}. \textbf{Scenario 2: Exim.} The second scenario is based on a remote code execution vulnerability in an Exim 4 SMTP mail server \cite{exim-cve}. This scenario raises exactly one (high priority) alert in our \SOC{}. \smallskip Table~\ref{tab:scenario_comparison} provides a comparison of the two scenarios across the attack phases defined by MITRE ATT\&CK framework, and which phases can be detected by our \SOC\ configuration. Note that the scenarios are unaffected by the \GOODSOC\ or \BADSOC\ configurations, as the \GOODSOC\ configuration only removes 'policy violation' rulesets that are not triggered by either scenario. Due to the higher number of alerts related to the \MIRAI{} attack than for \EXIM{}, we consider the latter to be a more advanced scenario than the former. \begin{table*}[t] \caption{Comparison between the injected attack scenarios \MIRAI{} and \EXIM{}} \label{tab:scenario_comparison}\vspace*{-6pt} \begin{tabular}{@{}l} \includegraphics[]{table3.pdf} \end{tabular} \end{table*} \smallskip \emph{Attack injection.} The IP address of the attacker was rewritten to match the IP address defined in the scenarios. The attacks were injected in pre-recorded network traffic arriving at the \SOC\ during working hours. While we cannot guarantee the background traffic to be attack-free, we analyzed the most significant alerts observed in the traffic to ensure that generated alerts not related to the injected attacks are not symptomatic of known attacks. We found no evidence of ongoing attacks in the pre-recorded network traffic. \smallskip \emph{Attack report.} Due to infrastructural limitations, we collect reports using an online survey. \footnote{A \SOC{} would normally rely on an integrated case management system for incident reporting; this was not available in the employed \SOC{} setup.} Each group could report up to five\footnote{The limit of five activities was chosen after piloting. A discussion of implications on result validity is provided in section~\ref{sec:limitations}.} suspicious activities detected during the experiment. Table~\ref{tab:questionnaire} provides an overview of the questions. The first two questions asked for the attacker and victim IP addresses; as multiple entities can be associated to a role for an attack, we allow to insert more than a single IP address. Further, multiple-choice questions address reconnaissance, vulnerability exploitation, the delivery and control phase of the attack. For each of the selected answers it is required to specify the IP address involved with the selected action. Lastly subjects could report additional free-text comments. The full survey is available in the Appendix. To evaluate whether a report is a response to one of the injected attack simulations, we compare the reported IP addresses to the ground-truth from the scenario definition. If the attacker \textit{and} victim IP addresses of a scenario were both mentioned in the respective field, we mark the report to be a response to one of the corresponding scenarios. \begin{table}[t] \centering \caption{Summary of information expected in a report} \label{tab:questionnaire} \Description{Asking for the attacker and victim IP addresses allows to frame the reported scenario, i.e., identify whether the report is in response to one of the injected scenarios or not. Questions about the reconnaissance phase, the exploitation phase, and the delivery and control phases allow to identify whether the respective phase was correctly identified by the SOC analyst. Lastly space for comments allows analysts to provide further information.} \begin{tabular}{p{0.3\linewidth} p{0.6\linewidth}} \toprule {Analysis param} & {Info provided for result evaluation} \\\midrule {Attacker IP} & Framing of the reported scenario \\ {Victim IP} & Framing of the reported scenario \\ {Reconnaissance} & Detection of reconnaissance actions \\ {Exploitation} & Detection of exploitation actions \\ {Delivery \& C\&C} & Detection of delivery \& C\&C \\ {Comments} & Space for further information \\ \bottomrule \end{tabular} \end{table} \smallskip \emph{Technical setup.} We deployed two instances of the SOC environment and setup each accordingly to the \GOODSOC{} and \BADSOC{} configurations (ref. subsection~\ref{subsec:experimental-variables}). Each VM is powered by a machine with Intel(R) Xeon(R) Bronze 3104 CPU @ 1.70GHz with 12 cores and 64GB of RAM. During the experiment the two \SOC{} servers' sensors were isolated from the University's network. Students accessed their respective analysis environments from the classroom on their own PCs. \subsection{Experiment Pilot} Prior to execution we ran a set of pilots to refine the infrastructure and test the devised experimental procedures. A pilot phase was conducted to evaluate the survey procedure (incl. question phrasing) employed for the reporting phase. Further, the pilots were used to assess whether the difficulty of the assignment and the pre-experiment training sessions were a good match with students' skills. To this aim, we piloted the whole experiment four times, pooling for volunteers from students with a similar background to our subjects (e.g., enrolled in other security courses at the time, or PhD students in Computer Science). \subsection{Experimental Execution} Student autonomously created groups of two and each group was assigned randomly to the \BADSOC\ (n=31) or \GOODSOC\ (n=32) experimental conditions. Students were given half a bonus point valid for the final exam for attending the experiment and if they managed to correctly identify (at least one) attacker in the injected attacks. \begin{figure}[t] \centering \includegraphics[width=0.5\columnwidth]{img/timeline.png} \caption{Experiment phases and duration} \label{fig:exptimeline} \Description[A timeline describing the individual phases of the experiment session and their duration.]{The experiment session lasted 115 minutes. First: 25 minutes crash course on incident investigation and a (SOC) walk-trough. Then: 15 minutes warm-up exercise. Then: 10 minutes break. Then: 50 minutes exercise (main experiment). Then: 15 minutes questionnaire.} \end{figure} The experiment session started with an introduction and training session lasting approximately 30 minutes. After introducing the assignment, we ran a 15 minutes warm-up exercise where students had to identify a simple scenario with small network traffic to familiarize with the interface. The warm-up exercise was run on the \BADSOC\ configuration for all groups.\footnote{The warm-up exercise, albeit simpler and shorter than the actual exercise, follows the same structure as the subsequently injected attacks.} The experiment was run after the warm-up phase and lasted 50 minutes. Subjects were told that at least one attack would be injected but were unaware of attack type and timing. At the end of the experiment, traffic injection was terminated, and the survey used for report collection was made available. Students were asked to submit their reports within 15 minutes but retained access to \SOC{} and questionnaire until all submissions were collected. Figure~\ref{fig:exptimeline} provides a visual representation of the experiment timeline. \subsection{Ethical and experimental considerations} \label{sec:limitations} The background noise traffic was captured from the \SOC\ operating at the M\&CS department of the host university under the ethical and organizational approval of the university. The traffic raw data was not accessible to the students during the experiment (i.e., they could only see the alerts generated based on the original traffic). The experiment was integrated in the practical educational activities run by the university and performed following guidelines approved by the university for exercises in classroom settings. \smallskip \emph{Experimental limitations.} \textbf{(a) Construct validity.} We implicitly assume that students who report the correct IP addresses for both attacker and victim detected the attack and started analyzing it. Using automated checking it is impossible for us to determine whether a group actually understood what happened. \textbf{(b) External validity.} Students do not have the same experience and training that \SOC{} analysts do and the training during the introduction section cannot make up for that. In real settings, the experiment should be replicated against multiple analysts and using a portfolio of attacks, as opposed to only one or two attack scenarios, to obtain ample validity across experimental conditions. \textbf{(c) Internal validity.} Students were told in advance that there would be at least one attack, creating an expectation to find something. Further, by allowing students to submit up to five incidents and not penalizing `false positive' reporting, our experiment may inflate the number of reports per group. As this limit is the same across all groups and treatments, we do not expect any effect on the likelihood that groups report the `real' injected incidents (i.e. our main experimental outcome). \section{Experimental Results} \label{sec:experimentresults} Whereas students could submit up to five reports, we expected exactly two reports detecting the injected attack scenarios \MIRAI{} and \EXIM{} respectively. Table~\ref{tab:expectations} reports the correct answers related to the \MIRAI\ and \EXIM\ scenarios. \begin{table}[t] \centering \caption{Expected findings/ground-truth for both scenarios} \label{tab:expectations} \Description{We expect reports in response to the Mirai attack to mention \MIRAIATTACKERIP{} as attacker IP address, \MIRAIVICTIMIP{} as victim IP address, 'port scan` as reconnaissance action, `weak credentials' as vulnerability or exploit used, and `data exfiltration' and `HTTP requests' as activities observed in the Delivery and Command and Control phase of the attack. In response to the Exim attack we expect reports to mention \EXIMATTACKERIP{} as attacker IP address, \EXIMVICTIMIP{} as victim IP address, 'port scan` as reconnaissance action, `remote code execution' as vulnerability or exploit used, and `data exfiltration' and `HTTP requests' as activities observed in the Delivery and Command and Control phase of the attack.} \begin{tabular}{p{0.26\columnwidth} p{0.30\columnwidth} p{0.30\columnwidth}} \toprule {Analysis param} & \MIRAI & \EXIM{} \\\midrule {Attacker IP } & \MIRAIATTACKERIP{} & \EXIMATTACKERIP{} \\ {Victim IP } & \BLINDED{\MIRAIVICTIMIP{}} & \BLINDED{\EXIMVICTIMIP{}} \\ {Reconnaissance} & port scan & port scan \\ {Exploit/Vuln.} & weak credentials & remote code exec. \\ {Delivery/C\&C} & data exfiltration\hfill\break HTTP requests & data exfiltration\hfill\break HTTP requests\\ \bottomrule \end{tabular} \end{table} \subsection{Attack identification} We received 63 submissions (one per group) reporting a total of 162 incidents. Figure~\ref{fig:plot-submission-histogram} \begin{figure}[t] \centering \includegraphics[width=\linewidth,height=6cm,keepaspectratio]{plot_submission_histogram} \caption{Aggregation of groups by \# submitted reports} \label{fig:plot-submission-histogram} \Description{Participants were allowed to submit up to five potential attacks. In the BADSOC condition, 7 groups submitted one report, 13 groups submitted two reports, 9 groups submitted three reports, 2 groups submitted four reports, and 1 group submitted five reports. In the GOODSOC condition, 6 groups subitted one report, 5 groups ubsmitted two reports, 11 groups submitted three reports, 5 groups submitted four reports, and 4 groups submitted five reports.} \end{figure} reports overall submission rates for all groups in the \BADSOC{} ($m=2.28,\ sd=0.99$) and \GOODSOC{} ($m=2.9,\ sd=1.3$) configurations. Overall, the 32 groups working on \BADSOC{} submitted 73 reports, the 31 groups on \GOODSOC{} submitted 89 reports in total. A Wilcoxon Rank-Sum test results in \BADSOC{} producing significantly less reports than \GOODSOC{} ($p=0.02,\ W=353.5$). This suggests that groups assigned to the \GOODSOC{} condition were able to reconstruct more `suspicious' activities than groups assigned to \BADSOC{}, despite the events related to these activities being available to both treatment groups. Overall, $26\%$ of \BADSOC{} reports (19/73) and $33\%$ of \GOODSOC{} reports (29/89) detailed the injected attack scenarios (i.e., the majority of reports were \textit{not} about the injected attacks). As groups could report up to five incidents, this is unsurprising. To evaluate reporting in more detail, Figure~\ref{fig:plot-group-report-count} \begin{figure}[t] \centering \includegraphics[width=\linewidth,height=6cm,keepaspectratio]{plot_group_report_count} \begin{minipage}{0.9\columnwidth} \footnotesize \smallskip Column \enquote{both} represents the number of groups that reported both scenarios (\MIRAI{} \emph{and} \EXIM{}), while \enquote{none} represents the number of groups that did not report any of the scenarios. \end{minipage} \caption{\textit{Attack identification} by reported scenario.} \label{fig:plot-group-report-count} \Description{In total, 32 groups operated in the BADSOC configuration, 31 groups in the GOODSOC condition. In BADSOC 14 (out of 32) groups did not report any attack, 10 reported the Mirai and 9 the Exim attack. Out of the 18 groups that found at least one attack, one reported both attacks. In GOODSOC 9 (out of 31) groups did not report any attack, 12 reported the Mirai and 17 the Exim attack. Out of the 22 groups that found at least one attack, 7 reported both attacks.} \end{figure} shows the distribution of reports on the injected scenarios. Overall, 57\% of groups in \BADSOC{} and 71\% of groups in \GOODSOC{} reported at least one of the injected attacks. Whereas no noticeable difference against \MIRAI{} reporting rates can be observed ($p=0.36,\ OR=1.38$), \GOODSOC{} groups were approximately three times more likely to report the \EXIM{} attack ($p=0.03,\ OR=3.04$) than the \BADSOC\ groups, and approximately eight times more likely to report both attacks ($p=0.02,\ OR=8.49$) overall. However, if one considers only groups that reported at least one of the attacks, the difference between \GOODSOC{} and \BADSOC{} decreases and becomes borderline significant ($p=0.09$,\ $OR=5.56$); this may suggest that, under our treatment conditions, groups that perform well and detect at least one attack are more likely to find both irrespective of the \SOC\ configuration. Similarly, \BADSOC\ groups seem overall more likely ($OR=1.88$) than \GOODSOC{} to \textit{not} report either of the attack scenarios, albeit the difference is not significant ($p=0.17$). These findings provide an initial indication that the proposed solution can be effectively employed to evaluate (relative) SOC performance across SOC configurations (e.g., before and after a major configuration change in a deployed \SOC{}). \subsection{Attack investigation} We now provide a breakdown over the \emph{reconnaissance}, \emph{exploitation}, and \emph{delivery \& control} attack phases across the two injected attack scenarios. Results are reported in Table~\ref{tab:content-result-table}. \begin{table*}[t!] \centering \caption{Report results of \textit{attack investigation}.} \label{tab:content-result-table}\vspace*{-6pt} \begin{tabular}{@{}l} \includegraphics[]{table6.pdf} \end{tabular} \end{table*} \paragraph{Reconnaissance.} For both injected attacks, \enquote{port scan} was the correct answer, when asked for the observed reconnaissance activity in the questionnaire (see Table~\ref{tab:expectations}). For the \MIRAI{} attack, the correct answer was given by 70\% (7/10) groups operating on \BADSOC{} and 75\% (9/12) groups operating on \GOODSOC{} configuration ($p=0.58,\ OR=1.27$). The ratio of reports mentioning the portscan for the \EXIM{} attack is, overall, lower than for \MIRAI{}, albeit no significant difference emerges ($p=0.42,\ OR=2.39$): In \BADSOC{} 11.1\% (1/9) correct answers, in \GOODSOC{} 23.5\% (4/17). In conclusion, \GOODSOC{} did not perform significantly better than \BADSOC{} with in the detection of the portscan in none of the scenarios. \paragraph{Exploitation.} For exploitation activity, Table~\ref{tab:content-result-table} shows that barely half of the groups selected the correct answer \enquote{weak credentials} when asked to report the exploitation vector abused by the attacker in the \MIRAI{} attack, i.e. 50\% (5/10) in \BADSOC{} and 41.7\% (5/12) in \GOODSOC{}. For the \EXIM{} attack, Table~\ref{tab:content-result-table} shows that 88.9\% (8/9) of the groups in \BADSOC{} that reported the \EXIM{} attack also reported the correct vulnerability \enquote{remote code execution} abused by the attacker to gain foothold on the victim. In \GOODSOC{}, 82.4\% (14/17) answered correctly. On neither of the two injected attacks \GOODSOC{} performed better than groups working with the \BADSOC{} (\MIRAI{}: $p=0.79,\ OR=0.73$, \EXIM{}: $p=0.84,\ OR=0.59$). In fact, \BADSOC{} performed slightly better than \GOODSOC{} in identifying the correct exploitation vector (\MIRAI{}: $p=0.52,\ OR=1.38$, \EXIM{}: $p=0.57,\ OR=1.68$). Putting the differences between \BADSOC{} and \GOODSOC{} aside, all groups were more likely to identify the correct exploitation actions in \EXIM{} (85\%, or 22/26) than in the \MIRAI{} scenario (45\%, or 10/22). \paragraph{Delivery \& Control.} We expected groups to select two correct answers in a multiple-choice question about the delivery and control activities observed in context of an attack. The answers \enquote{data exfiltration} and \enquote{HTTP requests} are considered correct for both simulated attacks (see Table~\ref{tab:expectations}). Of the groups who reported on the \MIRAI{} attack, 66.6\% (8/12) using \GOODSOC{} and 60\% (6/10) of the groups using \BADSOC{} reported at least one of the two activities ($ p=0.55,\ OR=1.32 $). Looking at the \EXIM{} attack, 22\% (2/9) of the groups reporting the attack on \BADSOC{} and 18\% (3/17) on \GOODSOC{} also mentioned one correct delivery/control activity ($p=0.79,\ OR=0.76$). No group submitted both correct answers, regardless of their condition or reported attack. Again, there are no significant differences in performance between \BADSOC{} and \GOODSOC{}. In the \MIRAI{} scenario option \enquote{HTTP requests} was likely to be selected roughly four times more often ($p=0.099,\ OR=4.32$) by groups operating \GOODSOC{}. In the \BADSOC{} configuration 30\% (3/10) selected it, in \GOODSOC{} 67\% (8/12). Only three groups, all using \BADSOC{}, chose the correct answer \enquote{data exfiltration} when reporting the \MIRAI{} attack. For the \EXIM{} attack, most groups, 56\% (5/9) in \BADSOC{} and 71\% (12/17) in \GOODSOC{} \emph{wrongly} chose \enquote{none of them}. \section{Discussion of results and presentation of the \SAIBERSOC{} tool} \label{sec:discussion} \begin{figure*}[t] \includegraphics[]{fig5.pdf} \caption{Screenshot of the \SAIBERSOC{} web interface and relation to the relevant architectural components.} \label{fig:saibersoc-ui} \Description[A screenshot of the SAIBERSOC user interface.]{\SAIBERSOC{} allows to generate attacks based on attack traces and inject them into the network. The picture shows three different views: the attack-trace library, the view to generate a new experiment, and lastly a timeline view of an assembled attack that can be injected at a later point in time.} \end{figure*} The presented results indicate that the \SAIBERSOC{} methodology is capable of highlighting the modifications introduced between SOC configurations. In our experiment, the \GOODSOC{} configuration significantly increases the chances of a correct \textit{attack identification}; however, the \BADSOC{} vs \GOODSOC{} conditions do not significantly affect the chances of correctly investigating the attack across its phases, indicating that the change in configuration leaves \textit{attack investigation} capabilities unaffected. Overall, in our example application the \SAIBERSOC{} method indicates that the \GOODSOC\ configuration is preferable to the \BADSOC\ configuration as it significantly increases (up to threefold) the likelihood of identification of incidents. In particular, if \GOODSOC\ and \BADSOC\ were alternative environments tested in a SOC environment, using the \SAIBERSOC\ solution the SOC manager of that infrastructure could conclude that analysts working with the \GOODSOC{} configuration were more likely to find one or both of the attacks: analysts on \GOODSOC{} were three times more likely to find the (slightly harder to identify) \EXIM{} attack ($p=0.03,\ OR=3.04$) than analysts on \BADSOC. The method results indicate that analysts in the \BADSOC{} configuration are either overwhelmed by the number of alerts to investigate or require more time analyzing individual events and therefore had no time to analyze the second scenario. However, analysts working with \GOODSOC{} produced more false-positive reports, i.e., reports \emph{not} in response to one of the injected attacks. This may indicate that analysts working on \GOODSOC{} either spent less time per analysis and thus could write more reports in the same time, or that they are generally more likely to report false-positives. \footnote{This effect may be caused by our experiment design; students had the \textit{expectation} to find at least one attack and were rewarded on finding at least one of the injected attacks, which may lead to over-reporting.} By contrast, no significant differences between \BADSOC{} and \GOODSOC{} can be observed in the \textit{attack investigation} phase. This provides additional information on the SOC performance related to which aspects of an incident investigations are (positively or negatively) affected by the different configurations under test. The ability to quantify these effects experimentally allows both researchers and practitioners in making informed decisions on technological and process-level solutions for security monitoring application. \smallskip \emph{Implications for research.} The \SAIBERSOC{} method can be used to evaluate the effect on security analysis of virtually any live analysis setting (such as a SOC or other security monitoring or analysis environments), either technical, procedural, or human. For example, \SAIBERSOC{} can be employed to evaluate the impact of factors such as the analysts' experience, skill composition, and training, or the effect of analysis and visualization tools by comparing the performance of two \SOC{} configurations with a known set of selected differences. Similarly, the proposed method can be employed to evaluate multiple performance variables, including timing (e.g., total time for alert investigation) and throughput measures~\cite{shah2018methodology}), and how these vary across different phases of the attack. The extensibility of the proposed method further opens the door to the investigation of more complex effects, such as the relation between attack types and analyst skills/expertise~\cite{emse-20}, which are still under-researched in the scientific literature. The \SAIBERSOC{} implementation presented further down in this section provides a practical tool to deploy experiments based on the propose method in live or laboratory environments. \smallskip \emph{Implications for practice.} The \SAIBERSOC{} methodology (and tool) is fully flexible in terms of attack procedure, traces, and outcome variables, and can be implemented in operational \SOC{}s to evaluate the relative performance of their configuration over the desired metrics. This includes both technical (e.g., rulesets, use-cases, alert correlation rules) and human-level (e.g., analysis processes, analyst expertise, flat vs. hierarchical reporting structures) aspects of SOC operation, both of central importance for effective incident detection and reporting~\cite{kokulu2019matched,muniz2015security}. Examples of concrete use-cases are comparison of \SOC{} performance before and after changes in \SOC{} configuration, or continuous monitoring of \SOC{} performance. Further, the proposed solution can be integrated in analyst training procedures, or as part of a selection procedure for security professional roles. \subsection{\SAIBERSOC\ tool implementation} \label{subsec:saibersoc-tool} To operationalize the \SAIBERSOC{} methodology, after its validation, we developed the \SAIBERSOC{} tool as an open source software solution. \SAIBERSOC{} implements all four architectural components outlined in subsection~\ref{subsec:architecture}. It is deployed with a web-based front-end (depicted in Figure~\ref{fig:saibersoc-ui}) interacting with a backend. A comprehensive API enables scripted access to all backend functionalities. \emph{Functionalities and User Interface.} Figure~\ref{fig:saibersoc-ui} shows the deployed web interface and how architectural components (see subsection~\ref{subsec:architecture}) \arch{1}\ldots\arch{3} are implemented in the web interface; report evaluation (\arch{4}) is not yet accessible through the frontend. On the left side of the screen, UX element \encircle{A} provides access to the attack \emph{trace library} (\arch{1}) showing previously uploaded network traffic recordings. A user can manually add traces onto a timeline \encircle{B} in the center of the screen. Convenience features allow to search a specific attack trace in the library or select a random one. From the timeline \encircle{B}, the offset and playback speed can be adjusted for each attack trace individually. In the lower section of the screen, \encircle{C} provides additional configuration options for the selected attack trace. Here, IP addresses and whole IP address ranges can be rewritten to create a realistic attack scenario for the monitoring environment. Buttons \encircle{D}, in the upper right area, provide functionalities to load and save experiments/attacks and to start, stop, or schedule their injections (\arch{3}). During attack injection (\arch{3}), state and progress is visualized on the timeline \encircle{B} using a vertical red line as progress indicator. The tool is capable of automatically extracting a ground-truth based on the metadata from the attack trace library (\arch{1}) and the optional IP address rewrites in \arch{2}. A \SOC{} report, allegorized by a \texttt{csv} file, can be checked against the ground-truth derived from the attack traces (\arch{4}). \emph{Tool implementation and API.} The \SAIBERSOC{} web application is implemented in \texttt{Python}. The (HTTP) API is based on \texttt{Flask}\cite{flask} and the \texttt{Flask-RESTX} framework\cite{flask-restx}. The web-frontend is built on top of the API using \texttt{vue.js}\cite{vuejs}. \noindent\textbf{Attack Traces~(\arch{1})}: The attack trace library consists of attack traces in form of \texttt{pcap} network traffic recordings linked to metadata stored in an internal database.\hfill\break \noindent\textbf{Attack Generation~(\arch{2})}: Internally, \SAIBERSOC{} uses a list of \emph{blocks} to specify an attack. Each \emph{block} consists of an attack trace (taken from the attack trace library) and additional information specifying time offset, playback speed, and IP address rewriting. Once an attack is fully sketched out, \texttt{scapy}\cite{scapy} is used to assemble a single intermediate attack \texttt{pcap}.\hfill\break \noindent\textbf{Attack Injection~(\arch{3})}: \SAIBERSOC{} invokes \texttt{tcpreplay}\cite{tcpreplay} to inject the \enquote{intermediate attack \texttt{pcap}} on a network interface. Optionally, background noise can be replayed together with the attack.\hfill\break \noindent\textbf{Reporting~(\arch{4})}: The reporting module extracts and combines the IP address rewriting from \arch{2} and attack trace metadata from \arch{1} as ground-truth. It then compares selected columns from an uploaded \texttt{csv} file against the extracted ground truth. \emph{Publication, Development, and Licensing} The development of \SAIBERSOC{} was supported by a team of BSc students as part of their final graduation project. The \SAIBERSOC{} tool is released under Mozilla Public License (MPL 2.0). Source code, extensive documentation, and supplementary materials are available from the artifact repository at \url{https://gitlab.tue.nl/saibersoc/acsac2020-artifacts}.% \section{Conclusion} \label{sec:conclusion} In this paper, we proposed a methodology based on attack injection to systematically measure \SOC{} performance across SOC configurations, analyst expertise, and for any output metric (e.g., accuracy, time-to-report, \ldots). We verified the proposed methodology by conducting an experiment in which 124 students assumed the role of a \SOC{} analysts. Our results show that the proposed methodology is capable of systematically measuring \SOC{} performance and attributing it to differences in configuration, where some is to be expected. Our solution is general and can be implemented in any SOC. In addition, we developed the \SAIBERSOC{} tool to help replicate the experiments and facilitate SOC exercises. \hyphenation{DEFRAUDIfy} \begin{acks} This work is supported by the DEFRAUDIfy project (grant no. ITEA191010) funded by the ITEA3 program by Rijksdienst voor Ondernemend Nederland and the DEPICT project (grant no. 628.001.032) by Nederlandse Organisatie voor Wetenschappelijk Onderzoek. \end{acks} \balance \bibliographystyle{ACM-Reference-Format} \section*{Appendix} \begin{table*}[t] \centering \caption{Mapping between requirements and architectural components.} \label{tab:requirements-implementation-mapping} \begin{tabular}{l p{0.21 \textwidth} p{0.21\textwidth} p{0.21\textwidth} p{0.21\textwidth}} \toprule \require{ID} & \arch{1} & \arch{2} & \arch{3} & \arch{4} \\ \midrule \require{1} & Attack traces are independent of the monitored environment. & The attack generation allows for the matching of the traces to the environment. & & The reporting and comparison relies on the ground truth for the generated scenario. \\ \require{2} & The attack traces identify all MITRE ATT\&CK `building blocks'. & The generated attack can suit any final environment and attack scenario. & & \\ \require{3} & & Attacks can be mapped to the target environment using asset information always available at the SOC. & The injection happens in the real network flow monitored by the SOC. & \\ \require{4} & & The tailoring of the attack generation guarantees the existence of a ground-truth for the examination. & & The analyst report can be automatically checked against the attack parameters (\arch{2}). \\ \bottomrule \end{tabular} \end{table*} \begin{table*}[t] \centering \caption{Implementation example across \arch{1}\ldots\arch{4}.} \label{tab:example} \begin{minipage}{0.97\textwidth} \footnotesize Each \texttt{AC} is characterized by its parameters (par.), execution (exec.) and output. In \arch{1} the attack traces are structured across the MITRE ATT\&CK phases; in \arch{2} these traces are parametrized for the specific environment, for example with IP ranges corresponding to the monitored infrastructure; \arch{2} produces the traces that will be injected based on the defined parameters and generates the attack by ordering the traces following the ATT\&CK framework phases. The parameters of \arch{2} also characterize the ground truth of the attack. \arch{3} injects the generated attack in the infrastructure, generating the corresponding alerts at the \SOC\ level; finally, \arch{4} checks the analyst's evaluations against the ground truth defined by the parametrization in \arch{2}. \end{minipage} \begin{tabular}{p{0.001\textwidth} p{0.155\textwidth} p{0.30\textwidth} p{0.16\textwidth} p{0.21\textwidth}} \toprule & \textbf{\arch{1} Trace} & \textbf{\arch{2} Attack Generation} & \textbf{\arch{3} Injection} & \textbf{\arch{4} Report} \\ \midrule \multirow{2}{*}{\rotatebox{90}{param}} & Identification of the needed attack phases & Attacker, victim, and CnC IP(s), URLs, \#CVE, protocols, encryption, ... & Setting up pcap injection and schedule & 1. \SOC{} report;\newline 2. Attack ground-truth \\ \midrule \multirow{4}{*}{\rotatebox{90}{execution}} & Gathering or creation of attack traces & \textbf{Recon:} \textit{portscan}(src_ip, dst_ip);\newline \textbf{Expl:} \textit{exploit_cve}(cve, src_ip, dst_ip);\newline \textbf{Del:} \textit{http_get}(src_ip, url, tls);\newline \textbf{C\&C: }\textit{contact_cnc}(src_ip, dst_ip, prot, enc) & Pcap is injected in the sensor of the SOC according to schedule (e.g, 12pm) & Comparison of SOC report and attack ground-truth \\ \midrule \multirow{4}{*}{\rotatebox{90}{output}} & \textbf{Del.:} \textit{http_get}();\newline \textbf{Expl.:} \textit{exploit_cve}();\newline \textbf{Recon.:} \textit{portscan}();\newline \textbf{C\&C:} \textit{contact_cnc}() & 1. Pcap of the synthetic attack built from the parametrized phases;\newline 2. Attack ground-truth (expectations) & (At 12pm) pcap on wire is raising alerts in the SOC & e.g., \SOC{} found portscan and CnC activity, but \textbf{not} exploitation \textbf{and} reported false positive lateral movement. \\ \bottomrule \end{tabular} \end{table*} \subsection*{Data Collection and Analysis} \paragraph{Evaluation for possible typos} In an exploratory data analysis, we observed that some groups reported IP addresses that are very similar to the ones we expected to see as attacker or victim IP address in one of the two scenarios. Based on the difference between the IP addresses in the report and the ground-truth, we conclude that it is very likely that those are typos or copy-paste errors. In other cases, groups did not make the right selections in the multiple-choice part of the questionnaire, but later mentioned correct details in the additional comment section of the report. For example, group 78 did not indicate that they observed \enquote{http requests} through the multiple-choice selection but wrote \enquote{[\ldots] this malware made a HTTP request [\ldots]} in the additional comments. To ensure automatic and reproducible processing of the results, we decided to only consider IP addresses that are perfect matches and solely rely on the multiple-choice selection. \paragraph{Submissions violating the enforced format} Some groups managed to submit reports that violate the constraints enforced through the questionnaire. This mostly includes submissions that ticked more or less checkboxes than we allowed. Group 80 was able to select three options where the questionnaire was supposed to allow no more than two selections. We kept those submissions as they do not interfere with our way of data analysis. \paragraph{Double-submission} One group submitted twice, i.e. we collected 64 submissions for 63 groups. While both submissions are similar, they are not identical. We decided to merge the submissions. The reports in response to one of the injected attack scenarios are merged by selecting the best parts of both submissions. We further decided to keep the submission time and duration of their first submission. \paragraph{(Not) Accepting \enquote{lateral movement} in \MIRAI{}} We initially did not plan to accept \enquote{lateral movement} as a correct answer in \MIRAI{} scenario. In the \MIRAI{} scenario, the victim eventually mirrors the attacker's behavior and starts scanning the local network for vulnerable hosts. While the scenario ended before and therefore does not cover lateral movement, the network scan can be interpreted as a first step of lateral movement. We decided to \emph{not} accept \enquote{lateral movement} as a correct answer for the \MIRAI{} scenario. In total 40.0\% groups (4/10) in \BADSOC{} and 41.7\% groups (5/12) in \GOODSOC{} selected \enquote{lateral movement} (either alone or in combination with \enquote{http requests}). \subsection*{Questionnaire} Based on the choice on question~9, questions~3--8 can be repeated up to four additional times (i.e., a total of five reports can be submitted). The decision to limit the number of reports per submission was induced by limitations of the survey tool used to collect the results. \begin{enumerate} \item \textbf{Insert your student ID}\\ Multiple short text fields for multiple student IDs. Answers are considered personal data. \item \textbf{Which was your SOC name?}\\ Binary choice between \BADSOC{} and \GOODSOC{} (names changed). \item \textbf{Insert the IP address(es) of the attacker, one per line. If no IP address is known, write \enquote{NA}.}\\ Multi-line text field. \item \textbf{Insert the IP address(es) of the attacker, one per line. If no IP address is known, write \enquote{NA}.}\\ Multi-line text field. \item \textbf{Did you observe any of the following reconnaissance activities?}\\ Multiple choice single selection only: \enquote{Username enumeration}, \enquote{Port scan}, \enquote{SIP scan}, \enquote{Web application vulnerability scan}, \enquote{None of them}, \enquote{Other (small text field to specify)}. \item \textbf{Which vulnerability did the attacker exploit?}\\ Multiple choice, multiple selections possible: \enquote{SQL injection}, \enquote{Weak credential}, \enquote{DNS remote command execution}, \enquote{Poor web server configuration}, \enquote{Remote coded execution}, \enquote{None of them}, \enquote{Other (small text field to specify)}. \item \textbf{Which of the following actions did you observe? (check at most 2 boxes). For each option selected insert IP address of the receiver of such activities (i.e. HTTP requests -> web server's IP; enumerating SMB shares -> SMB server's IP;.}\\ Multiple choice, at least one, at most two answers can be selected. Except of \enquote{No action observed}, all answers have a small text field to further specify an IP address: \enquote{Data exfiltration}, \enquote{Enumerating SMB shares}, \enquote{HTTP requests}, \enquote{Denial of Service attack}, \enquote{Web server path traversal}, \enquote{NTP amplification}, \enquote{Network lateral movement}, \enquote{No action observed}. \item \textbf{Anything else to report about this attack?}\\ Multi-line text field. \item \textbf{Do you want to report another attack?}\\ Binary yes/no selector. Subjects could submit up to five reports (questions 3 -- 8), selecting \enquote{yes} would allow them to continue, selecting \enquote{no} would allow them to submit their results. \item \textbf{Did you had fun?}\\ Rating-scale 1 (really boring) -- 5 (it was great) \item \textbf{Do you think the introduction was enough to do the exercise?}\\ Rating-scale 1 (not at all) -- 5 (definitely enough) \item \textbf{Do you think we should do again this next year?} Binary yes/no selection. \item \textbf{Did you find anything particularly challenging during the investigation process?}\\ Multi-line text field. \item \textbf{Write here any other suggestions you might have in mind.}\\ Multi-line text field. \end{enumerate} \section{Introduction} The growing importance of effective security monitoring solutions calls for appropriate measures of their effectiveness. The operation of Security Operation Centers (SOCs) is the recommended best practice to which large and medium-size enterprises rely for the detection, notification, and ultimately response to cybersecurity incidents~\cite{kokulu2019matched,muniz2015security}. Yet, the average time for detecting an attack ranges between several weeks to years~\cite{verizon2018}. In a recent study, Kokulu et al.~\cite{kokulu2019matched} interviewed security analysts and mangers, who explicitly identify the issue of \textit{measuring} SOC performance as one of the main obstacles towards effective detection and response operations. The problem of measuring security (performance) is a long-standing and difficult one~\cite{herley2017sok}. Measuring the performance of \SOC{}s is no exception. Whereas numerous performance metrics exist (e.g., number of detected incidents, time to detection, time to response, etc.)~\cite{shah2018understanding}, it is still unclear how to obtain reliable and reproducible measures over those metrics. As incoming attacks are, by definition, unknown, a ground truth on which to base the measurements cannot be easily defined; on the other hand, performing measurements in \textit{in-vitro} settings limits the representativeness of those measurements in real-world settings~\cite{shah2018methodology,kokulu2019matched}. However, the problem of measuring the performance of infrastructures and systems dedicated to the detection of \textit{rare} events of unknown magnitude is not new. For example, the \textit{LIGO} (\textit{Laser Interferometer Gravitational-Wave Observatory}) infrastructure has been built with the goal of detecting perturbations in the spacetime continuum caused by `rippling effects' of large-scale events, such as the collapse of a binary blackhole system. Despite the completely different settings and event generation processes, the challenges faced by the LIGO interferometer and SOCs are quite similar: both must detect unknown, unpredictable, and arbitrarily `small' manifestations of an event, and both must know whether the detection procedure is accurate while operating in the absence of a ground-truth on the events that ought be detected. This paper presents \texttt{SAIBERSOC}, a practical and deployable solution for SOC performance evaluation based on the same working principle as the LIGO infrastructure~\cite{PhysRevD.81.102001}: to generate and automatically inject `events' (in our case, cyber-attacks) into the detection infrastructure at random instants in time, with the purpose of evaluating, in a controlled fashion, the performance of the detection system. The \SAIBERSOC{} methodology and tool can be employed by researchers and security operatives alike to evaluate the impact of various factors on SOC performance, such as analyst training, experience , and skill composition, or the relative change in effectiveness of the deployed analysis and visualization tools as the SOC configuration and processes change. \SAIBERSOC{} automatically generates the injected attacks relying on the MITRE ATT\&CK Framework\cite{mitre_attck} and is structured over four components providing automated methods for attack definition, generation, injection, and analysis. The \SAIBERSOC{} tool is publicly available as free and open source software (see \autoref{subsec:saibersoc-tool}). To evaluate the effectiveness of the method at the core of \SAIBERSOC{}, we design and run an experiment employing $n=124$ students enrolled in a security course of a medium-sized technical university in Europe. The experiment relies on a real SOC infrastructure (normally monitoring network events at the M\&CS department of the university) where students operate as SOC analysts. In particular, we measure detection accuracy in terms of both attack \textit{identification} and \textit{investigation}, injecting two attacks based on the \MIRAI{}~\cite{mirai-botnet} and \EXIM{}~\cite{exim-cve} scenarios over two SOC configurations (\BADSOC{} and \GOODSOC{}). Our evaluation shows that the \SAIBERSOC{} methodology correctly identifies and can quantify the relative change in detection accuracy across SOC configurations and, importantly, does not \enquote{overshoot} or reveal differences where there should be none. \smallskip This paper develops as follows: \hyperref[sec:background]{Section~\ref*{sec:background}} provides a background on SOC operations and discusses relevant literature. \hyperref[sec:method]{Section~\ref*{sec:method}} describes the proposed methodology and \autoref{sec:validationmethodology} the experimental validation strategy. Experimental results follow in \autoref{sec:experimentresults}. \hyperref[sec:discussion]{Section~\ref*{sec:discussion}} discusses our results and presents the \SAIBERSOC{} software implementation in detail. Finally, \autoref{sec:conclusion} concludes the paper. \section{Background and Related Work} \label{sec:background} \subsection{Attack frameworks} Defensive operations against increasingly sophisticated attacks require a deep understanding of how adversaries conduct offensive operations, how threats unfold and how security breaches escalate into major incidents. The MITRE PRE-ATT\&CK\cite{mitre_pre-attck}, MITRE ATT\&CK \cite{mitre_attck}, and Cyber Kill Chain\cite{lockheed_martin} frameworks aim at building a knowledge base of adversary TTPs (Tactics, Techniques, and Procedures) from real-world observations, grouping them in a taxonomy of attack stages to describe the anatomy of any attack. The extensive and detailed enumeration of the attack techniques provided by the frameworks and stages can be, roughly, grouped in four phases: \textit{Reconnaissance}, \textit{Exploitation}, \textit{Delivery} and \textit{Control} (\autoref{tab:phases}). \begin{table}[t] \centering \caption{Attack phases} \label{tab:phases} \Description{Overview of the four phases `Reconnaissance', `Exploitation', `Delivery', and `Control'} \begin{tabular}{p{0.22\columnwidth} p{0.7\columnwidth}} \toprule \textbf{Phase} & \textbf{Description} \\\midrule Reconnaissance & Techniques to research, identify and select targets using active or passive reconnaissance. \\ Exploitation & Techniques employed by attackers to gain initial control over (vulnerable) target systems. \\ Delivery & Techniques resulting in the transmission of the weaponized object to the targeted environment. \\ Control & Techniques used by attackers to communicate with controlled systems in a target network. \\\bottomrule \end{tabular} \end{table} \textit{Reconnaissance} groups data gathering operations performed by the adversary, ranging from subject information for the development of social engineering attacks, to probing the network surface of the infrastructure to derive paths of compromise. During \textit{Exploitation}, the attacker evaluates the measured attack surface (vulnerabilities, misconfigured software, phishing opportunities) and creates or acquires the attacks (vulnerability exploits, phishing artefacts, malware, ...) to perform information leak, lateral movement (e.g., inside the organization), command execution, and/or privilege escalation. \textit{Delivery} covers the vectors adopted from the adversary to drop malicious software that will act as a foothold for further actions. This includes spear phishing and supply chain compromise. \textit{Control} includes the techniques adopted by the adversary to control the system and reliably execute commands on it, compromising system integrity, confidentiality and availability. This can be achieved via remote management interfaces, custom software and web services. \subsection{Security monitoring operations} Tools and procedure to support security analysts in incident response and network monitoring (such as Network Intrusion Detection Systems (NIDS) and Security Information and Event Management (SIEM)) are at the core of modern security monitoring in operational settings. \textit{Security Operation Centers} (SOCs) are the center of monitoring operations in medium or large organizations, either internally or outsourced to service providers~\cite{muniz2015security,kokulu2019matched}. SOCs are organized hierarchically in (generally three) tiers~\cite{muniz2015security}, where analysts with different skills and expertise monitor the network activity and take action against a threat. Tier~1 is the first frontier where alerts are investigated by analysts, identifying possible threats among the non-significant ones and prioritizing them. Identified threats are escalated to Tier~2, where more qualified analysts with forensics and incident response skills correlate the information with threat intelligence to identify threat actors. Tier~2 is in charge to determine a strategy for containment, remediation and recovery. If the threat targets business critical operations, Tier~3 analysts identify and develop tailored responses to the identified threats and attack patterns. In general, incident investigation can be split in two phases~\cite{muniz2015security}: \textit{Attack identification}, where Tier 1 analysts evaluate incoming alerts to identify possible attacks; \textit{Attack investigation}, where Tier~1 and Tier~2 analysts investigate the identified attack over its phases (ref. \autoref{tab:phases}) to, for example, identify victims, attack timing, payloads, and propagation. Once these two phases are complete, the attack is reported and responded to, depending on the service level agreement at which the SOC operates. The large amount of alerts and potential security events detected in a SOCs make it impossible, operationally to `investigate everything'~\cite{shah2018understanding}: the more relevant are the alerts generated by a SOC (e.g., through accurate use-cases), the fewer `false positives' a (Tier~1) analyst will have to investigate before passing the baton on to higher tiers (i.e., Tier~2~and~3). However, \textit{measuring} how SOC operations respond to changes in the SOC configuration (e.g., a refined use-case, a different alert investigation process, new rulesets, etc.) remains an open and critical challenge~\cite{kokulu2019matched}, in terms of analyst competences as well as for metric definition and measurement \cite{shah2018understanding,shah2018methodology,zimmerman2014ten,ganesan2017optimal}. \subsection{SOC performance evaluation} Albeit attempts have been made in trying to tackle these problems, the scientific literature proposing methods to measure SOC performance is still limited. Effectiveness of a SOC depends on both the qualities of the tools adopted, their configurations and capabilities, and on skills of the personnel. For what concerns the correlation between human capabilities and a SOC's performance, a few studies have been made\cite{sundaramurthy2016turning, sundaramurthy2014tale}. In \cite{sundaramurthy2014tale}, Sundaramurthy et al., they trained three students to work as SOC analysts and embedded them in three different SOCs. While working as operational components, they were required to produce reports on their observations and meet with an anthropologist involved in the research. By comparing reports and interviews, is was possible to draw conclusions on the aspects that may be more promising to the effectiveness of a SOC and which not, in terms of its architecture, experience of analysts, nature and degree of their interactions, workflow for incident reports and the quality of work itself for the employee. Kokulu et al.~\cite{kokulu2019matched} investigate through interviews to both SOC analysts and SOC managers about technical and non-technical issues of a SOC; from their interviews emerge how often SOCs fail to provide substantial support against specific types of attacks, overloading analysts with low-quality threat intelligence, long reports and logs, and more. Albeit evidences are supported by interviews, the authors point out that metrics to measure security quantitatively and qualitatively are rudimentary \cite{kokulu2019matched}. Jacobs et al.~\cite{jacobs_towards_2014} propose a method to systematically and quantitatively evaluate \SOC{}'s maturity by identifying a set of capabilities that a \SOC{} embodies, i.e. log analysis, event correlation, incident management, threat identification and reporting, scoring each of them \cite{jacobs_classification_2013} \cite{jacobs_towards_2014}. The SOC aspects analyzed derive from a number of industrial security management and control frameworks, including ISO 27000 series \cite{iso_2019} and SANS Critical Controls and each of them is scored with respect to their maturity; however, the score attribution is left as an expert-driven task, rather than a data-driven measurement. A simulation-optimization approach is proposed by Shah et al. \cite{shah2018methodology}, where they identified some of the causes that negatively affect the throughput of a SOC in terms of efficiency. They propose the \textit{Time to Analyze Alert} (TTA) metric to evaluate the efficiency of a SOC by measuring the time that goes from the alert generation to its analysis. By monitoring SOC's TTA, Shah et al. are able to generate advice for the SOC Manager, suggesting live corrective actions towards a desired benchmark. In subsequent work Shah et al.\cite{shah2018understanding} also model the problem as a simulation-optimization problem and evaluated it from data derived from a simulated SOC, to obtain a set of metrics that allow the optimization of some of a SOC capabilities; however, a procedure to test the resulting SOC performance in real-world scenarios remains to be identified and tested. \smallskip \textbf{Research gap.} Whereas current research has focused mostly on the identification of metrics~\cite{shah2018understanding} and procedures~\cite{jacobs_towards_2014,shah2018methodology,shah2018understanding} to evaluate SOC performance, an empirical method capable of capturing the complexity of a SOC operation (including alert configuration, analyst capabilities, etc.) has yet to be proposed and validated~\cite{kokulu2019matched}. \section{The \SAIBERSOC{} solution} \label{sec:method} To address this gap, we propose \SAIBERSOC{}, a method and solution to perform systematic SOC performance evaluations through automated attack injection. Our solution is composed of four Architectural Components (\texttt{AC-\{1..4\}}) constituting of a library of (attack) traces (\arch{1}), and components to generate (\arch{2)}, inject (\arch{3}), and report (\arch{4}) the synthetic attacks. \begin{figure}[t] \centering \includegraphics[width=0.73\columnwidth]{img/flow_diagram.pdf} \begin{minipage}{0.9\columnwidth} \footnotesize \smallskip The platform uses (network) traces characterizing the \enquote{building blocks} of an attack (\arch{1}), and (re-)combines them to generate new attacks (\arch{2}). The generated attacks are then injected into the network (\arch{3}). The SOC analysts perform and report on the investigation results, which can be checked (\arch{4}) against the known ground-truth (derived from the attacks generated in \arch{2}). \end{minipage} \caption{Schematic depiction of the \SAIBERSOC{} solution} \label{fig:schema} \Description[Schematic overview of how the four components interact in relation to the Security Operations Center.]{Component `AC-1 Attack Traces' is a library of network traffic captures maintained by experts. In component `AC-2 Attack Generation' the network traces get merged. Experts monitor and supervise rules for merging network traces to ensure that the output is a realistic attack. The output of this component is the assembled attack ready to be replayed on the network, as well as a ground-truth that describes the assembled attack. In phase `AC-3 Attack Injection' the assembled attack is injected somewhere into a network monitored by the Security Operations Center. The Security Operations Center, unable to distinguish injected attack simulation traffic from regular network traffic, will investigate and report on the injected attack. In component `AC-4 Reporting' the report generated by an analyst in the Security Operations Center is compared to the automatically generated ground truth from `AC-2 Attack Generation'.} \end{figure} \SAIBERSOC{} can be used to inject attacks into a \SOC{} during operation, or alternatively in a \enquote{virtual} \SOC{} testing environment where all network traffic is replaced by pre-recorded background traffic. Once the attack has been detected, the \SOC{} analysts perform the investigation following their normal procedure. The type of injected attack as well as its timing, targets and sources, and velocity are unknown to the \SOC{} analysts. Finally, the analyst's attack report is automatically evaluated against the ground truth obtained from the attack assembly phase. A more detailed description of the \SAIBERSOC{} architecture can be found in \autoref{subsec:architecture}, we present our software implementation in \autoref{subsec:saibersoc-tool}. \subsection{Solution requirements} To guide the development of the proposed solution, we pose a list of requirements that a real-world \SOC{} performance evaluation framework should fulfill. A summary of the identified requirements is provided in \autoref{tab:requirements}. \begin{table*}[t] \centering \caption{Architectural requirements. \autoref{tab:requirements-implementation-mapping} in the Appendix details the mapping to the architectural components.} \label{tab:requirements} \Description[Mapping between requirements `R' and architectural components `AC' that must meet the respective requirement.]{Architectural components `AC-1', `AC-2', and `AC-4' must fulfill requirement `R-1 Independence' (the proposed solution should be independent of the specific SOC implementation and monitored environment). Architectural components `AC-1' and `AC-2' must fulfill requirement `R-2 Versatility' (the framework must work with all types of attack scenarios in scope of the SOC, regardless of their complexity). Architectural components `AC-2' and `AC-3' must fulfill requirement `R-3 Realism' (the attack injection must be seamlessly integrated to the operative environment of the analyst. This includes IP addresses, local software configurations, and network setups). Architectural components `AC-2' and `AC-4' must fulfill requirement `R-4 Tracability' (the framework must be able to link all SOC reactions i.e., a report to the initial stimulus or attack that caused it.).} \begin{tabular}{l l p{0.56\textwidth} c c c c} \toprule \require{ID} & \textbf{Requirement} & \textbf{Description} & \arch{1} & \arch{2} &\arch{3} &\arch{4} \\ \midrule \require{1} & Independence & The proposed solution should be independent of the specific SOC implementation and monitored environment. & \checkmark & \checkmark & & \checkmark \\ \require{2} & Versatility & The framework must work with all types of attack scenarios in scope of the \SOC{}, regardless of their complexity. & \checkmark & \checkmark & & \\ \require{3} & Realism & The attack injection must be seamlessly integrated to the operative environment of the analyst. This includes IP addresses, local software configurations, and network setups. & & \checkmark & \checkmark & \\ \require{4} & Traceability & The framework must be able to link all \SOC{} reactions (i.e., a report) to the initial stimulus or attack that caused it. & & \checkmark & & \checkmark \\ \bottomrule \end{tabular} \end{table*} \noindent\textbf{Independence (\require{1})} To measure and compare \SOC{} performance, the framework must apply to all \SOC{}s, regardless of how they are implemented. Further, the results must be reproducible, regardless of who uses the framework. Those are fundamental requirements for any measure or assessment~\cite{pfleeger2010measuring}. Therefore, a solution must be able to work with various \SOC{} configurations and implementations. \noindent\textbf{Versatility (\require{2})} To be able to create meaningful measures covering the whole scope of the \SOC{}, all aspects of a potential attack must be covered. Thus, a metric should cover the complete value-space to assure meaningful results reflecting real-world performance~\cite{kokulu2019matched}. Because attackers continuously adapt their behavior, a solution must be capable to simulate past, current, as well as future attacks in realistic ways to be able to measure real-world security. \noindent\textbf{Realism (\require{3})} Real-world security is influenced by numerous factors, sometimes in unpredictable ways. For example, wrong presumptions about context or human behavior in unforeseen situations leads to alleged security measures and therefore a false sense of security\cite{chiasson_quantifying_2015,adams2005bridging}. This can be avoided by assessing real-world performance, i.e., a setup that is as close as possible) to reality. In case of a \SOC{} this means measuring a real \SOC{} (including software and configuration), realistic work environments, and realistic attacks. It is therefore imperative that the evaluation is performed under real or realistic operational conditions (e.g., the analysts do not know the attacks in advance, and the injected attacks are realistic). \noindent\textbf{Traceability (\require{4})} The framework must be able to link \SOC{} reactions i.e., reports, to the attacks that caused those reactions in the \SOC{}. Only if both input and output are known, a meaningful evaluation of the \SOC{} performance can be made by comparing the \textit{expected} output to the realized output. \subsection{The \SAIBERSOC{} solution architecture} \label{subsec:architecture} \autoref{fig:schema} provides a schematic depiction of the architecture behind the proposed \SAIBERSOC{} solution. \autoref{tab:requirements} reports the mapping of the architectural components to the identified requirements. A running example of implementation of the proposed workflow is reported in \autoref{tab:example} in the appendix and discussed below. \subsubsection{Attack Traces (\arch{1})} \label{subsubsec:attack-module-database} All attack simulations or scenarios deployed in \SAIBERSOC{} are constructed by combining multiple pre-defined attack traces. An attack trace consists of a set of network packets (e.g., stored in a \textit{pcap} file) that reproduces the network traffic generated by an attack during a specific attack phase. These traces can be extended to non-network events (e.g., \textit{syslog} activity to reproduce events at the host level). To structure traces in attack phases, we rely on the ATT\&CK Framework\cite{mitre_attck} to create and store a library of different attack traces reflecting different phases of ongoing attacks (see \autoref{tab:phases}). The MITRE CALDERA\cite{caldera} and Atomic Red Team\cite{atomic} already maintain some form of an attack-database with attacker actions mapped to the ATT\&CK Framework\cite{mitre_attck}. \paragraph{Impl. example:} with reference to the example reported in \autoref{tab:example}, \arch{1} generates a set of traces characterizing events in each phase of the ATT\&CK framework; for example, \textit{portscan(src\_ip, dst\_ip)} will reproduce network traffic (to be parameterized with \textit{src\_ip, dst\_ip} associated to the \textit{Reconnaissance} phase of the MITRE ATT\&CK framework (ref. \autoref{tab:phases}). Similarly, \textit{expl\_cve()} will reproduce traces corresponding to the exploitation of a known vulnerability (e.g., as derived from an exploit on ExploitDB~\cite{exploitdb}. \subsubsection{Attack Generation (\arch{2})} \label{subsubsec:scenario-builder} Multiple attack traces are combined to generate fully-fledged attack simulations. Attacks are composed following the ATT\&CK framework\cite{mitre_attck} (i.e., reconnaissance happens before exploit delivery, which happens before command and control communication, which happens before data exfiltration). The CALDERA framework is already capable of automatically generating meaningful attacks from attack traces\cite{caldera}. In this step, the generic attack traces are matched to the specific environment monitored by the SOC (e.g., IP ranges, exploits vs vulnerable systems, etc.). This process can be automated by relying on asset information available to any SOC during normal operation. The result of this phase is a \textit{ready-to-inject} attack simulation. The \enquote{ground-truth} of the simulation (e.g., attacker's IP addresses(es)) can be extracted from the parameterized attack traces composing the attack. Once re-parameterized (i.e., victim IP addresses matching the range of a monitored network and system functionality), attack scenarios can be reused the \SOC{} or organization's network. \paragraph{Impl. example:} with reference to \autoref{tab:example}, a sequence of (attack) traces is selected and parameterized. In this example, the IP of the attacker and the receiving victim system(s) are identified (\textit{src\_ip,dst\_ip}), as well as the exploited vulnerability (\textit{cve}), and protocols used for the command and control (\textit{proto}). The parametrized attack traces are then composed following the MITRE ATT\&CK framework phases; the parameters of the attack are used to generate the ground truth against which the analysts' reports will be checked in \arch{4}. \subsubsection{Attack Injection (\arch{3})} \label{subsubsec:attack-scenario-injector} Attack simulations retrieved from \arch{2} are injected in the network traffic monitored by the \SOC{}. This can be either executed on the live infrastructure, or on a virtual \enquote{shadow network} separate from the operative environment. In the latter setting, the entire (virtual) network traffic is recorded and later forwarded to the Network Intrusion Detection sensors employed by the \SOC{}. The attack simulation can be merged seamlessly into (real-world) traffic streams either on a \SOC{} sensor or on network infrastructure devices (i.e., network switches or routers). To make simulations as realistic as possible, (optional) background traffic that was previously recorded on site can be mixed with the attack simulation. Attack simulations can be injected, recorded, and replayed at any point in time (i.e., record network traffic from virtual environment instead of passing to the \SOC{} immediately). The \SOC{} will then raise the respective events and alerts as if the injected traffic was real traffic to (or from) the monitored infrastructure. \paragraph{Impl. example:} In the example in \autoref{tab:example} traffic is recorded and replayed into a \SOC{} sensor as scheduled by executing the parametrized traces (e.g., \textit{exploit\_cve(cve,src\_ip,dst\_ip)}) (i.e., 12pm). The attack injection raises corresponding \SOC{} alerts, then evaluated by the analyst during incident identification and investigation. \subsubsection{Reporting (\arch{4})} \label{subsubsec:report-evaluator} The attack reports produced by \SOC{} analysts in response to the attack simulation are matched against the ground truth (obtained from \arch{2}) in \arch{4}. Because the exact details of the simulated attacks are known in advance, report(s) that mention specific details unique to the injected attack can be identified automatically. Using simple string matching and the knowledge-base of the SIEM, it is possible to check whether the final \SOC{} report details the incident events and sources correctly. \paragraph{Impl. example:} A \SOC{} analyst investigated the generated SOC alerts and reported the incident through a standardized template (e.g., \textit{src\_ip, cve}, \ldots). Comparing the analyst report with the ground truth may indicate that the current \SOC{} configuration lacks detection capabilities (e.g., undetected exploitation), or that raised alerts systematically misdirect the analyst (e.g., due to poorly defined threats or use cases). \section{Experimental validation} \label{sec:validationmethodology} Before presenting the \SAIBERSOC{} tool implementing the described architecture and solution, we validate the methodology behind it by testing it experimentally. To do so, we devise an experiment involving $n=124$ MSc students attending the 'Security in Organizations' course of a medium-sized European Technical University and an operative SOC infrastructure deployed at the Department level. \smallskip \textbf{Goal of the experiment}: \textit{to evaluate whether the proposed solution is capable of detecting (small) differences in SOC performance.} \smallskip Experimental subjects worked in groups of two and took the role of \textit{Tier 1} security analysts to investigate (injected) attacks. Subjects were randomly assigned to the experimental treatment (consisting in a small tweak in the SOC configuration) and asked to report the results of their analysis by filling in a report template. \subsection{Experimental infrastructure} The experiment is based on a real SOC used for research and education operating at the Mathematics and Computer Science department of the university. The SOC is operated over open-source technology and based on Security Onion\cite{onion} and Elastic Stack\cite{elastic} for event correlation and analysis. During regular operation the SOC monitors real incoming and outgoing network traffic in the department. The chosen network sensors (NIDS) are Suricata\cite{suricata} for security monitoring, and Bro/Zeek\cite{zeek} for network flow logs. The SOC is currently limited to the monitoring of network traffic and is operated with the involvement and cooperation of the security team of the university. \subsection{Experimental subjects} Subjects were recruited from a security in organization MSc course held at the university operating the SOC. The course is mandatory for all students graduating in the security track of the MSc program in Computer Science and open to students from others tracks (security=14; computer science=56; other=64; tot=124). Students were asked to form groups of two to participate in the experiment and were randomly assigned to the respective treatment groups (next subsection). The final size of the experiment pool is n=63; the term `experiment subject' in the remainder of the paper will refer to the student groups and not to the single students. \subsection{Experimental variables} \label{subsec:experimental-variables} \paragraph{Independent variable} To reproduce realistic SOC configurations we setup two analysis environments, namely \GOODSOC{} and \BADSOC{}. To test the effectiveness of the proposed solution, we introduce only a small change between the two configurations. To maintain the change realistic, we (1) define it around the university environment in which the SOC operates, and (2) base it only on the (de-)activation of a set of predefined rules that \textit{do not} match the use-cases of the university. \footnote{This setup has been checked against a set of use-cases provided by the university for SOC operation.} Namely, as the university is an open environment, default rulesets triggering alerts related to violation of generic policies such as use of TOR or p2p are out of the scope of the SOC. We therefore define the following two experimental conditions: \smallskip \noindent\textbf{\BADSOC{}}: baseline SOC configuration consisting of the default set of rules defined by the detection software (Suricata);\\ \textbf{\GOODSOC{}}: baseline SOC configuration \textit{minus} alerts related to policy violation events. \smallskip \noindent In the \BADSOC{} configuration 19731 out of 27125 present Suricata~\cite{suricata} rules were active by default. By deactivating 2753 rules (14\%), 16978 active rules remain). The disabled rules\footnote{All rules prefixed with either \enquote{ET POLICY}, \enquote{ET INFO}, \enquote{ET CHAT}, \enquote{GPL CHAT}, \enquote{ET TOR}, or \enquote{SURICATA} were disabled (see \enquote{\href{https://gitlab.tue.nl/saibersoc/acsac2020-artifacts/-/blob/master/experiment/scripts/better-soc.sh}{\texttt{better-soc.sh}}} in the \href{https://gitlab.tue.nl/saibersoc/acsac2020-artifacts/}{artifact repository}).} inform about policy violations (including the use of chat/instant messaging software and usage of the TOR network\cite{tor}). \paragraph{Outcome variables} In output of the experiment we evaluate the accuracy of the assessments made by the experiment subjects. We collect analyst output through a survey compiled by all subjects at the end of the experiment. To evaluate the subject's output under different experimental conditions, we consider the following variables: (1) the total number of reports submitted by each group: these may be related to the real injected attacks, or to other suspicious events detected by the subjects; (2) the number of submitted reports dealing with one of the simulated attacks; (3) the correctness of the submitted reports when compared against the ground truth. \subsection{Expected outcome and evaluation criteria} If the proposed solution is effective in detecting changes in SOC performance triggered by (small) changes in the SOC configuration, we would expect that \GOODSOC{} (i.e., the configuration producing fewer alerts not related to the university's use cases), lead to more accurate reports when compared to \BADSOC{}. Reflecting normal SOC operation procedures~\cite{muniz2015security}, we split our evaluation over the analysis phases of \textit{Attack identification} and \textit{Attack investigation}. \smallskip \textbf{Outcome expectation.} As the modification between \BADSOC{} and \GOODSOC{} should only reduce the number of false alerts displayed to the analyst, leaving alerts relevant to an attack unaffected, we expect the \SAIBERSOC{} method to highlight that: \medskip \noindent (1) \GOODSOC{} outperforms \BADSOC{} for the \textit{attack identification} phase; \smallskip \noindent (2) no significant difference between \GOODSOC{} and \BADSOC{} emerges for the \textit{attack investigation} phase. \smallskip To evaluate the accuracy of the \textit{Attack identification}, we evaluate the number of correct entries reported by the subjects in relation to: IP(s) of the attacker, IP(s) of the victims. To evaluate the accuracy of \textit{Attack investigation}, we evaluate reported information on the reconnaissance, exploitation, and delivery and control activities (ref. \autoref{tab:phases}). As we are interested in testing the effectiveness of the proposed solution, we are not concerned with quantifying whether our \GOODSOC\ configuration is \textit{significantly better than} our \BADSOC\ configuration; differently, we are interested in evaluating whether the (albeit small) \textit{change in the \GOODSOC\ configuration can be spotted by the proposed experimental procedure} in terms of a difference in performance. To evaluate these differences, we employ a mix of non-parametric statistical tests including Fisher's Exact Test (for differences in counts across conditions), and Wilcoxon rank-sum tests (for differences in outcome distributions). The significance level is set at $\alpha=0.05$. \subsection{Experiment Preparation} This section details the experiment setup and preparation for the scenario injection, and the attack reporting. \smallskip \emph{Attack traces.} We use the previously identified attack phases in \autoref{tab:phases} for our proof-of-concept implementation, namely \textit{Reconnaissance}, \textit{Exploitation}, and \textit{Delivery} and \textit{Control} phases. For each of these phases we collect or reconstruct the respective network traces from public resources. For the \textit{Reconnaissance} phase we collect data using \texttt{nmap}\cite{nmap} scans against selected targets; in the \textit{Exploitation} phase we rely on PoC exploits and brute-force attacks available on public resources, such as ExploitDB\cite{exploitdb} and Metasploit\cite{metasploit}. \textit{Delivery} and \textit{Control} include the download of malicious software from both ExploitDB and suspect IP addresses, and communication with IPs known to be involved in botnet C2C infrastructures. \smallskip \emph{Attack generation.} Using the previously identified attack traces, we build two different attack scenarios; these attacks are built by assembling the previous network captures created and provided with consistency among individual actions by editing the IP addresses involved. Resulting attacks reproduce the \textit{modus operandi} implemented by two real-world attacks (namely, \textit{Mirai} and \textit{Exim}). \smallskip \textbf{Scenario 1: Mirai.} This scenario is inspired by the Mirai botnet\cite{mirai-botnet}. The attacker gains access by successfully guessing SSH credentials. In the end of the scenario, the victim scans the internal network. As this scenario employs blacklisted IP addresses and domain names related to the Mirai botnet, it raises multiple (high priority) alerts in the \SOC{}. \textbf{Scenario 2: Exim.} The second scenario is based on a remote code execution vulnerability in an Exim 4 SMTP mail server \cite{exim-cve}. This scenario raises exactly one (high priority) alert in our \SOC{}. \smallskip \autoref{tab:scenario_comparison} provides a comparison of the two scenarios across the attack phases defined by MITRE ATT\&CK framework, and which phases can be detected by our \SOC\ configuration. Note that the scenarios are unaffected by the \GOODSOC\ or \BADSOC\ configurations, as the \GOODSOC\ configuration only removes 'policy violation' rulesets that are not triggered by either scenario. Due to the higher number of alerts related to the \MIRAI{} attack than for \EXIM{}, we consider the latter to be a more advanced scenario than the former. \begin{table*}[t] \caption{Comparison between the injected attack scenarios \MIRAI{} and \EXIM{}} \label{tab:scenario_comparison} \begin{tabular}{p{0.14\textwidth}p{0.33\textwidth}c p{0.33\textwidth}c} \toprule & \multicolumn{2}{c}{Mirai} & \multicolumn{2}{c}{Exim} \\ \cmidrule(l){2-3}\cmidrule(l){4-5} \noindent\parbox[b]{\hsize}{Scenario phase} & Phase description & Alert & Phase description & Alert \\\midrule Reconnaissance\newline(port scan) & Comprehensive port scan; Multiple hosts, ports \& services scanned with aggressive techniques. & & Probing multiple hosts using a targeted port scan on port TCP/25. & \\ Exploitation\newline(Initial access) & Successful SSH password guessing and local file inclusion/upload through SSH. & & Attacker runs a known exploit against an SMTP server, triggering a red alert. & \checkmark \\ Delivery\newline(2nd stage) & Victim requests web page with suspicious data via HTTP. Bogus user agent triggers a red alert. & \checkmark & Visited a web page offering public exploits via HTTPS; Encrypted content not readable & \\ Control\newline(CnC DNS query) & Victim tries to resolve Mirai-related hostnames. Multiple red alerts are triggered. & \checkmark & Nothing - no DNS resolution. & \\ Control\newline(CnC comm.) & Victim sends suspicious UDP packets to an IP address known to be involved in CnC activities; triggers a red alert. & \checkmark & Victim sends suspicious UDP packet to a non-blacklisted IP address. & \\ Control\newline(Pivot port scan) & Comprehensive port scan; Multiple hosts, ports \& services scanned with aggressive techniques. & & Nothing - no further port scan. & \\ \bottomrule \end{tabular} \end{table*} \smallskip \emph{Attack injection.} The IP address of the attacker was rewritten to match the IP address defined in the scenarios. The attacks were injected in pre-recorded network traffic arriving at the \SOC\ during working hours. While we cannot guarantee the background traffic to be attack-free, we analyzed the most significant alerts observed in the traffic to ensure that generated alerts not related to the injected attacks are not symptomatic of known attacks. We found no evidence of ongoing attacks in the pre-recorded network traffic. \smallskip \emph{Attack report.} Due to infrastructural limitations, we collect reports using an online survey. \footnote{A \SOC{} would normally rely on an integrated case management system for incident reporting; this was not available in the employed \SOC{} setup.} Each group could report up to five\footnote{The limit of five activities was chosen after piloting. A discussion of implications on result validity is provided in \autoref{sec:limitations}.} suspicious activities detected during the experiment. \autoref{tab:questionnaire} provides an overview of the questions. The first two questions asked for the attacker and victim IP addresses; as multiple entities can be associated to a role for an attack, we allow to insert more than a single IP address. Further, multiple-choice questions address reconnaissance, vulnerability exploitation, the delivery and control phase of the attack. For each of the selected answers it is required to specify the IP address involved with the selected action. Lastly subjects could report additional free-text comments. The full survey is available in the Appendix. To evaluate whether a report is a response to one of the injected attack simulations, we compare the reported IP addresses to the ground-truth from the scenario definition. If the attacker \textit{and} victim IP addresses of a scenario were both mentioned in the respective field, we mark the report to be a response to one of the corresponding scenarios. \begin{table}[t] \centering \caption{Summary of information expected in a report} \label{tab:questionnaire} \Description{Asking for the attacker and victim IP addresses allows to frame the reported scenario, i.e., identify whether the report is in response to one of the injected scenarios or not. Questions about the reconnaissance phase, the exploitation phase, and the delivery and control phases allow to identify whether the respective phase was correctly identified by the SOC analyst. Lastly space for comments allows analysts to provide further information.} \begin{tabular}{p{0.3\linewidth} p{0.6\linewidth}} \toprule {Analysis param} & {Info provided for result evaluation} \\\midrule {Attacker IP} & Framing of the reported scenario \\ {Victim IP} & Framing of the reported scenario \\ {Reconnaissance} & Detection of reconnaissance actions \\ {Exploitation} & Detection of exploitation actions \\ {Delivery \& C\&C} & Detection of delivery \& C\&C \\ {Comments} & Space for further information \\ \bottomrule \end{tabular} \end{table} \smallskip \emph{Technical setup.} We deployed two instances of the SOC environment and setup each accordingly to the \GOODSOC{} and \BADSOC{} configurations (ref. \autoref{subsec:experimental-variables}). Each VM is powered by a machine with Intel(R) Xeon(R) Bronze 3104 CPU @ 1.70GHz with 12 cores and 64GB of RAM. During the experiment the two \SOC{} servers' sensors were isolated from the University's network. Students accessed their respective analysis environments from the classroom on their own PCs. \subsection{Experiment Pilot} Prior to execution we ran a set of pilots to refine the infrastructure and test the devised experimental procedures. A pilot phase was conducted to evaluate the survey procedure (incl. question phrasing) employed for the reporting phase. Further, the pilots were used to assess whether the difficulty of the assignment and the pre-experiment training sessions were a good match with students' skills. To this aim, we piloted the whole experiment four times, pooling for volunteers from students with a similar background to our subjects (e.g., enrolled in other security courses at the time, or PhD students in Computer Science). \subsection{Experimental Execution} Student autonomously created groups of two and each group was assigned randomly to the \BADSOC\ (n=31) or \GOODSOC\ (n=32) experimental conditions. Students were given half a bonus point valid for the final exam for attending the experiment and if they managed to correctly identify (at least one) attacker in the injected attacks. \begin{figure}[t] \centering \includegraphics[width=0.5\columnwidth]{img/timeline.png} \caption{Experiment phases and duration} \label{fig:exptimeline} \Description[A timeline describing the individual phases of the experiment session and their duration.]{The experiment session lasted 115 minutes. First: 25 minutes crash course on incident investigation and a (SOC) walk-trough. Then: 15 minutes warm-up exercise. Then: 10 minutes break. Then: 50 minutes exercise (main experiment). Then: 15 minutes questionnaire.} \end{figure} The experiment session started with an introduction and training session lasting approximately 30 minutes. After introducing the assignment, we ran a 15 minutes warm-up exercise where students had to identify a simple scenario with small network traffic to familiarize with the interface. The warm-up exercise was run on the \BADSOC\ configuration for all groups.\footnote{The warm-up exercise, albeit simpler and shorter than the actual exercise, follows the same structure as the subsequently injected attacks.} The experiment was run after the warm-up phase and lasted 50 minutes. Subjects were told that at least one attack would be injected but were unaware of attack type and timing. At the end of the experiment, traffic injection was terminated, and the survey used for report collection was made available. Students were asked to submit their reports within 15 minutes but retained access to \SOC{} and questionnaire until all submissions were collected. \autoref{fig:exptimeline} provides a visual representation of the experiment timeline. \subsection{Ethical and experimental considerations} \label{sec:limitations} The background noise traffic was captured from the \SOC\ operating at the M\&CS department of the host university under the ethical and organizational approval of the university. The traffic raw data was not accessible to the students during the experiment (i.e., they could only see the alerts generated based on the original traffic). The experiment was integrated in the practical educational activities run by the university and performed following guidelines approved by the university for exercises in classroom settings. \smallskip \emph{Experimental limitations.} \textbf{(a) Construct validity.} We implicitly assume that students who report the correct IP addresses for both attacker and victim detected the attack and started analyzing it. Using automated checking it is impossible for us to determine whether a group actually understood what happened. \textbf{(b) External validity.} Students do not have the same experience and training that \SOC{} analysts do and the training during the introduction section cannot make up for that. In real settings, the experiment should be replicated against multiple analysts and using a portfolio of attacks, as opposed to only one or two attack scenarios, to obtain ample validity across experimental conditions. \textbf{(c) Internal validity.} Students were told in advance that there would be at least one attack, creating an expectation to find something. Further, by allowing students to submit up to five incidents and not penalizing `false positive' reporting, our experiment may inflate the number of reports per group. As this limit is the same across all groups and treatments, we do not expect any effect on the likelihood that groups report the `real' injected incidents (i.e. our main experimental outcome). \section{Experimental Results} \label{sec:experimentresults} Whereas students could submit up to five reports, we expected exactly two reports detecting the injected attack scenarios \MIRAI{} and \EXIM{} respectively. \autoref{tab:expectations} reports the correct answers related to the \MIRAI\ and \EXIM\ scenarios. \begin{table}[t] \centering \caption{Expected findings/ground-truth for both scenarios} \label{tab:expectations} \Description{We expect reports in response to the Mirai attack to mention \MIRAIATTACKERIP{} as attacker IP address, \MIRAIVICTIMIP{} as victim IP address, 'port scan` as reconnaissance action, `weak credentials' as vulnerability or exploit used, and `data exfiltration' and `HTTP requests' as activities observed in the Delivery and Command and Control phase of the attack. In response to the Exim attack we expect reports to mention \EXIMATTACKERIP{} as attacker IP address, \EXIMVICTIMIP{} as victim IP address, 'port scan` as reconnaissance action, `remote code execution' as vulnerability or exploit used, and `data exfiltration' and `HTTP requests' as activities observed in the Delivery and Command and Control phase of the attack.} \begin{tabular}{p{0.26\columnwidth} p{0.30\columnwidth} p{0.30\columnwidth}} \toprule {Analysis param} & \MIRAI & \EXIM{} \\\midrule {Attacker IP } & \MIRAIATTACKERIP{} & \EXIMATTACKERIP{} \\ {Victim IP } & \BLINDED{\MIRAIVICTIMIP{}} & \BLINDED{\EXIMVICTIMIP{}} \\ {Reconnaissance} & port scan & port scan \\ {Exploit/Vuln.} & weak credentials & remote code exec. \\ {Delivery/C\&C} & \begin{tabular}[t]{@{}l@{}}data exfiltration\\ HTTP requests \end{tabular} & \begin{tabular}[t]{@{}l@{}}data exfiltration\\ HTTP requests\end{tabular}\\ \bottomrule \end{tabular} \end{table} \subsection{Attack identification} We received 63 submissions (one per group) reporting a total of 162 incidents. \autoref{fig:plot-submission-histogram} \begin{figure}[t] \centering \includegraphics[width=\linewidth,height=6cm,keepaspectratio]{plot_submission_histogram} \caption{Aggregation of groups by \# submitted reports} \label{fig:plot-submission-histogram} \Description{Participants were allowed to submit up to five potential attacks. In the BADSOC condition, 7 groups submitted one report, 13 groups submitted two reports, 9 groups submitted three reports, 2 groups submitted four reports, and 1 group submitted five reports. In the GOODSOC condition, 6 groups subitted one report, 5 groups ubsmitted two reports, 11 groups submitted three reports, 5 groups submitted four reports, and 4 groups submitted five reports.} \end{figure} reports overall submission rates for all groups in the \BADSOC{} ($m=2.28,\ sd=0.99$) and \GOODSOC{} ($m=2.9,\ sd=1.3$) configurations. Overall, the 32 groups working on \BADSOC{} submitted 73 reports, the 31 groups on \GOODSOC{} submitted 89 reports in total. A Wilcoxon Rank-Sum test results in \BADSOC{} producing significantly less reports than \GOODSOC{} ($p=0.02,\ W=353.5$). This suggests that groups assigned to the \GOODSOC{} condition were able to reconstruct more `suspicious' activities than groups assigned to \BADSOC{}, despite the events related to these activities being available to both treatment groups. Overall, $26\%$ of \BADSOC{} reports (19/73) and $33\%$ of \GOODSOC{} reports (29/89) detailed the injected attack scenarios (i.e., the majority of reports were \textit{not} about the injected attacks). As groups could report up to five incidents, this is unsurprising. To evaluate reporting in more detail, \autoref{fig:plot-group-report-count} \begin{figure}[t] \centering \includegraphics[width=\linewidth,height=6cm,keepaspectratio]{plot_group_report_count} \begin{minipage}{0.9\columnwidth} \footnotesize \smallskip Column \enquote{both} represents the number of groups that reported both scenarios (\MIRAI{} \emph{and} \EXIM{}), while \enquote{none} represents the number of groups that did not report any of the scenarios. \end{minipage} \caption{\textit{Attack identification} by reported scenario.} \label{fig:plot-group-report-count} \Description{In total, 32 groups operated in the BADSOC configuration, 31 groups in the GOODSOC condition. In BADSOC 14 (out of 32) groups did not report any attack, 10 reported the Mirai and 9 the Exim attack. Out of the 18 groups that found at least one attack, one reported both attacks. In GOODSOC 9 (out of 31) groups did not report any attack, 12 reported the Mirai and 17 the Exim attack. Out of the 22 groups that found at least one attack, 7 reported both attacks.} \end{figure} shows the distribution of reports on the injected scenarios. Overall, 57\% of groups in \BADSOC{} and 71\% of groups in \GOODSOC{} reported at least one of the injected attacks. Whereas no noticeable difference against \MIRAI{} reporting rates can be observed ($p=0.36,\ OR=1.38$), \GOODSOC{} groups were approximately three times more likely to report the \EXIM{} attack ($p=0.03,\ OR=3.04$) than the \BADSOC\ groups, and approximately eight times more likely to report both attacks ($p=0.02,\ OR=8.49$) overall. However, if one considers only groups that reported at least one of the attacks, the difference between \GOODSOC{} and \BADSOC{} decreases and becomes borderline significant ($p=0.09$,\ $OR=5.56$); this may suggest that, under our treatment conditions, groups that perform well and detect at least one attack are more likely to find both irrespective of the \SOC\ configuration. Similarly, \BADSOC\ groups seem overall more likely ($OR=1.88$) than \GOODSOC{} to \textit{not} report either of the attack scenarios, albeit the difference is not significant ($p=0.17$). These findings provide an initial indication that the proposed solution can be effectively employed to evaluate (relative) SOC performance across SOC configurations (e.g., before and after a major configuration change in a deployed \SOC{}). \subsection{Attack investigation} We now provide a breakdown over the \emph{reconnaissance}, \emph{exploitation}, and \emph{delivery \& control} attack phases across the two injected attack scenarios. Results are reported in \autoref{tab:content-result-table}. \input{content-result-table} \paragraph{Reconnaissance.} For both injected attacks, \enquote{port scan} was the correct answer, when asked for the observed reconnaissance activity in the questionnaire (see \autoref{tab:expectations}). For the \MIRAI{} attack, the correct answer was given by 70\% (7/10) groups operating on \BADSOC{} and 75\% (9/12) groups operating on \GOODSOC{} configuration ($p=0.58,\ OR=1.27$). The ratio of reports mentioning the portscan for the \EXIM{} attack is, overall, lower than for \MIRAI{}, albeit no significant difference emerges ($p=0.42,\ OR=2.39$): In \BADSOC{} 11.1\% (1/9) correct answers, in \GOODSOC{} 23.5\% (4/17). In conclusion, \GOODSOC{} did not perform significantly better than \BADSOC{} with in the detection of the portscan in none of the scenarios. \paragraph{Exploitation.} For exploitation activity, \autoref{tab:content-result-table} shows that barely half of the groups selected the correct answer \enquote{weak credentials} when asked to report the exploitation vector abused by the attacker in the \MIRAI{} attack, i.e. 50\% (5/10) in \BADSOC{} and 41.7\% (5/12) in \GOODSOC{}. For the \EXIM{} attack, \autoref{tab:content-result-table} shows that 88.9\% (8/9) of the groups in \BADSOC{} that reported the \EXIM{} attack also reported the correct vulnerability \enquote{remote code execution} abused by the attacker to gain foothold on the victim. In \GOODSOC{}, 82.4\% (14/17) answered correctly. On neither of the two injected attacks \GOODSOC{} performed better than groups working with the \BADSOC{} (\MIRAI{}: $p=0.79,\ OR=0.73$, \EXIM{}: $p=0.84,\ OR=0.59$). In fact, \BADSOC{} performed slightly better than \GOODSOC{} in identifying the correct exploitation vector (\MIRAI{}: $p=0.52,\ OR=1.38$, \EXIM{}: $p=0.57,\ OR=1.68$). Putting the differences between \BADSOC{} and \GOODSOC{} aside, all groups were more likely to identify the correct exploitation actions in \EXIM{} (85\%, or 22/26) than in the \MIRAI{} scenario (45\%, or 10/22). \paragraph{Delivery \& Control.} We expected groups to select two correct answers in a multiple-choice question about the delivery and control activities observed in context of an attack. The answers \enquote{data exfiltration} and \enquote{HTTP requests} are considered correct for both simulated attacks (see \autoref{tab:expectations}). Of the groups who reported on the \MIRAI{} attack, 66.6\% (8/12) using \GOODSOC{} and 60\% (6/10) of the groups using \BADSOC{} reported at least one of the two activities ($ p=0.55,\ OR=1.32 $). Looking at the \EXIM{} attack, 22\% (2/9) of the groups reporting the attack on \BADSOC{} and 18\% (3/17) on \GOODSOC{} also mentioned one correct delivery/control activity ($p=0.79,\ OR=0.76$). No group submitted both correct answers, regardless of their condition or reported attack. Again, there are no significant differences in performance between \BADSOC{} and \GOODSOC{}. In the \MIRAI{} scenario option \enquote{HTTP requests} was likely to be selected roughly four times more often ($p=0.099,\ OR=4.32$) by groups operating \GOODSOC{}. In the \BADSOC{} configuration 30\% (3/10) selected it, in \GOODSOC{} 67\% (8/12). Only three groups, all using \BADSOC{}, chose the correct answer \enquote{data exfiltration} when reporting the \MIRAI{} attack. For the \EXIM{} attack, most groups, 56\% (5/9) in \BADSOC{} and 71\% (12/17) in \GOODSOC{} \emph{wrongly} chose \enquote{none of them}. \section{Discussion of results and presentation of the \SAIBERSOC{} tool} \label{sec:discussion} \begin{figure*}[t] \centering \begin{annotatedFigure} {\includegraphics[width=1.0\textwidth]{img/saibersoc_browser.png}} \annotatedFigureBox{0.004,0.015}{0.298,0.750}{A}{0.004,0.015 \annotatedFigureBox{0.303,0.181}{0.995,0.750}{B}{0.303,0.181 \annotatedFigureBox{0.303,0.015}{0.995,0.168}{C}{0.303,0.015 \annotatedFigureBox{0.748,0.770}{0.934,0.850}{D}{0.748,0.770 \end{annotatedFigure} \begin{minipage}{0.95\textwidth} \footnotesize \smallskip The \emph{attack trace} library (\arch{1}) is depicted in (A). Attacks are \emph{generated} (\arch{2}) by adding attack traces to the timeline (B), optionally changing playback speed and IP address rewriting (C). The \emph{attack injection} (\arch{3}) is controlled using simple buttons. A red marker indicates the progress on the timeline (B). \end{minipage} \caption{Screenshot of the \SAIBERSOC{} web interface and relation to the relevant architectural components.} \label{fig:saibersoc-ui} \Description[A screenshot of the SAIBERSOC user interface.]{\SAIBERSOC{} allows to generate attacks based on attack traces and inject them into the network. The picture shows three different views: the attack-trace library, the view to generate a new experiment, and lastly a timeline view of an assembled attack that can be injected at a later point in time.} \end{figure*} The presented results indicate that the \SAIBERSOC{} methodology is capable of highlighting the modifications introduced between SOC configurations. In our experiment, the \GOODSOC{} configuration significantly increases the chances of a correct \textit{attack identification}; however, the \BADSOC{} vs \GOODSOC{} conditions do not significantly affect the chances of correctly investigating the attack across its phases, indicating that the change in configuration leaves \textit{attack investigation} capabilities unaffected. Overall, in our example application the \SAIBERSOC{} method indicates that the \GOODSOC\ configuration is preferable to the \BADSOC\ configuration as it significantly increases (up to threefold) the likelihood of identification of incidents. In particular, if \GOODSOC\ and \BADSOC\ were alternative environments tested in a SOC environment, using the \SAIBERSOC\ solution the SOC manager of that infrastructure could conclude that analysts working with the \GOODSOC{} configuration were more likely to find one or both of the attacks: analysts on \GOODSOC{} were three times more likely to find the (slightly harder to identify) \EXIM{} attack ($p=0.03,\ OR=3.04$) than analysts on \BADSOC. The method results indicate that analysts in the \BADSOC{} configuration are either overwhelmed by the number of alerts to investigate or require more time analyzing individual events and therefore had no time to analyze the second scenario. However, analysts working with \GOODSOC{} produced more false-positive reports, i.e., reports \emph{not} in response to one of the injected attacks. This may indicate that analysts working on \GOODSOC{} either spent less time per analysis and thus could write more reports in the same time, or that they are generally more likely to report false-positives. \footnote{This effect may be caused by our experiment design; students had the \textit{expectation} to find at least one attack and were rewarded on finding at least one of the injected attacks, which may lead to over-reporting.} By contrast, no significant differences between \BADSOC{} and \GOODSOC{} can be observed in the \textit{attack investigation} phase. This provides additional information on the SOC performance related to which aspects of an incident investigations are (positively or negatively) affected by the different configurations under test. The ability to quantify these effects experimentally allows both researchers and practitioners in making informed decisions on technological and process-level solutions for security monitoring application. \smallskip \emph{Implications for research.} The \SAIBERSOC{} method can be used to evaluate the effect on security analysis of virtually any live analysis setting (such as a SOC or other security monitoring or analysis environments), either technical, procedural, or human. For example, \SAIBERSOC{} can be employed to evaluate the impact of factors such as the analysts' experience, skill composition, and training, or the effect of analysis and visualization tools by comparing the performance of two \SOC{} configurations with a known set of selected differences. Similarly, the proposed method can be employed to evaluate multiple performance variables, including timing (e.g., total time for alert investigation) and throughput measures~\cite{shah2018methodology}), and how these vary across different phases of the attack. The extensibility of the proposed method further opens the door to the investigation of more complex effects, such as the relation between attack types and analyst skills/expertise~\cite{emse-20}, which are still under-researched in the scientific literature. The \SAIBERSOC{} implementation presented further down in this section provides a practical tool to deploy experiments based on the propose method in live or laboratory environments. \smallskip \emph{Implications for practice.} The \SAIBERSOC{} methodology (and tool) is fully flexible in terms of attack procedure, traces, and outcome variables, and can be implemented in operational \SOC{}s to evaluate the relative performance of their configuration over the desired metrics. This includes both technical (e.g., rulesets, use-cases, alert correlation rules) and human-level (e.g., analysis processes, analyst expertise, flat vs. hierarchical reporting structures) aspects of SOC operation, both of central importance for effective incident detection and reporting~\cite{kokulu2019matched,muniz2015security}. Examples of concrete use-cases are comparison of \SOC{} performance before and after changes in \SOC{} configuration, or continuous monitoring of \SOC{} performance. Further, the proposed solution can be integrated in analyst training procedures, or as part of a selection procedure for security professional roles. \subsection{\SAIBERSOC\ tool implementation} \label{subsec:saibersoc-tool} To operationalize the \SAIBERSOC{} methodology, after its validation, we developed the \SAIBERSOC{} tool as an open source software solution. \SAIBERSOC{} implements all four architectural components outlined in \autoref{subsec:architecture}. It is deployed with a web-based front-end (depicted in \autoref{fig:saibersoc-ui}) interacting with a backend. A comprehensive API enables scripted access to all backend functionalities. \emph{Functionalities and User Interface.} \autoref{fig:saibersoc-ui} shows the deployed web interface and how architectural components (see \autoref{subsec:architecture}) \arch{1}\ldots\arch{3} are implemented in the web interface; report evaluation (\arch{4}) is not yet accessible through the frontend. On the left side of the screen, UX element \encircle{A} provides access to the attack \emph{trace library} (\arch{1}) showing previously uploaded network traffic recordings. A user can manually add traces onto a timeline \encircle{B} in the center of the screen. Convenience features allow to search a specific attack trace in the library or select a random one. From the timeline \encircle{B}, the offset and playback speed can be adjusted for each attack trace individually. In the lower section of the screen, \encircle{C} provides additional configuration options for the selected attack trace. Here, IP addresses and whole IP address ranges can be rewritten to create a realistic attack scenario for the monitoring environment. Buttons \encircle{D}, in the upper right area, provide functionalities to load and save experiments/attacks and to start, stop, or schedule their injections (\arch{3}). During attack injection (\arch{3}), state and progress is visualized on the timeline \encircle{B} using a vertical red line as progress indicator. The tool is capable of automatically extracting a ground-truth based on the metadata from the attack trace library (\arch{1}) and the optional IP address rewrites in \arch{2}. A \SOC{} report, allegorized by a \texttt{csv} file, can be checked against the ground-truth derived from the attack traces (\arch{4}). \emph{Tool implementation and API.} The \SAIBERSOC{} web application is implemented in \texttt{Python}. The (HTTP) API is based on \texttt{Flask}\cite{flask} and the \texttt{Flask-RESTX} framework\cite{flask-restx}. The web-frontend is built on top of the API using \texttt{vue.js}\cite{vuejs}. \noindent\textbf{Attack Traces~(\arch{1})}: The attack trace library consists of attack traces in form of \texttt{pcap} network traffic recordings linked to metadata stored in an internal database. \\\noindent\textbf{Attack Generation~(\arch{2})}: Internally, \SAIBERSOC{} uses a list of \emph{blocks} to specify an attack. Each \emph{block} consists of an attack trace (taken from the attack trace library) and additional information specifying time offset, playback speed, and IP address rewriting. Once an attack is fully sketched out, \texttt{scapy}\cite{scapy} is used to assemble a single intermediate attack \texttt{pcap}. \\\noindent\textbf{Attack Injection~(\arch{3})}: \SAIBERSOC{} invokes \texttt{tcpreplay}\cite{tcpreplay} to inject the \enquote{intermediate attack \texttt{pcap}} on a network interface. Optionally, background noise can be replayed together with the attack. \\\noindent\textbf{Reporting~(\arch{4})}: The reporting module extracts and combines the IP address rewriting from \arch{2} and attack trace metadata from \arch{1} as ground-truth. It then compares selected columns from an uploaded \texttt{csv} file against the extracted ground truth. \emph{Publication, Development, and Licensing} The development of \SAIBERSOC{} was supported by a team of BSc students as part of their final graduation project. The \SAIBERSOC{} tool is released under Mozilla Public License (MPL 2.0). Source code, extensive documentation, and supplementary materials are available from the artifact repository at \url{https://gitlab.tue.nl/saibersoc/acsac2020-artifacts}.% \section{Conclusion} \label{sec:conclusion} In this paper, we proposed a methodology based on attack injection to systematically measure \SOC{} performance across SOC configurations, analyst expertise, and for any output metric (e.g., accuracy, time-to-report, \ldots). We verified the proposed methodology by conducting an experiment in which 124 students assumed the role of a \SOC{} analysts. Our results show that the proposed methodology is capable of systematically measuring \SOC{} performance and attributing it to differences in configuration, where some is to be expected. Our solution is general and can be implemented in any SOC. In addition, we developed the \SAIBERSOC{} tool to help replicate the experiments and facilitate SOC exercises.
{'timestamp': '2020-10-19T02:19:39', 'yymm': '2010', 'arxiv_id': '2010.08453', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08453'}
arxiv
\section{Introduction} Deep learning methodology has revealed some striking deficiencies of classical statistical learning theory: large neural networks, trained to zero empirical risk on noisy training data, have good predictive accuracy on independent test data. These methods are overfitting (that is, fitting to the training data better than the noise should allow), but the overfitting is benign (that is, prediction performance is good). It is an important open problem to understand why this is possible. The presence of noise is key to why the success of interpolating algorithms is mysterious. Generalization of algorithms that produce a perfect fit in the absence of noise has been studied for decades (see~\citep{haussler1992} and its references). A number of recent papers have provided generalization bounds for interpolating algorithms in the absence of noise, either for deep networks or in abstract frameworks motivated by deep networks~\citep{ll-lonnsgdsd-18,arora2019fine,cao2019generalization,feldman2020does}. The generalization bounds in these papers either do not hold or become vacuous in the presence of noise: Assumption A1 in~\citep{ll-lonnsgdsd-18} rules out noisy data; the data-dependent bound in~\citet[Theorem~5.1]{arora2019fine} becomes vacuous when independent noise is added to the $y_i$; adding a constant level of independent noise to the $y_i$ in~\citep[Theorem~3.3]{cao2019generalization} gives an upper bound on excess risk that is at least a constant; and the analysis in~\citep{feldman2020does} concerns the noise-free case. There has also been progress on bounding the gap between average loss on the training set and expected loss on independent test data, based on uniform convergence arguments that bound the complexity of classes of real-valued functions computed by deep networks. For instance, the results in~\citep{b-scpcnn-98} for sigmoid nonlinearities rely on $\ell_1$-norm bounds on parameters throughout the network, and those in~\citep{bft-snmbnn-17} for ReLUs rely on spectral norm bounds of the weight matrices throughout the network (see also the refinements in~\citep{bm-rgcrbsr-02,nts-nbccnn-15,bft-snmbnn-17,% grs-siscnn-18,long2019size}. These bounds involve distribution-dependent function classes, since they depend on some measure of the complexity of the output model that may be expected to be small for natural training data. For instance, if some training method gives weight matrices that all have small spectral norm, the bound in~\citep{bft-snmbnn-17} will imply that the gap between empirical risk and predictive accuracy will be small. But while it is possible for these bounds to be small for networks that trade off fit to the data with complexity in some way, it is not clear that a network that interpolates noisy data could ever have small values of these complexity measures. This raises the question: are there any good data-dependent bounds for interpolating networks? \citet{zbhrv-udlrrg-17} claimed, based on empirical evidence, that conventional learning theoretic tools are useless for deep networks, but they considered the case of a fixed class of functions defined, for example, as the set of functions that can be computed by a neural network, or that can be reached by stochastic gradient descent with some training data, no matter how unlikely. These observations illustrate the need to consider distribution-dependent notions of complexity in understanding the generalization performance of deep networks. The study of such distribution-dependent complexity notions has a long history in nonparametric statistics, where it is central to the problem of model selection~\citep[see, for example,][and its references]{bartlett2002model}; uniform convergence analysis over a level in a complexity hierarchy is part of a standard outline for analyzing model selection methods. \citet{DBLP:conf/nips/NagarajanK19} provided an example of a scenario where, with high probability, an algorithm generalizes well, but two-sided uniform convergence fails for any hypothesis space that is likely to contain the algorithm's output. Their analysis takes an important step in allowing distribution-dependent notions of complexity, but only rules out the application of a specific set of tools: uniform convergence over a model class of the absolute differences between expectations and sample averages. Indeed, in their proof, the failure is an under-estimation of the accuracy of a model---a model has good predictive accuracy, but performs poorly on a sample (one obtained as a transformed but equally likely version of the sample that was used to train the model). However, in applying uniform convergence tools to show good performance of an algorithm, uniform bounds are only needed to show that bad models are unlikely to perform well on the training data. So if one wishes to provide bounds that guarantee that an algorithm has {\em poor} predictive accuracy, \citet{DBLP:conf/nips/NagarajanK19} provided an example where uniform convergence tools will not suffice. In contrast, we are concerned with understanding what tools can provide guarantees of {\em good} predictive accuracy of interpolating algorithms. In this paper, motivated by the phenomenon of benign overfitting in deep networks, we consider a simpler setting where the phenomenon occurs, that of linear regression. (Lemma 5.2 of~\citep{NDR20} adapts the construction of \citep{DBLP:conf/nips/NagarajanK19} to show a similar failure of uniform convergence in this context, and similarly cannot shed light on tools that can or cannot guarantee good predictive accuracy.) We study the minimum norm linear interpolant. Earlier work~\citep{bartlett2019benign} provides tight upper and lower bounds on the excess risk of this interpolating prediction rule under suitable conditions on the probability distribution generating the data, showing that benign overfitting depends on the pattern of eigenvalues of the population covariance (and there is already a rich literature on related questions~\citep{lr-jikrrcg-18,BRT19,BHMM19,hastie2019surprises,hmrt-shdrlsi-19,NDR20,derezinski2019exact,li2020benign,tsigler2020benign}). These risk bounds involve fine-grained properties of the distribution. Is this knowledge necessary? Is it instead possible to obtain data-dependent bounds for interpolating prediction rules? Already the proof in~\citep{bartlett2019benign} provides some clues that this might be difficult: when benign overfitting occurs, the eigenvalues of the empirical covariance are a very poor estimate of the true covariance eigenvalues---all but a small fraction (the largest eigenvalues) are within a constant factor of each other. In this paper, we show that in these settings there cannot be good risk bounds based on data-dependent function classes in a strong sense: For linear regression with the minimum norm prediction rule, any ``bounded-antimonotonic'' model-dependent error bound that is valid for a sufficiently broad set of probability distributions must be loose---too large by an additive constant---for some (rather innocuous) probability distribution. The bounded-antimonotonic condition formalizes the mild requirement that the bound does not degrade very rapidly with additional data. Aside from this constraint, our result applies for any bound that is determined as a function of the output of the learning algorithm, the number of training examples, and the confidence parameter. This function could depend on the level in a hierarchy of models where the output of the algorithm lies. Our result applies whether the bound is obtained by uniform convergence over a level in the hierarchy, or in some other way. The intuition behind our result is that benign overfitting can only occur when the test distribution has a vanishing overlap with the training data. Indeed, interpolating the data in the training sample guarantees that the conditional expectation of the prediction rule's loss on the training points that occur once must be at least the noise level. Using a Poissonization method, we show that a situation where the training sample forms a significant fraction of the support of the distribution is essentially indistinguishable from a benign overfitting situation where the training sample has measure zero. Since we want a data-dependent bound to be valid in both cases, it must be loose in the second case. \section{Preliminaries and main results} We consider prediction problems with patterns $x\in\ell_2$ and labels $y\in{\mathbb R}$, where $\ell_2$ is the space of square summable sequences of real numbers. In fact, all probability distributions that we consider have support restricted to a finite dimensional subspace of $\ell_2$, which we identify with ${\mathbb R}^d$ for an appropriate $d$. For a joint distribution $P$ over ${\mathbb R}^d \times {\mathbb R}$ and a hypothesis $h : {\mathbb R}^d \rightarrow {\mathbb R}$, define the {\em risk} of $h$ to be \[ R_P(h) = {\bf E}_{(x,y) \sim P} [ (y - h(x))^2]. \] Let $R_P^*$ be the minimum of $R_P$ over measurable functions. For any positive integer $k$, a distribution $D$ over ${\mathbb R}^k$ is sub-Gaussian with parameter $\sigma$ if, for any $u \in {\mathbb R}^k$, ${\bf E}_{x \sim D}[ \exp( u \cdot (x-{\bf E} x)) ] \leq \exp\left( \frac{ \| u \|^2 \sigma^2}{2} \right)$. A joint distribution $P$ over ${\mathbb R}^d \times {\mathbb R}$ has {\em unit scale} if $(X_1,...,X_d,Y) \sim P$ is sub-Gaussian with parameter $1$. It is {\em innocuous} if \begin{itemize} \item it is unit scale, \item the marginal on $(X_1,...,X_d)$ is Gaussian, and \item the conditional of $Y$ given $(X_1,...,X_d)$ is continuous. \end{itemize} A {\em sample} is a finite multiset of elements of ${\mathbb R}^d \times {\mathbb R}$. A {\em least-norm interpolation algorithm} takes as input a sample, and outputs $\theta \in {\mathbb R}^d$ that minimizes $\| \theta \|$ subject to \[ \sum_i (\theta \cdot {\bf x}_i - y_i)^2 = \min_{\hat{y}_1,...,\hat{y}_n} \sum_i (\hat{y}_i - y_i)^2. \] We will refer both to the parameter vector $\theta$ output by the least-norm interpolation algorithm and the function $x \rightarrow \theta \cdot x$ parameterized by $\theta$ as the {\em least-norm interpolant}. A function $\epsilon(h,n,\delta)$ mapping a hypothesis $h$, a sample size $n$ and a confidence $\delta$ to a positive real number is a {\em uniform model-dependent bound for unit-scale distributions} if, for all unit-scale joint distributions $P$ and all sample sizes $n$, with probability at least $1-\delta$ over the random choice of $S \sim P^n$, we have \[ R_P(h) - R_P^* \leq \epsilon(h,n,\delta). \] The bound $\epsilon$ is {\em $c$-bounded antimonotonic} for $c\ge 1$ if for all $h$, $\delta$, $n_1$ and $n_2$, if $n_2/2\le n_1\le n_2$ then $\epsilon(h,n_2,\delta) \le c\epsilon(h,n_1,\delta)$. This requires that the bound cannot get too much worse too quickly with more data. If $\epsilon(h,\cdot,\delta)$ is monotone-decreasing for all $h$ and $\delta$, then it is $1$-bounded antimonotonic. A set ${\cal B} \subseteq {\mathbb N}$ is {\em $\beta$-dense} if $\mathrm{liminf}_{N \rightarrow \infty} \frac{ |{\cal B} \cap \{ 1,...,N \}| }{N} \geq \beta. $ Say that ${\cal B} \subseteq {\mathbb N}$ is {\em strongly $\beta$-dense beyond $n_0$} if, for all $s \in {\mathbb N}$ such that $s^2 \geq n_0$, \[ \frac{ |{\cal B} \cap \{ s^2,...,(s+1)^2 - 1 \}| }{2 s + 1} \geq \beta. \] (Notice that if a set is strongly $\beta$-dense beyond $n_0$, then it is $\beta$-dense.) The following is our main result. \begin{theorem} \label{t:main} If $\epsilon$ is a bounded-antimonotonic, uniform model-dependent bound for unit-scale distributions, then there are constants $c_0,c_1,c_2,c_3,c_4 > 0$ and innocuous distributions $P_{1}, P_{2},\ldots$, such that for all $0 < \delta < c_1$, the least-norm interpolant $h$ satisfies, for all large enough $n$, \[ \Pr_{S\sim P_n^n} \left[ R_{P_n}(h) - R_{P_n}^* \leq c_0/\sqrt{n} \right]\ge 1-\delta \] but nonetheless, the set of $n$ such that \[ \Pr_{S\sim P_n^n} \left[\epsilon(h,n,\delta) > c_2\right] \geq \frac{1}{2} \] is strongly $(1 - \frac{c_3}{\log(1/\delta)})$-dense beyond $c_4\log(1/\delta)$. \end{theorem} \section{Proof of Theorem~\protect\ref{t:main}} Our proof uses the following lemma~\citep{birch1963maximum} (see also~\citep[p. 216]{feller} and~\citep{batu2000testing,DBLP:journals/jacm/BatuFRSW13}), which has become known as the ``Poissonization lemma''. We use $\mathrm{Poi}(\lambda)$ to denote the Poisson distribution with mean $\lambda$: For $t\sim\mathrm{Poi}(\lambda)$ and $k\ge 0$, \[ \Pr[t=k] = \frac{\lambda^k e^{-\lambda}}{k!}. \] \begin{lemma} \label{l:poissonization} If, for $t \sim \mathrm{Poi}(n)$, you throw $t$ balls independently uniformly at random into $m$ bins, \begin{itemize} \item the numbers of balls falling into the bins are mutually independent, and \item the number of balls falling in each bin is distributed as $\mathrm{Poi}(n/m)$. \end{itemize} \end{lemma} For each $n$, our proof uses three distributions: $D_n$, $Q_n$ and $P_n$. The first, $D_n$, is used to define $Q_n$ and $P_n$; it is chosen so that the least-norm interpolant performs well on $D_n$. The distribution $Q_n$ is defined so that the least-norm interpolant performs poorly on $Q_n$. The distribution $P_n$ is defined so that, when the least-norm interpolant performs well on $D_n$, it also performs well on $P_n$. Crucially, the least norm interpolants that arise from $Q_n$ and $P_n$ are closely related. For each $n$, the joint distribution $D_n$ on $(x,y)$-pairs is defined as follows. Let $s = \floor{\sqrt{n}}$, $N = s^2$, $d = N^2$. Let $\theta^*$ be an arbitrary unit-length vector. Let $\Sigma_s$ be an arbitrary covariance matrix with eigenvalues $\lambda_1=1/81,\lambda_2=\cdots=\lambda_d=1/d^2$. The marginal of $D_n$ on $x$ is then ${\cal N}(0, \Sigma_s)$. For each $x \in {\mathbb R}^d$, the distribution of $y$ given $x$ is ${\cal N}\left(\theta^* \cdot x,\frac{1}{81}\right)$. For $d\ge 9$, since $(x,y)$ is Gaussian, $\| \Sigma_s \| \leq 1/81$, and the variance of $y$ is $1/81$, each $D_n$ is innocuous. For an absolute constant positive integer $b$, we get $Q_n$ from $D_n$ through the following steps. \begin{enumerate} \item Sample $(x_1,y_1),\ldots,(x_{bn},y_{bn})\sim D_n^{b n}$. \item Define $Q_n$ on ${\mathbb R}^d \times {\mathbb R}$ so that its marginal on ${\mathbb R}^d$ is uniform on $U = \{x_1,\ldots,x_{bn}\}$ and its conditional distribution of $Y|X$ is the same as $D_n$. \end{enumerate} \begin{definition} For a sample $S$, the {\em compression} of $S$, denoted by $C(S)$, is defined to be \[ C(S) = \left((u_1,v_1),\ldots,(u_k,v_k)\right), \] where $u_1,\ldots,u_k$ are the unique elements of $\{x_1,\ldots,x_n\}$, and, for each $i$, $v_i$ is the average of $\{ y_j : 1\le j \le n,\, x_j = u_i \}$. \end{definition} For the least-norm interpolation algorithm $A$, for any pair $S$ and $S'$ of samples such that $C(S) = C(S')$, we have $A(S) = A(S')$. (This is true because the least-norm interpolant $A(S)$ is uniquely defined by the equality constraints specified by the compression $C(S)$.) So that a generalization bound often must apply to $Q_n$, we need to show that it is likely to be unit scale. The proof of this lemma is in Appendix~\ref{a:unit}. \begin{lemma} \label{l:unit} There is a positive constant $c_5$ such that, for all large enough $n$, with probability $1 - \frac{c_5}{n}$, $Q_n$ has unit scale. \end{lemma} We can show that the least-norm interpolant is bad for $Q_n$ by only considering the points in the support of $Q_n$ that the algorithm sees exactly once. \begin{lemma}\label{lemma:Qbad.poisson} For any constant $c > 0$, there are constants $c_6, c_7 > 0$ such that, for all sufficiently large $n$, almost surely for $Q_n$ chosen randomly as described above, if $t$ is chosen randomly according to $\mathrm{Poi}(c n)$ and $S$ consists of $t$ random draws from $Q_n$, then with probability at least $1 - e^{-c_6 n}$ over $t$ and $S$, \[ {\bf E}_{(x,y) \sim Q_n}\left[(A(C(S))(x)-y)^2\right] - {\bf E}_{(x,y) \sim Q_n}\left[(f^*(X)-Y)^2\right] \ge c_7 \] where $f^*$ is the regression function for $D_n$ (and hence also for $Q_n$). \end{lemma} \begin{proof} Recall that $U=\{x_1,\ldots,x_{bn}\}$ is the support of the marginal of $Q_n$ on the independent variables. With probability $1$, $U$ has cardinality $b n$. Define $h = A(C(S))$. If some $x\in U$ appears exactly once in $S$, then $h(x)$ is a sample from the distribution of $y$ given $x$ under $D_n$. Thus, for such an $x$, the expected quadratic loss of $h(x)$ on a test point is the squared difference between two independent samples from this distribution, which is twice its variance, i.e.\ twice the expected loss of $f^*$, which is $2 \times 1/2 = 1$. On any $x\in U$, whether or not it was seen exactly once in $S$, by definition, $f^*(x)$ minimizes the expected loss given $x$. Lemma~\ref{l:poissonization} shows that, conditioned on the random choice of $Q_n$, the numbers of times the various $x$ in $U$ in $S$ are mutually independent and, the probability that $x \in U$ is seen exactly once in $S$ is $\frac{c}{b} \exp\left(-\frac{c}{b}\right) \geq \frac{c e^{-c}}{b}$. Applying a Chernoff bound (see, for example, Theorem 4.5 in~\cite{MU}), the probability that fewer than $ce^{-c}n/2$ members of $U$ are seen exactly once in $S$ is at most $e^{-c_6 n}$ for an absolute constant $c_6$. Thus if $U_1$ is the (random) subset of points in $U$ that were seen exactly once, we have \begin{align*} & Q_n\left[(h(X)-Y)^2\right] - Q_n\left[(f^*(X)-Y)^2\right] \\ & = \sum_{x \in U} Q_n\left[((h(X)-Y)^2 - (f^*(X)-Y)^2) 1_{X = x}\right] \\ & \geq \sum_{x \in U_1} {\bf E}[ (f^*(X)-Y)^2 1_{X = x} ] \\ & = \frac{|U_1|}{bn}. \end{align*} Since, with probability $1 - e^{- c_6 n}$, $|U_1| \geq ce^{-c}n/2$, this completes the proof. \end{proof} \begin{definition} \label{e:good.same_marginal} Define $P_n$ as follows. \begin{enumerate} \item Set the marginal distribution of $P_n$ on ${\mathbb R}^d$ the same as that of $D_n$. \item To generate $Y$ given $X=x$ for $(X,Y) \sim P_n$, first sample a random variable $Z$ whose distribution is obtained by conditioning a draw from a Poisson with mean $\frac{c}{b}$ on the event that it is at least $1$, then sample $Z$ values $V_1,\ldots,V_{Z}$ from the conditional distribution $D_n(Y|X=x)$, and set $ Y = \frac{1}{Z} \sum_{i=1}^Z V_j. $ \end{enumerate} \end{definition} Note that, since $D_n$ has a density, $x_1,...,x_r$ are almost surely distinct and hence $S$ drawn from $P_n^r$ has $C(S)=S$ a.s. The following lemma implies that the bounds for $P_n$ tend to be as big as those for $Q_n$. \begin{lemma} \label{l:easy.by.hard} Define $Q_n$ as above let ${\cal Q}_n$ be the resulting distribution over the random choice of $Q_n$. Suppose $P_n$ is defined as in Definition~\ref{e:good.same_marginal}. Let $c > 0$ be an arbitrary constant. Choose $S$ randomly by choosing $t \sim \mathrm{Poi}(c n)$, $Q_n\sim{\cal Q}_n$ and $S\sim Q_n^t$. Choose $T$ by choosing $r \sim B\left(bn, 1 - \exp\left(-\frac{c}{b}\right)\right)$ and $T\sim P_n^r$. Then $C(S)$ and $T$ have the same distribution. In particular, for all $\delta > 0$, for any function $\psi$ of the least norm interpolant $h$, a sample size $r$, and a confidence parameter $\delta$, we have \[ {\bf E}_{t \sim \mathrm{Poi}(c n),Q_n \sim {\cal Q}_n} [{\bf E}_{S \sim Q_n^t} [\psi(h(S),|C(S)|,\delta)]] = {\bf E}_{r \sim B\left(bn, 1 - \exp\left(-\frac{c}{b}\right)\right)} [{\bf E}_{T \sim P_n^r} [\psi(h(T),r,\delta)]. \] \end{lemma} \begin{proof} Let ${\cal C}$ be the probability distribution over training sets obtained by picking $Q_n$ from ${\cal Q}_n$, picking $t$ from $\mathrm{Poi}(cn)$, picking $S$ from $Q_n^t$ and compressing it. Let $C = C(S)$ be a random draw from ${\cal C}$. Let $n_C$ be the number of examples in $C$. We claim that $n_C$ is distributed as $B\left(bn, 1 - \exp\left(-\frac{c}{b}\right)\right)$. Conditioned on $Q_n$, and recalling that $U$ is the support of $Q_n$, for any $x \in U$, Lemma~\ref{l:poissonization} implies that for each $x \in U$, the probability that $x$ is not seen is the probability, under a Poisson with mean $\frac{c}{b}$, of drawing a $0$. Thus, the probability that $x$ is seen is $1 - \exp\left(-\frac{c}{b}\right)$. Since the numbers of times different $x$ are seen in $S$ are independent, the number seen is distributed as $B\left(bn, 1 - \exp\left(-\frac{c}{b}\right)\right)$. Now, for each $x \in U$, the event that it is in $C(S)$ is the same as the event that at appears at least once in $S$. Thus, conditioned on the event that $x$ appears in $S$, the number of $y$ values that are used to compute the $y$ value in $C(S)$ is distributed as a Poisson with mean $\frac{c}{b}$, conditioned on having a value at least $1$. Let $D_{n,X}$ be the marginal distribution of $D_n$ on the $x$'s. If we make $n$ independent draws from $D_{n,X}$, and then independently reject some of these examples, to get $n_C$ draws, the resulting $n_C$ examples are independent. (We could first randomly decide the number $n_C$ of examples to keep, and then draw those independently from $D_n$, and we would have the same distribution.) The last two paragraphs together, along with the definition of $Q_n$, imply that the distribution over $T$ obtained by sampling $r$ from $B(bn, 1 - e^{-c/b})$ and $T$ from $P_n^r$ is the same as the distribution over $C$ obtained by sampling $Q_n$ from ${\cal Q}_n$, $t$ from $\mathrm{Poi}(cn)$, then sampling $S$ from $Q_n^t$ and compressing it. Thus, the distributions of $T$ and $C(S)$ are the same, and hence the distributions of $(h(T),|T|)$ and $(h(S),|C(S)|)$ are the same, because $h(S)=h(C(S))$. \end{proof} We will use the following bound on a tail of the Poisson distribution. \begin{lemma}[\citep{canonne2017short}] \label{l:poisson.tail} For any $\lambda,\alpha>0$, $\Pr_{r \sim \mathrm{Poi}(\lambda)} (r \geq (1+\alpha)\lambda) \leq \exp \left(-\frac{\alpha^2}{2(1+\alpha)}\lambda\right)$. \end{lemma} Armed with these tools, we now show that $\epsilon$ must often have a large value. \begin{lemma} \label{l:bound_big} Then there are positive constants $c_1,c_2,c_3,c_4$ such that, for all $0 < \delta < c_1$, the set of $n$ such that \[ \Pr_{S\sim P_n^n} \left[\epsilon(h,n,\delta) > c_2\right] \geq \frac{1}{2} \] is strongly $(1 - \frac{c_3}{\log(1/\delta)})$-dense beyond $c_4\log(1/\delta)$. \end{lemma} \begin{proof} We will think of the natural numbers as being divided into bins $[1,2),[2,4), [4,7),...$ Let us focus our attention on one bin: $\{ s^2, ..., (s+1)^2 - 1 \}$. Let $n$ denote the center of the bin, $n = s^2 + s$, so that $s \sim \sqrt{n}$. For a constant $c_8 > 0$ and any $\delta > 0$, Lemma~\ref{l:easy.by.hard} implies \begin{equation} \label{e:easy.by.hard} {\bf E}_{r \sim B(bn, 1 - e^{-c/b})} [ \Pr_{T \sim P_n^r} [ \epsilon(h(T),r,\delta) \leq c_8 ]] = {\bf E}_{t \sim \mathrm{Poi}(c n),Q_n \sim {\cal Q}_n} [\Pr_{S \sim Q_n^t} [\epsilon(h(S),|C(S)|,\delta) \leq c_8]]. \end{equation} Suppose that $\epsilon$ is $B'$-bounded-antimonotonic. Fix $B>0$ such that $B>B'$. Then \begin{align} \nonumber & {\bf E}_{t \sim \mathrm{Poi}(c n),Q_n \sim {\cal Q}_n} [ \Pr_{S \sim Q_n^t} [\epsilon(h,|C(S)|,\delta) \leq c_8]] \\ \nonumber & = {\bf E}_{t \sim \mathrm{Poi}(c n),Q_n \sim {\cal Q}_n} [ \Pr_{S \sim Q_n^t} [B\epsilon(h,|C(S)|,\delta) \leq c_8B]] \\ \nonumber & \leq {\bf E}_{t \sim \mathrm{Poi}(c n),Q_n \sim {\cal Q}_n} [\Pr_{S \sim Q_n^t} [R_{Q_n}(h) - R_{Q_n}^* > B\epsilon(h,|C(S)|,\delta)]] \\ \label{e:by.regrets} & \hspace{1.0in} + {\bf E}_{t \sim \mathrm{Poi}(c n),Q_n \sim {\cal Q}_n} [ \Pr_{S \sim Q_n^t} [ R_{Q_n}(h) - R_{Q_n}^* \leq c_8B ]]. \end{align} For each sample size $t$ and any $Q_n$ that has unit scale \begin{align*} & \Pr_{S \sim Q_n^t} [R_{Q_n}(h) - R_{Q_n}^* > B \epsilon(h,|C(S)|,\delta)] \\ & \le \Pr_{S \sim Q_n^t} \left[R_{Q_n}(h) - R_{Q_n}^* > \epsilon(h,t,\delta)\right] + \Pr_{S \sim Q_n^t} \left[ B\epsilon(h,|C(S)|,\delta)\le \epsilon(h,t,\delta)\right] \\ & \leq \delta + \Pr_{S \sim Q_n^t} [|C(S)| < t/2] \end{align*} where the second inequality follows from the fact that $\epsilon$ is a valid $B'$-bounded-antimonotonic uniform model-dependent bound for unit-scale distributions and $B > B'$. Combining this with Lemma~\ref{l:unit}, we have \[ {\bf E}_{t \sim \mathrm{Poi}(c n),Q_n \sim {\cal Q}_n} [\Pr_{S \sim Q_n^t} [R_{Q_n}(h) - R_{Q_n}^* > B\epsilon(h,|C(S)|,\delta)]] \leq \delta + \frac{c_5}{n} + \Pr_{S \sim Q_n^t} [|C(S)| < t/2]. \] Now by a union bound, for some constant $c_9>0$, \begin{align} \lefteqn{{\bf E}_{t \sim \mathrm{Poi}(c n),Q_n \sim {\cal Q}_n} [\Pr_{S \sim Q_n^t} [|C(S)| < t/2]]} & \notag\\ & \le {\bf E}_{t \sim \mathrm{Poi}(c n),Q_n \sim {\cal Q}_n} [\Pr_{S \sim Q_n^t} [|C(S)| < c_9n]] + \Pr_{t \sim \mathrm{Poi}(c n)} [t/2 \geq c_9n] \notag\\ & = \Pr_{Z \sim B(bn, 1 - e^{-c/b})} [Z < c_9n] + \Pr_{t \sim \mathrm{Poi}(c n)} [t/2 \geq c_9n] \notag\\ & \le \delta, \label{ineq:chernoffpoisson} \end{align} where the last inequality follows from a Chernoff bound and from Lemma~\ref{l:poisson.tail} with $\alpha=1-2c_9/c$, provided $n=\Omega(\log(1/\delta))$ and provided we can choose $c_9$ to satisfy $c/2<c_9<b(1-e^{-c/b})$. Our choice of $b$ and $c$, specified below, will ensure this. In that case, we have that \begin{align*} & {\bf E}_{t \sim \mathrm{Poi}(c n),Q_n \sim {\cal Q}_n} [\Pr_{S \sim Q_n^t} [\epsilon(h,|C(S)|,\delta) \leq c_8]] \\ & \leq 2 \delta + \frac{c_5}{n} + {\bf E}_{t \sim \mathrm{Poi}(c n),Q_n \sim {\cal Q}_n} [\Pr_{S \sim Q_n^t} [R_{Q_n}(h) - R_{Q_n}^* \leq c_8B]]. \end{align*} Applying Lemma~\ref{lemma:Qbad.poisson} to bound the RHS, if $n$ is large enough and $c_8 B < c_7$, then \[ {\bf E}_{t \sim \mathrm{Poi}(c n),Q_n \sim {\cal Q}_n} [\Pr_{S \sim Q_n^t} [\epsilon(h,|C(S)|,\delta) \leq c_8]] \leq 3 \delta + \frac{c_5}{n}. \] Returning to (\ref{e:easy.by.hard}), we get \begin{equation} \label{e:ave.prob.small.random_r} {\bf E}_{r \sim B(bn, 1 - e^{-c/b})} [\Pr_{T \sim P_n^r} [ \epsilon(h,r,\delta))\leq c_8 ]] \leq 3 \delta + \frac{c_5}{n}. \end{equation} Let us now focus on the case that $b = 2$ and $c = 2 \ln 2$, so that \[ {\bf E}_{r \sim B(bn, 1 - e^{-c/b})}[r] = (1 - e^{-c/b})b n = n. \] (And note that $c/2=\ln 2 < 1 = b(1-e^{-c/b})$, as required for~\eqref{ineq:chernoffpoisson}.) Chebyshev's inequality implies \[ \Pr_{r \sim B(bn, 1 - e^{-c/b})}[ r \not\in [n - s, n + s ]] \leq c_{10} \] for an absolute positive constant $c_{10}$. Returning now to (\ref{e:ave.prob.small.random_r}), Markov's inequality implies \begin{equation} \label{e:most.bad.binomial} \Pr_{r \sim B(bn, 1 - e^{-c/b})} [\Pr_{T \sim P_n^r} [ \epsilon(h,r,\delta))\leq c_8 ] > 1/2] \leq c_{11} \left( \delta+ \frac{1}{n} \right). \end{equation} Further, it is known~\citep{slud1977distribution,box1978statistics} that there is an absolute constant $c_{12}$ such that, for all large enough $n$ and all $r_0 \in [n - s, n + s ]$, \[ \Pr_{r \sim B(bn, 1 - e^{-c/b})}[ r = r_0 ] \geq \frac{c_{12}}{\sqrt{n}}. \] Combining this with (\ref{e:most.bad.binomial}) and recalling that $s$ and $s'$ are $\Theta(\sqrt{n})$, we get \[ \frac{| \{ r \in [n - s, n + s] : \Pr_{T \sim P_n^r} [ \epsilon(h,r,\delta))\leq c_8 ] > 1/2 \} |}{2 s + 1} \leq c_{13} \left( \delta+ \frac{1}{n} \right) \leq \frac{c_{14}}{\log(1/\delta)}, \] for $n \geq c_4\log(1/\delta)$ and small enough $\delta$. Since, for all $r \in [n - s, n + s]$, we have $P_r = P_n$, this completes the proof. \end{proof} The following bound can be obtained through direction application of the results in \citep{bartlett2019benign}. The details are given in Appendix~\ref{a:P.interpolant_succeeds}. \begin{lemma} \label{l:P.interpolant_succeeds} There is a constant $c$ such that, for all large enough $n$, with probability at least $1-\delta$, for $S \sim P_n^n$, the least-norm interpolant $h$ satisfies $R_{P_n}(h) - R^*_{P_n} \leq c \sqrt{\frac{\log(1/\delta)}{n}}$. \end{lemma} Combining this with Lemma~\ref{l:bound_big} proves Theorem~\ref{t:main}. \section{Acknowledgements} We thank Andrea Montanari for alerting us to a flaw in an earlier version of this paper. We also thank Vaishnavh Nagarajan and Zico Kolter for helpful comments on an earlier draft of this paper, and Dan Roy for calling our attention to Lemma~5.2 of \citep{NDR20}. \bibliographystyle{plainnat}
{'timestamp': '2021-01-21T02:25:18', 'yymm': '2010', 'arxiv_id': '2010.08479', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08479'}
arxiv
\section{Introduction} Since the deployment of surgical robotic devices such as the da Vinci\textregistered{} Surgical System, efforts to automate surgical tasks have become a popular area of research \cite{yipDasJournal}. The automation of surgery has promised to help reduce surgeon fatigue and improve the procedural consistency between surgeries, and perhaps one day take over surgeries itself to address lack-of-access to timely, life-saving surgery in remote or under-served communities. Success in realizing surgical automation has accelerated in recent years, with improvements in available open-source platforms such as the da Vinci Research Toolkit (dVRK) \cite{kazanzides2014open} and simulators \cite{richter2019open}, coupled with significant advances to data-driven controller synthesis. Successful demonstrations of automated tasks have included cutting \cite{murali2015learning, thananjeyan2017multilateral}, suture needle hand-off \cite{d2018automated}, suturing \cite{sen2016automating, zhong2019dual}, and debridement removal \cite{kehoe2014autonomous}. Recent developments in perception for surgical robotics helps bridge these autonomous policies in ideal scenarios to realistic, deformable and noisy tissue environments such as the SuPer frameworks \cite{li2020super, lu2020super}. While progress in developing autonomous surgical tasks has leapt forward, a key area that has been given little attention are reactive policies to traumatic events, such as hemostasis. Hemostasis describes a state of the surgical field that is fulfilled when there is no site of active bleeding and the tissues are unobstructed by blood. The bleeding can originate from a visible or macroscopic blood vessel (artery or vein), or from the microvasculature and capillary network within tissues. Unlike previously automated tasks that occur in a more predictable cadence within a procedure, bleeding can be unpredictable which necessitates hemostasis maneuvers at any time during any surgery. Surgical manipulation of any type--suction, grasping, retraction, cutting, dissection--can immediately cause bleeding. Bleeding can also occur in a delayed manner, for example if a vessel is not definitively sealed, it can rupture spontaneously without direct contact. If surgical automation is ever to be deployed, reactive policies will be required to handle these traumatic scenarios. This work specifically addresses the problem of small and medium vessel ruptures. Overall, there are four distinct stages in hemostasis of this scenario: (1) clearing the surgical field of blood; (2) identification of the bleeding source (vessel rupture); (3) grasping the identified vessel to temporarily stop bleeding; (4) closing the vessel rupture, usually with an energy device, clip, or suture. Each stage requires a complex set of manipulation skills as well as perception algorithms that make it non-trivial to implement. In this paper, we describe an automated solution to the first task, clearing the surgical field, as shown in Fig. \ref{fig:cover_figure}. This task involves first recognizing blood in a scene, then tracking blood flow temporally, and finally prescribing a real-time trajectory generation strategy that will intelligently control a suction tool to siphon the blood to efficiently suction it. To this end, we present the following novel contributions: \begin{enumerate} \item The first complete automated solution for clearing the surgical field of flowing blood from a ruptured vessel using a robotic suction tool, \item a novel blood flow detection and tracking method by utilizing temporal visual information, \item and a trajectory generation technique from blood regions in the image frame for a surgical suction tool to follow and clear the surgical field. \end{enumerate} The blood flow detection and tracking method is tested within various simulated scenes as well as a real-life case involving a vessel rupture during thyroidectomy. The complete solution is tested in a lab setting with the da Vinci Research Kit (dVRK) \cite{kazanzides2014open} and a simulated surgical cavity for blood to flow through and collect in. The results from the experiments show the effectiveness of the blood flow tracking and surgical suction tool trajectory generation developed in this work. \section{Related Works} Previous work on blood detection largely is from the context of Wireless Capsule Endoscopy (WCE) where image processing for detections is used to speed up clinician workflow \cite{liedlgruber2011computer}. The typical approach to blood detection in WCE is to classify either on a pixel level or using patch-based methods \cite{fu2013computer}. The feature space used for classification is either direct Red, Green, Blue (RGB) \cite{liu2009obscure} channels or the transformed Hue, Saturation, Value (HSV) channels \cite{jung2008active}. To efficiently process these color spaces, techniques such as support vector machines \cite{okamoto2019real}, chromium moments combined with binary pattern textures \cite{li2009computer}, and neural networks \cite{pan2011bleeding, fu2011bleeding} have been demonstrated. While these methods are robust to small individual lesions, in a surgical scene there can be stains from previous ruptures and larger amounts of blood flow that make the problem of blood detection and, specifically, tracking, a more challenging and complex problem. There has been previous research on robots interacting with liquids in the act of pouring \cite{mottaghi2017see}. However, these methods cannot be applied to a surgical setting since they are limited to specific objects for pouring and capturing liquids. Schenck and Fox applied deep neural networks to detect fluids \cite{schenck2018perceiving} that can be combined with differential fluid dynamics to reconstruct 3D information \cite{schenck2018spnets}. This detection method however requires labelled real-world data which are challenging to collect in a surgical context. Yamaguchi and Atkeson instead used the heuristic of optical flow to detect moving fluid \cite{yamaguchi2016stereo}. The work presented here also uses optical flow to detect blood flow. However, instead of the classical method used by Yamaguchi and Atkeson, we applied a deep learning technique for improved performance of optical flow estimation in a surgical environment and fused the detections temporally with a novel temporal filter. \begin{figure}[t] \vspace{-2.5mm} \end{figure} \begin{algorithm}[t] \caption{Blood Suction} \label{alg} Initialize image frame probability map of blood: $\mathbf{P}_0$ \\ Initialize optical flow CNN with $l$ image frame inputs \\ Initialize counts of being blood: $\mathbf{C}_t \leftarrow \mathbf{0}$\\ \While{new image, $\mathbf{I}_t$, arrives}{ // Blood Region Detection\\ $\mathbf{O}_t \leftarrow \text{getOpticalFlowCNN}(\mathbf{I}_t, \dots, \mathbf{I}_{t-l-1})$\\ \For{pixel $p_{t} \in \mathbf{P}_{t}$}{ // Detect: \\ \eIf{$||\mathbf{O}_t(p)|| > \gamma_o$}{$z^p_t \leftarrow \text{b}$} {$z^p_t \leftarrow \overline{\text{b}}$} Predict: $P(p_t = \text{b} | z^p_{1:t-1})$ with (\ref{eq:predict_step}) and $\mathbf{P}_{t-1}$\\ Update: $P(p_t = \text{b} | z^p_{1:t})$ with (\ref{eq:update_step}) and $z^p_t$\\ } $\mathbf{B}_t$ is set to the largest connected region in binary mask $\mathbf{P}_t > 0.5$ \\ \If{ $size(\mathbf{B}_t) < \gamma_B$}{ continue\\ } // Suction Trajectory Generation\\ Update Blood Count: $\mathbf{C}_t \leftarrow \mathbf{C}_{t-1} + \mathbf{B}_t$ \\ End point: $e_t \leftarrow \underset{pixel}{\mathrm{argmax }} \text{ } \mathbf{C}_t \wedge \mathbf{B}_t$ \\ Start point: $s_t \leftarrow \underset{pixel}{\mathrm{argmin}} \text{ } \mathbf{C}_t \wedge \mathbf{B}_t$ \\ $\mathbf{T}_t \leftarrow $ generateTrajectoryForSuction($s_t$, $e_t$, $\mathbf{B}_t$)\\ \If{length$(\mathbf{T}_t) > \gamma_T$}{ break\\ } } executeTrajectory($\mathbf{T}_t$) \end{algorithm} \section{Methods} An overview of the proposed algorithms for blood region estimation and trajectory generation for an autonomous suction tool on a surgical robot is provided in Algorithm \ref{alg}. At a high level, the blood region is estimated by updating a probability map on the scene, which describes the probability of each pixel in the image frame being blood or not. From the probability map, the blood region is extracted. A trajectory is then generated for the suction tool to follow in order to clear the surgical field from blood. The trajectory is constrained to stay within the blood region to maximize the blood removed. \begin{figure}[t] \centering \vspace{2mm} \begin{subfigure}{0.2225\textwidth} \includegraphics[trim=10.5cm 1.25cm 10.5cm 0.5cm, clip, width=1\textwidth]{Figures/OpticalFlowExample/VectorsV1.pdf} \end{subfigure} \begin{subfigure}{0.255\textwidth} \includegraphics[trim=12.37cm 6.56cm 11.5cm 2.3cm, clip, width=1\textwidth]{Figures/OpticalFlowExample/Heatmap.pdf} \end{subfigure} \caption{The above images are generated by optical flow estimation from an in-vivo surgical scene. The left image shows the vectors of estimated image motion from optical flow, and the right image is a normalized heatmap of their magnitudes. Notice that the magnitude of optical flow detects the regions of blood flow well, while the orientation gives inconsistent information about the flow. } \label{fig:optical_flow_example_image} \end{figure} \subsection{Detecting Flowing Blood in Image Frame} Optical flow is chosen to detect flowing blood because it extracts information about all moving objects in the scene. In a surgical scene, the main motion comes from surgical tools and flowing fluids. Another source of motion in robotic surgery comes from a moving camera, but for robotic surgery the camera remains stationary when work is being done in a scene and its position is reset only to change the field of view. We therefore consider only stationary scenes. To mask instrument motion from the scene, previously developed methods can be applied to effectively segment and remove pixels attributed to surgical tools from image \cite{li2020super, lu2020super, allan20192017}. To estimate optical flow, a pretrained convolutional neural network (CNN) is used \cite{teney2016learning}. A deep learning strategy is used instead of traditional methods such as Lucas-Kanade \cite{lucas1981iterative} (used in previous work in robot pouring \cite{yamaguchi2016stereo}) as traditional optical flow approaches utilize brightness constancy constraint assumption, and this assumption is not valid in endoscopic procedures due to irregular lighting. Meanwhile, the proposed architecture by Teney and Herbert \cite{teney2016learning} is able to extract motion from learned features that are invariant to textures, brightness, and contrast, which is ideal for detecting flowing blood from an endoscope. Similar to previous work in robot pouring \cite{yamaguchi2016stereo}, we also found experimentally that the magnitude of optical flow is a good signal for detecting fluid motion while the orientation is not. An example of the processed image is shown in Fig. \ref{fig:optical_flow_example_image} comparing the RGB image to the amplitude map for optical flow. Consider the magnitude of optical flow at pixel $p$. Let $z^p_t$ be the random variable describing the detection of blood at pixel $p_t$ at time $t$. The detection is modelled where blood is detected, $z^p_t = \text{b}$, if the magnitude of optical flow at pixel $p_t$ is greater than a threshold, $\gamma_o$. The inverse is also set, so no blood is detected, $z^p_t = \overline{\text{b}}$, if the magnitude at pixel $p_t$ is less than $\gamma_o$. Hence the probability model for these detections can be simply written as: \begin{align} P( z^p_t = \text{b} \mid p_t = \text{b}) && P(z^p_t = \text{b} \mid p_t = \overline{\text{b}}) \label{eq:detection_probabilities_blood} \end{align} which describes an observation model for the hidden state $p_t \in \{ \text{b}, \overline{\text{b}} \}$. \subsection{Temporal Filtering for Blood Region Detection} Although the magnitudes of optical flow provide a good initial estimate for blood detection, they are nevertheless noisy and require filtering. Therefore, a temporal filter is based on a Hidden Markov Model (HMM) is proposed to fuse independent measurements of the pixel labels over time. The HMM tracks the discrete states for $p_t$ using the observation models in (\ref{eq:detection_probabilities_blood}). Let the following be a transition probability for a pixel $p_t$ be \begin{equation} P(p_{t+1} = \text{b} \mid p_t = \text{b}), \label{eq:motion_model_blood_to_blood} \end{equation} which models the probability that if a pixel is already blood it will continue being blood. In the case of blood vessel ruptures, this should be set close to 1 since the vessel rupture will not stop emitting blood until it has been closed. For the transition probabilities where the pixel is not blood at time $t$, an additional parameter, $k^p_t$, is introduced to the model: \begin{align} \label{eq:motion_model_no_blood_to_blood} P(p_{t+1} = \text{b} \mid p_t = \overline{\text{b}}, k^p_t = \text{b}) \\ P(p_{t+1} = \text{b} \mid p_t = \overline{\text{b}}, k^p_t = \overline{\text{b}}), \label{eq:motion_model_no_no_blood_to_blood} \end{align} where $k^p_t$ describes the state of the neighboring pixels of $p_t$. This is modelled as the resulting Boolean-OR operation ($\vee$) on the states of the neighboring pixels: \begin{equation} k^p_t = \DOTSB\bigop{\vee}_{q^i \in \mathbf{A}_p} q^i_t \end{equation} where $\mathbf{A}_p$ is the set of neighboring pixels to $p_t$. Therefore, the model from (\ref{eq:motion_model_no_blood_to_blood}) is capturing the flow of the blood and (\ref{eq:motion_model_no_no_blood_to_blood}) is describing the probability a blood source starts at pixel $p_t$. To appropriately describe these processes in this case of blood vessel ruptures, (\ref{eq:motion_model_no_blood_to_blood}) should be set less than (\ref{eq:motion_model_blood_to_blood}) and (\ref{eq:motion_model_no_no_blood_to_blood}) close to 0. The temporal filter is designed to estimate the posterior probability of the state $p_t$ using transition probabilities and observation models. This is done using a predict and update step after every detection. The predict step can be calculated as: \begin{multline} P(p_{t+1} \mid z^p_{1:t}) = P(p_{t+1} \mid p_t = \text{b}) P(p_t = \text{b} \mid z^p_{1:t}) + \\ \sum \limits_{k^p_t \in \{\text{b}, \overline{\text{b}}\}} P(p_{t+1} \mid p_t = \overline{\text{b}}, k^p_t) P(p_t = \overline{\text{b}}, k^p_t \mid z^p_{1:t}) \end{multline} and the update step is computed: \begin{equation} P(p_{t+1} \mid z^p_{1:t+1}) \propto P(z_{t+1} \mid p_{t+1}) P(p_{t+1} \mid z^p_{1:t}) \label{eq:update_step} \end{equation} However, the predict expression has the joint probability of $p_t$ and $k^p_t$. Explicit estimation for this joint probability would be computationally intractable, so each pixel's probability of being blood is approximated to be independent of all others at time $t$. With this simplification, the predict step can be rewritten as: \begin{multline} P(p_{t+1} \mid z^p_{1:t}) = P(p_{t+1} \mid p_t = \text{b}) P(p_t = \text{b} \mid z_{1:t}) + \\ \sum \limits_{k^p_t \in \{\text{b}, \overline{\text{b}}\}} P(p_{t+1} \mid p_t = \overline{\text{b}}, k^p_t) P(k^p_t \mid z^p_{1:t}) P(p_t = \overline{\text{b}}\mid z^p_{1:t}) \label{eq:predict_step} \end{multline} and an expression can be found for $P(k^p_t \mid z^p_{1:t})$ using the inclusion-exclusion principle: \begin{equation} P(k^p_t \mid z^p_{1:t}) = \sum \limits_{j = 1}^{|\mathbf{A}_p|} (-1)^{j-1} \sum \limits_{\substack{\mathbf{J} \subseteq \mathbf{A}_p\\|\mathbf{J}| = j}} \prod \limits_{q^i \in \mathbf{J}} P( q^i_t \mid z^p_{1:t}) \end{equation} This results in the ability to compute and track the probabilities of each pixel being blood using (\ref{eq:predict_step}) and (\ref{eq:update_step}) after every detection. \begin{figure}[t] \vspace{-3mm} \end{figure} \begin{algorithm}[t] \caption{Trajectory Generation for Suction} \label{alg:traj} \SetKwInOut{Input}{Input} \SetKwInOut{Output}{Output} \Input{Start pixel, $s_t$, end pixel, $e_t$, and mask of blood region $\mathbf{B}_t$} \Output{Trajectory $\mathbf{T}_t$} Initialize clearance reward $\mathbf{R} \leftarrow \mathbf{0}$\\ Initialize temporary eroded blood region $\mathbf{E} \leftarrow \mathbf{B}_t$\\ Initialize $i \leftarrow 0$ \\ \While{$\mathbf{E} \neq \mathbf{0}$ and $i < \gamma_r$}{ $\mathbf{E} \leftarrow \text{erode}(\mathbf{E})$ \\ $\mathbf{R} \leftarrow \mathbf{R} + r\mathbf{E}$\\ $i \leftarrow i + 1$ } Initialize pixels cost to go to goal: $\mathbf{D} \leftarrow \mathbf{\infty}$\\ Initialize visited map: $\mathbf{V} \leftarrow ! \mathbf{B}_t$ \\ Initialize parents of nodes: $\mathbf{K} \leftarrow \text{UNDEFINED}$\\ $\mathbf{D}(s_t) \leftarrow 0$\\ \While{ $\mathbf{V} \neq \mathbf{1}$ }{ $u \leftarrow \underset{pixel}{\mathrm{argmin}} \text{ } \mathbf{D}$ \\ $\mathbf{V}(u) \leftarrow 1$\\ \If{$u = e_t$}{ break\\ } \For{pixel $q$ neighboring $u$ and $\mathbf{V}(q) \neq 1$}{ \If{$\mathbf{D}(q) > ||q - u|| - \mathbf{R}(q)$}{ $\mathbf{D}(q) \leftarrow ||q - u|| - \mathbf{R}(q)$\\ $\mathbf{K}(q) \leftarrow u$\\ } } } Initialize trajectory for output: $\mathbf{T}_t \leftarrow $ [ ]\\ Initialize parent traversal node: $u \leftarrow e_t$\\ \While{$u \neq s_t$}{ Insert $u$ at beginning of $\mathbf{T}_t$\\ $u \leftarrow \mathbf{K}(p)$ \\ } \Return{ $\mathbf{T}_t$ } \end{algorithm} To find the region of blood on the image frame, a mask is generated where all pixels with a posterior probability greater than 0.5 is set to 1, and the rest are set to 0. Then dilation and erosion morphological operations are applied once to reduce noise on the mask. Finally, the largest connected region of the mask is considered the region with blood flowing if its size is greater than a threshold of $\gamma_B$. This threshold keeps a detection from occurring when there is no actual blood flowing. \begin{figure}[t] \centering \vspace{2mm} \begin{subfigure}{0.47\textwidth} \includegraphics[trim=4cm 1.5cm 4cm 4cm, clip, width=1\textwidth]{Figures/TrajectoryGenerationExample/sample_motion_plan.pdf} \end{subfigure} \begin{subfigure}{0.215\textwidth} \includegraphics[trim=1.9cm 1.8cm 1.5cm 1.65cm, clip, width=1\textwidth]{Figures/TrajectoryGenerationExample/counts_of_blood.pdf} \end{subfigure} \begin{subfigure}{0.25\textwidth} \includegraphics[trim=1.8cm 2.0cm 0.9cm 1.6cm, clip, width=1\textwidth]{Figures/TrajectoryGenerationExample/clearance_cost.pdf} \end{subfigure} \caption{Example of trajectory generation for blood suction from in-vivo scene. In the top figure, the white highlighted region is the detected blood region and the blue path is the generated trajectory. The starting and stopping points are chosen from the newest and oldest regions of the detected blood respectively, and a heatmap of the normalized detected blood age is shown in the bottom left figure. The generated path uses an additional clearance reward, which is shown in the bottom right figure, to reward paths that stay centered along the blood stream.} \label{fig:trajectory_gen_example} \end{figure} \begin{figure*}[t] \centering \vspace{2mm} \begin{subfigure}{0.16\textwidth} \includegraphics[trim=0cm 0cm 0cm 3cm, clip, width=1\textwidth]{Figures/simulated_scenes/Vector9_39.pdf} \end{subfigure} \begin{subfigure}{0.16\textwidth} \includegraphics[width=1\textwidth]{Figures/simulated_scenes/Vector8_39.pdf} \end{subfigure} \begin{subfigure}{0.16\textwidth} \includegraphics[width=1\textwidth]{Figures/simulated_scenes/Vector10_39.pdf} \end{subfigure} \begin{subfigure}{0.16\textwidth} \includegraphics[width=1\textwidth]{Figures/simulated_scenes/Vector11_39.pdf} \end{subfigure} \begin{subfigure}{0.16\textwidth} \includegraphics[width=1\textwidth]{Figures/simulated_scenes/Vector12_39.pdf} \end{subfigure} \begin{subfigure}{0.16\textwidth} \includegraphics[width=1\textwidth]{Figures/simulated_scenes/Vector13_39.pdf} \end{subfigure} \caption{Simulated scenes used to evaluate the proposed blood flow detection algorithm. The arrows highlight the direction of flow for the blood and how it fills the cavity. The detection algorithm estimates the blood flow via temporal tracking and aids in trajectory generation for a suction tool to remove the blood.} \label{fig:simulated_scenes} \end{figure*} \begin{figure*}[t] \includegraphics[trim=2.5cm 1.5cm 3cm 1cm, clip, width=0.495\textwidth]{Figures/IoUBoxPlots/IoUboxplot2.pdf} \includegraphics[trim=2.5cm 1.5cm 3cm 1cm, clip, width=0.495\textwidth]{Figures/IoUBoxPlots/IoUwithoutFilter.pdf} \caption{The left and right plots show Intersection over Union (IoU) results of blood flow estimation when using the proposed blood flow detection and tracking algorithm and only the blood detection from optical flow thresholding respectively. The complete pipeline results in better performance overall.} \label{fig:iou_results} \end{figure*} \subsection{Trajectory Generation for Blood Suction} A start and end point must be decided to generate a trajectory for suction. The end point should be roughly near the location of the vessel rupture in order to continuously remove any newly released blood. Meanwhile, the starting point should be downstream of the flowing blood in order to effectively clear the surgical field when suctioning upstream towards the source. Therefore, a simple estimation for the start and end point is done based on the age of the pixels in the blood region. The pixel with the largest and smallest ages in the blood region are defined as the end and start points respectively. To ensure that the end point is not generated at the exact edge of the blood stream, the blood region is eroded before selecting it The trajectory generated from the start to end point should also maximize its ability to suction blood while moving upstream. Therefore, using standard minimum distance paths are not ideal as they would tend to plan towards the edges of the blood region rather than the center. To center the trajectory in the blood region, an additional clearance reward is given to the motion planner. The clearance reward is generated by iteratively eroding the blood region for a max of $\gamma_r$ iterations. The pixels left in the eroded region are given an additional reward of $r$ at each iteration. The final trajectory in the image frame is then generated using Dijkstra's algorithm where the path is constrained to stay within the blood region and the clearance reward is subtracted from the normal distance cost. An outline of this trajectory generation technique is shown in Algorithm \ref{alg:traj}, and an example is shown in Fig. \ref{fig:trajectory_gen_example}. The trajectory is then executed if it is longer than a threshold $\gamma_T$. This threshold gives time for the start and end points to stabilize so an effective trajectory can be generated. \section{Experiments and Results} The proposed blood flow detection and tracking method was evaluated on both simulated scenes and a live surgery involving a hemorrhage during a thyroidectomy. The complete automated suctioning solution was demonstrated on in a lab setting on a simulated surgical cavity and red fluid for blood. The following sections describe these experiments, the necessary implementation details, and results. \subsection{Implementation Details} All subsequent experiments were ran on a computer with Intel\textregistered{} Core$^{\text{TM}}$ i9-7940X Processor and NVIDIA’s GeForce RTX 2080. The blood flow detection and trajectory generation algorithms were implemented in MATLAB. The CNN for optical flow estimation \cite{teney2016learning} is pre-trained on the Middlebury dataset \cite{baker2011database}, uses $l=3$ image frames for input, and the resolution of the optical flow estimation is 1/4 of the input frame resolution. These are the default values of the original CNN implementation. The size of the probability map is set to the optical flow resolution. The threshold for detection, $\gamma_o$, region size, $\gamma_B$, maximum number of erosions for clearance, $\gamma_r$, and trajectory length, $\gamma_T$, are set to 0.45, 20, 4, and 30 respectively. The detection probability, $P(z^p_t = \text{b} | p_t = \text{b})$, $P(z^p_t = \text{b} | p_t = \overline{\text{b}})$, are set to 0.95 and 0.2 respectively because experimentally we found the true positive rate and false negative rate to be very accurate and noisy respectively. The initial probability of a pixel being blood, $P(p_0 = \text{b})$ and transition probabilities of a pixel being blood, $P(p_{t+1} = \text{b} | p_t = \text{b})$, $P(p_{t+1} = \text{b} | p_t = \overline{\text{b}}, k^p_t = \text{b})$, $P(p_{t+1} = \text{b} | p_t = \overline{\text{b}}, k^p_t = \overline{\text{b}})$, are set to 0.1, 0.98, 0.85, and 0.01 respectively. The neighbors for a pixel, $\mathbf{A}_p$, are set to just up, down, left, and right since the algorithm needs to run quickly for real-time detection in the upcoming experiments. The clearance reward per erosion, $r$, is set to 0.2. \begin{figure*}[t] \centering \vspace{2mm} \begin{subfigure}{0.245\textwidth} \includegraphics[width=1\textwidth]{Figures/IoU_Figures/InVivo_6.jpg} \end{subfigure} \begin{subfigure}{0.245\textwidth} \includegraphics[width=1\textwidth]{Figures/IoU_Figures/InVivo_18.jpg} \end{subfigure} \begin{subfigure}{0.245\textwidth} \includegraphics[width=1\textwidth]{Figures/IoU_Figures/InVivo_26.jpg} \end{subfigure} \begin{subfigure}{0.245\textwidth} \includegraphics[width=1\textwidth]{Figures/IoU_Figures/InVivo_38.jpg} \end{subfigure} \vspace{1mm} \begin{subfigure}{0.245\textwidth} \includegraphics[width=1\textwidth]{Figures/IoU_Figures/simublood9_2.jpg} \end{subfigure} \begin{subfigure}{0.245\textwidth} \includegraphics[width=1\textwidth]{Figures/IoU_Figures/simublood9_20.jpg} \end{subfigure} \begin{subfigure}{0.245\textwidth} \includegraphics[width=1\textwidth]{Figures/IoU_Figures/simublood9_40.jpg} \end{subfigure} \begin{subfigure}{0.245\textwidth} \includegraphics[width=1\textwidth]{Figures/IoU_Figures/simublood9_60.jpg} \end{subfigure} \caption{Example figures of blood flow detection and tracking. The top and bottom sequences are from an in-vivo rupture and simulated scene respectively. The highlighted green regions are the intersection between ground truth and blood flow detection. Meanwhile, the highlighted blue regions are the error of detection, i.e., the union minus intersection between the ground truth and blood flow detection. These figures are best viewed in color } \label{fig:IoU_qualitive_results} \end{figure*} \subsection{Datasets to Evaluate Blood Region Detection} Two separate datasets were generated for this work to evaluate the proposed blood region detection algorithm. Both datasets have labelled ground-truth masks, $\mathbf{G}_t$, of the blood region. Performance is evaluated from these datasets using the Intersection over Union (IoU) metric: \begin{equation} \frac{\mathbf{B}_t \wedge \mathbf{G}_t}{\mathbf{B}_t \vee \mathbf{G}_t} \label{eq:iou} \end{equation} where $\mathbf{B}_t$ is a mask of the detected blood region from our proposed method, $\wedge$ is the Boolean-AND operation and $\vee$ is the Boolean-OR operation. \subsubsection{Simulated Scenes} Six simulated scenes of flowing blood are generated using Unity3D's particle-based fluid dynamics (PBDs). The scenes are shown in Fig. \ref{fig:simulated_scenes}. A total of 61 image frames were extracted per scene. The ground-truth mask, $\mathbf{G}_t$, of the blood region is generated by projecting the fluid particles onto a virtual camera's image plane and applying Gaussian smoothing. The rendered image is set to 1095$\times$1284 pixels. \subsubsection{In-Vivo Surgical Scene} After the completion of a thyroidectomy conducted on a pig (UCSD IACUC S19130), a rupture occurred on the carotid artery. The 8s video data from this incident is used to evaluate the blood flow detection and tracking algorithm in a similar manner to the simulated scenes. For ground-truth masks of the blood region, $\mathbf{G}_t$, 10 evenly distributed frames were manually annotated. The recorded image size was 640 by 480 pixels. \subsection{Performance of Blood Region Detection} To show the effectiveness of the tracking algorithm, a comparison experiment was conducted where the blood flow region was simply set to be the pixels with optical flow magnitude greater than $\gamma_O$. The distribution of IoU results are shown in Fig. \ref{fig:iou_results} for blood flow region detection with and without the tracking algorithm on the simulated scenes and in-vivo dataset. There is a clear difference in performance of the blood flow detection and tracking between the simulated scenes and in-vivo rupture. We believe this is due to the poorer lighting conditions and the reflective surgical clamps used in the in-vivo scene as seen in Fig. \ref{fig:IoU_qualitive_results}. Nonetheless, the blood region is successfully estimated when using the tracking algorithm despite the many red stains, hence highlighting the importance of using temporal information for detection rather than color features. For additional comparison, Lucas-Kanade's \cite{lucas1981iterative} and Farnebeck's \cite{farneback2003two} optical flow estimation techniques were replaced for the CNN based optical flow estimation \cite{teney2016learning}. Note that Lucas-Kanade's optical flow estimation is the proposed detection method for fluids by Yamaguchi and Atkeson used for robot pouring \cite{yamaguchi2016stereo}. The resulting IoU for the in-vivo and simulated scenes was measured to be consistently below 0.50 in both cases, which is substantially lower than our proposed detection technique. \begin{figure}[t] \centering \includegraphics[trim=0cm 0cm 6.65cm 0cm, clip, width=0.45\textwidth]{Figures/simple_cavity/injection_points.pdf} \caption{Endoscopic view of phantom used for the automated suction experiments. The red arrows highlight the direction of flow at the four injection points tested in the experiment.} \vspace{-2mm} \label{fig:silicon_cavity} \end{figure} \begin{figure*}[t] \centering \vspace{2mm} \begin{subfigure}{0.24\textwidth} \includegraphics[width=1\textwidth]{Figures/simple_cavity/sequence_endo_0.jpg} \end{subfigure} \begin{subfigure}{0.24\textwidth} \includegraphics[width=1\textwidth]{Figures/simple_cavity/sequence_endo_2.jpeg} \end{subfigure} \begin{subfigure}{0.24\textwidth} \includegraphics[width=1\textwidth]{Figures/simple_cavity/sequence_endo_3.jpeg} \end{subfigure} \begin{subfigure}{0.24\textwidth} \includegraphics[width=1\textwidth]{Figures/simple_cavity/sequence_endo_4.jpeg} \end{subfigure} \caption{Sequence of figures (from left to right) of an automated suction experiment where the liquid is injected at the bottom left corner. The images are captured from the endoscopic view with the first one highlighting the detected and tracked blood region in white and the generated trajectory in blue. To achieve real-time capabilities and react quickly to flowing blood, the blood detection and tracking algorithm is set to a lower resolution in these experiments. Nonetheless, the robotic suction tool follows the generated trajectory and efficiently removes fluids from the cavity. } \label{fig:simple_cavity_suction} \end{figure*} \subsection{Automated Suction in Cavity} To evaluate the complete autonomous surgical task of recognizing blood flow and performing autonomous suction, a tissue phantom with a cavity for liquid to flow through is constructed from silicone, and water with red coloring dye is drained into the cavity using surgical tubing as shown in Fig. \ref{fig:silicon_cavity}. A stereoscopic camera with a resolution of 1080$\times$1920 pixels at 30fps on the dVRK \cite{kazanzides2014open} is used. The trajectory generated for suction is converted into 3D position commands using the Pyramid Stereo Matching Network (PSMNet) \cite{chang2018pyramid}, which takes the stereo-images of the cameras and determines the depth of each pixel. PSMNet's weight are provided by their original implementations without any task-specific fine-tuning; the maximum disparity is set to 192. PSMNet estimated depth using an image size of 640 by 480 pixels meanwhile the blood flow detection algorithm used a reduced image size of 160 by 120 pixels to improve its speed. A Patient Side Manipulator (PSM) from the dVRK \cite{kazanzides2014open} was equipped with da Vinci\textregistered{} Si Suction Tool and followed the generated trajectory to clear the simulated surgical cavity from blood. To follow the trajectory, the position of the end-effector in the PSM base frame, $\mathbf{b}_t$, is iteratively set to: \begin{equation} \overline{\mathbf{b}}_{t+1} = \begin{cases} \gamma_s \frac{\mathbf{d}_{t}}{||\mathbf{d}_{t}||} + \overline{\mathbf{b}}_{t} & \text{if } ||\mathbf{d}_{t}|| > \gamma_s\\ \mathbf{d}_{t} + \overline{\mathbf{b}}_{t} & \text{if } ||\mathbf{d}_{t}|| \leq \gamma_s \end{cases} \end{equation} where $\gamma_s = 0.75$mm is the max step size, the operator $\overline{\cdot} = \begin{bmatrix} \cdot& 1\end{bmatrix}^\top$ gives the homogeneous representation of a point, and the direction, $\mathbf{d}_t$, is computed as \begin{equation} \mathbf{d}_t = \mathbf{T}^b_c \overline{\mathbf{b}}^g - \overline{\mathbf{b}}_{t} \end{equation} The camera to base transform, $\mathbf{T}^b_c \in SE(3)$, is estimated in real time using our previous work \cite{li2020super} and $\mathbf{b}^g$ is the 3D goal position generated by the trajectory and PSMNet. This controller is ran at 100Hz and is repeated until $||\mathbf{d}_t|| < 2$mm per target position, $\mathbf{b}^g$, from the generated trajectory. Meanwhile the orientation of the suction tip is set to always be in direction of gravity. The position, $\mathbf{b}_t$, and orientation of the end-effector is converted to joint angles using an analytical inverse kinematic solution. These joint angles are then regulated using dVRK \cite{kazanzides2014open}. To account for imperfections in the 3D depth estimation from PSMNet and surgical tool tracking to regulate the end-effector, the suction tool was commanded to oscillate in and out along the direction of gravity an additional 5mm at every point on the trajectory. This probing behavior ensured that the tool always sucked up the blood and neither drifted above the blood nor penetrated and dragged tissue. The Robot Operation System (ROS) is used to encapsulate the image processing and robot trajectory tracking processes \cite{ros}. Roughly 50mL of liquid is injected using a syringe into the cavity at one of the four locations highlighted in Fig. \ref{fig:silicon_cavity}. Before each trial, the end-effector is centered in the middle of the silicon mold such that it does not obstruct any of the injected liquid as shown in Fig. \ref{fig:silicon_cavity}. The percentage of liquid removed from the cavity, time to react to the injected fluid, the time to complete the trajectory were measured to evaluate the performance of the proposed automation method. The percentage of liquid removed was measured by weighing the silicon mold and syringe before and after each trial. Time to react refers to the time taken to detect the flowing blood and generate a trajectory (i.e., completing Algorithm \ref{alg}) from the first moment that the injected blood is visible in the camera frame. To ensure consistency of the proposed automation method, the experiment is repeated ten times at each of the four injection spots. The results from the total 40 trials of the automated suction experiment are shown in Table \ref{tab:automated_suction_results} and an example sequence is shown in Fig. \ref{fig:simple_cavity_suction}. During the experiments, we noticed the liquid generally pooled near the bottom left injection point since it was slightly lower with respect to gravity than the rest of the cavity. This lead to shorter trajectories being generated, and hence less time to execute them as seen in the results, for the bottom left corner experiment compared to the others. A similar set up is repeated for demonstration purposes and the result is shown in Fig. \ref{fig:cover_figure}. The mold used for this demonstration was constructed using candle wax and has pig intestine embedded in it. Everything else is kept the same as the previously described. Despite changes to the visual textures and topology of the scene, we can see that the method is robust enough to perform autonomous tracking and suction of blood without modification. \begin{table}[t] \centering \caption{Mean results from automated suction experiment at each injection point. } \def1.2{1.2} \begin{tabular}{c|c|c|c} \multirow{ 2}{*}{\textbf{Injection Point}} & \textbf{Liquid} & \multirow{ 2}{*}{\textbf{Time to React}} & \textbf{Time to Execute}\\ & \textbf{Suctioned} & & \textbf{Trajectory} \\ \hline Top Left & 96.7\% & 4.1s & 45.3s \\ Top Right & 93.6\% & 2.6s & 47.4s \\ Bottom Left & 96.1\% & 4.7s & 23.9s \\ Bottom Right & 96.8\% & 6.4s & 38.1s \end{tabular} \label{tab:automated_suction_results} \end{table} \section{Discussion and Conclusion} In this work, the first completely automated solution for clearing the surgical field from blood is presented. The solution provides both the perception, trajectory generation, and control strategy required for the task of clearing blood. This is the first step taken towards automation of a crucial surgical task, hemostasis, which can occur in any surgery at any time. To ensure robustness against blood stains, the algorithm relies on temporal information for detection. The novel blood flow detection and tracking algorithm presented offers a unique, probabilistic solution to tracking liquids over 3D cavities and channels, under noisy and harsh visibility conditions, and is a critical perceptual element. This estimation and tracking helps inform a trajectory generation technique to act upon the detected blood and uses a clearance reward to maximize the blood suctioned by the suction tool and be robust against imperfect blood region estimation. For future work, we intend to push towards a complete solution for automation of hemostasis. To accomplish this, a more precise location of the bleeding source will be estimated using a particle based motion model, similar to PBD simulators, in the temporal filtering. Another consideration will be integration of surgical tool masking using our previous works \cite{li2020super, lu2020super} into the blood tracking framework as the hemostasis automation task will require additional surgical robotic tools. \section{Acknowledgements} This work is supported by the National Science Foundation (NSF) under grant number 1830403 and 1935329 and the US Army Telemedicine and Advanced Technology Research Center (TATRC) under the Robotic Battlefield Medical Support System project. F. Richter is supported by the NSF Graduate Research Fellowship. The authors would like to thank Intuitive Surgical Inc. for instrument donations, Jingpei Lu for his support with PSMNet, Harleen Singh for her support with the molds, Simon DiMiao, Omid Maherari, Dale Bergman, and Anton Deguet for their support with the dVRK. \balance \bibliographystyle{ieeetr}
{'timestamp': '2021-01-19T02:45:53', 'yymm': '2010', 'arxiv_id': '2010.08441', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08441'}
arxiv
\section{Introduction} Electronic health records (EHRs) have now become ubiquitous and offer novel opportunities for clinical research by supporting the development of intelligent decision support systems and improvement of patients' care. One of the distinct features of EHR is that the data are being collected over time and might be seen as health data streams, allowing research to study longitudinal trends and make inference about the progression of disease, treatments and outcomes. However, the proper representation of sequential medical events still remains a challenge. Moreover, longitudinal clinical notes exhibit a multi-level hierarchical structure, where events are described and embedded in sentences, sentences in paragraphs and eventually resulting in chronologically ordered documents. Recent works have addressed the problem of capturing this information directly from raw texts by introducing novel neural network architectures, such as attention-based recurrent neural networks \cite{bai2018interpretable} and time-aware Transformers \cite{zhang2020time}. When dealing with chronological clinical notes, practitioners make multiple decisions on how to structure and transform these sequential events, which are often simplifications of medical histories. In this work we proposed a different methodology to address the problem of learning from events found in clinical notes, by first extracting them using natural language processing and then representing the sequential order by means of the {\it path signatures}. The signature \cite{lyons2014rough} is a non-parametric representation of heterogeneous sequential data, offers a feature extraction method from longitudinal events and can naturally be integrated within a general data mining pipeline. To demonstrate the methodology, we used the largest secondary care mental health EHR data in the UK to develop a survival prognostic model for patients diagnosed with Alzheimer's disease. \section{Method} \subsection{Data} The data in this study were sourced from the UK-Clinical Record Interactive Search system (UK-CRIS), which provides a research platform (https://crisnetwork.co/) for data mining and analysis using de-identified real-world observational electronic patients records from twelve secondary care UK Mental Health NHS Trusts \citep{goodday2020maximizing}. UK-CRIS provides access to structured information, such as ICD-10 coded diagnoses, quality of life scales and demographic information, as well as various unstructured texts, such as clinical summaries, discharge letters and progress notes. The study cohort jointly comprised records from 24,108 patients diagnosed with Alzheimer's disease and various types of dementia, containing more than 3.7 million individual clinical documents from two centres: Oxford and Southern Health Foundation NHS Trusts. The field of clinical NLP in general, and of mental health and Alzheimer's research in particular, largely suffers from the dearth of gold-annotated data. The reason is due to the shortage of trained annotators with clinical background who are also authorised to access sensitive patient-level data. Therefore, to develop a robust information extraction (IE) model from an insufficient amount of data, we leveraged the idea of transfer learning using the publicly available MIMIC-III corpus \citep{johnson2016mimic} comprising information relating to patients admitted to intensive care units (ICU) with more than 2.1 million clinical notes as well as 505 gold-annotated by clinical experts discharge summaries from the 2018 n2c2 challenge \citep{henry20202018}. We assert that the study was independently approved and granted by the Oxfordshire and Southern Health NHS Foundation Trust Research Ethics Committees. \subsection{Information extraction model} The information extraction model was developed to identify diagnosis, medications and cognitive health assessment Mini-Mental State Examination score (MMSE) \cite{pangman2000examination}. Additionally, the identified entities were classified according to several attributes, such as the 'experiencer' modality (i.e., whether the MMSE was actually referring to a patient or to a family member), temporal information (i.e the date of diagnosis or MMSE score) and negations (i.e. discontinued medications) \citep{harkema2009context, gligic2019named}. Such drug mentions were discarded in order to extract the most accurate information. Generic and brand drug names were normalised using the British National Formulary, the core pharmaceutical reference book \citep{joint2019bnf}. The architecture of the named entity recognition model comprised a hybrid approach of an ontology-based fuzzy pattern matching and a bi-directional LSTM neural network architecture with the attention mechanism \citep{bahdanau2014neural} for sequence classification. The GloVE word embedding \cite{pennington2014glove} were fine-tuned on both MIMIC-III and UK-CRIS data \citep{vaci_koychev_kim_kormilitzin_liu_lucas_dehghan_nenadic_nevado-holgado_2020, kormilitzin2020med7}. The developed IE model was trained only on data from the Oxford Health NHS Trust instance and externally validated on a sample of data from a regionally different Southern Health NHS Foundation Trust. \subsection{The signature of a path} \label{sec:signatures} Repeated measurements, speech, text, time-series or any other sequential data might be seen as a path-valued random variable. Formally, a path $X$ of finite length in \textit{d} dimensions can be described by the mapping $X:[a, b]\rightarrow\mathbb{R}$ $\!\!^d$, or in terms of co-ordinates $X=(X^1_t, X^2_t, ...,X^d_t)$, where each coordinate $X^i_t$ is real-valued and parametrised by $t\in[a,b]$. The signature representation $S$ of a path $X$ is defined as an infinite series: \noindent \begin{equation}\label{eq:path_signature} \begin{split} S(X)_{a, b} = (1, & S(X)_{a, b}^1, S(X)_{a, b}^2, ..., S(X)_{a, b}^d, \\ & S(X)_{a,b}^{1, 1}, S(X)_{a,b}^{1, 2}, ...), \end{split} \end{equation} \noindent where each term is a $k$-fold iterated integral of the path $X$ labelled by multi-index $i_1,...,i_k$: \begin{equation}\label{eq:sig_moments} S(X)_{a, b}^{i_1,...,i_k} = \int_{a<t_k<b}...\int_{a<t_1<t_2} \mathrm{d}X_{t_1}^{i_1}...\mathrm{d}X_{t_k}^{i_k}. \end{equation} \noindent However, in many real-life applications the first $k$-terms of the truncated signature at level $L$ give a satisfying approximation. Intuitively, it is analogous to statistical moments of a $d$-dimensional vector-valued random variable, such as mean, variance or higher moments. One can define statistical moments of a \textit{path}-valued random variable, which are essentially the {\it signature} moments \citep{chevyrev2018signature} defined in Eq. \eqref{eq:sig_moments}. The signature $S(X)$ completely characterises a path $X$ up to tree-like equivalence and is invariant to reparameterisation \citep{hambly2010uniqueness}. The signature can also be expressed in a more compact form known as {\it log-signature} \cite{liao2019learning, morrill2020neural}, which is the formal power series of $\log S(X)$, while carrying the same information. Informally, the path signature captures the order of events. For example, consider two sequences $X_1$ = {\it aabba} and $X_2$ = {\it baaab} consisting of a simple vocabulary with only two letters $\{a, b\}$. The sequences might be presented as paths in 2d space as shown in Fig. \ref{fig:two_paths}. \begin{figure}[htp!] \centering \includegraphics[width=0.4\textwidth, height=3.5cm]{artwork/two_paths.png} \caption{Two paths $X_1$ = {\it aabba} and $X_2$={\it baaab}.} \label{fig:two_paths} \vspace{-0.0cm} \end{figure} \noindent Each linear segment between two points (Fig. \ref{fig:two_paths}) corresponds to a single letter in the sequence and the arrows denote the temporal direction of the sequence. \begin{table}[h] \centering \resizebox{\columnwidth}{!}{ \begin{tabular}{c|cc|c|cc|ccc} Level & \multicolumn{2}{c|}{1} & \multicolumn{1}{c|}{2} & \multicolumn{2}{c|}{3} & \multicolumn{3}{c}{4} \\\hline\hline $S(X_1)$ & 3 & 2 & {\bf 1} & {\bf -0.5} & {\bf -1} & {\bf -1/3} & {\bf -0.5} & 0 \\ $S(X_2)$ & 3 & 2 & {\bf 0} & {\bf 1.5} & {\bf 0.5} & {\bf 0} & {\bf 0} & 0 \\ \hline \end{tabular}} \caption{The first $k=8$ terms of the log signature expansion up to level $L=4$. The difference between two sequences $X_1$ and $X_2$ is apparent starting from the second level.} \label{tab:log_sig_of_paths} \end{table} \noindent \vspace{-0.2cm} Despite the same number of letters in the sequences $\{a=3, b=2 \}$, the order of letters matters. The signature easily picks the differences and the first four levels of the log-signatures of paths are shown in Table \ref{tab:log_sig_of_paths}. The lower order signature terms $S^{(i)}$ are the increments along the $i$-th direction (i.e. the distance between the endpoints), for example, $S^{(1)}=3-0=3$ and $S^{(2)}=2-0=2$ as can be seen in Figure \ref{fig:two_paths}. The second order corresponds to the area enclosed by a path and a chord connecting endpoints \cite{chevyrev2016primer}. The usefulness of a path signature as a feature map of sequential data was demonstrated theoretically \citep{chevyrev2018signature} as well as in numerous machine learning applications in healthcare \citep{morrill2019signature, kormilitzin2016application, arribas2017signature, morrill2020utilization, kormilitzin2017detecting}, finance \citep{arribas2018derivatives}, computer vision \citep{yang2017leveraging, xie2017learning}, topological data analysis \citep{chevyrev2018persistence} and deep learning \citep{kidger2019deep}. \begin{table*}[t] \centering \resizebox{2\columnwidth}{!}{ \begin{tabular}{L{2.2cm} L{16cm}} Doc date & Text \\\hline\hline 05-Oct-2016 & {\it Today I saw a patient diagnosed with Alzheimer's, who deteriorated: MMSE 23/30 as compared to 25/30 from 1st January. Started on Rivastigmine.}\\ 12-Feb-2017 & {\it Today MMSE 19, the patient didn't respond to Rivastigmine and was changed to Donepezil.} \\ 03-Feb-2018 & {\it Great response to new treatment (MMSE 23/30), continue on Donepezil.} \\ 01-Apr-2019 & {\it The patient stopped responding to Donepezil and severely deteriorated (MMSE 14/30), stop Donepezil.} \\\hline \end{tabular} \caption{A synthetic example of chronological medical records.} \label{tab:records} \end{table*} \noindent \vspace{-0.0cm} \noindent \subsection{Independent and outcome variables} The independent variables used in the prognostic model were medications and the MMSE scores collected over time. The dependent outcome variable was right-censored time to death data in months. A synthetic example of the patient's records (Table \ref{tab:records}) and the corresponding algorithmically extracted longitudinal data is presented in Table \ref{tab:longitudinal_data_example}. The outcome variable was encoded as a tuple: $(True, 34.17)$ indicating that a person has died after 34.17 months since the very first visit to a specialist memory clinic. The patient was treated by two different medications with a changing pattern and eventually was tapered off medication due to no further expected improvement. \begin{table}[htp!] \centering \resizebox{0.99\columnwidth}{!}{ \begin{tabular}{L{3cm}L{3cm}L{1.5cm}} Date & Medication & MMSE \\\hline\hline 01-Jan-2016 & NoMed & 25/30 \\ 05-Oct-2016 & Rivastigmine & 22/30 \\ 12-Feb-2017 & Donepezil & 19/30 \\ 03-Feb-2018 & Donepezil & 23/30 \\ 01-Apr-2019 & Discontinued & 14/30 \\\hline \end{tabular}} \caption{Extracted and chronologically structured data from Table \ref{tab:records}.} \label{tab:longitudinal_data_example} \end{table} \vspace{-0.0cm} \noindent \subsection{Baseline longitudinal data summarisation} \label{sec:linear_features} The signature transformation might be seen as a hierarchical statistical summarisation (\say{feature extraction}) of the longitudinal data along the temporal dimension. In order to benchmark the proposed method, we used a time-honoured linear mixed-effects regression as a baseline model for longitudinal summarisation. Specifically, each patient-level longitudinal MMSE scores were modelled using a linear regression and the resulting coefficients, such as an intercept and a slope, were used as features representing the progression of the MMSE over time. The median number of medication categories was used as an additional feature, resulting in three features for each patient. \subsection{Survival random forests} The common statistical approach to analyse the time-to-event survival data is based on the linear Cox model \cite{collett2015modelling}. However, \citet{miao2015random} showed that a survival random forest (SRF) approach \cite{ishwaran2008random} outperformed linear Cox model, based on the Harrell’s concordance index (C-index) \cite{harrell1982evaluating}, and was understandably capable of identifying non-linear effects of the input variables as opposed to linear Cox model. Therefore, we chose the SRF as the preferred method. The SRF approach was implemented in Python using \say{scikit-survival} package \cite{polsterl2015fast}. The Harell's C-index (the concordance index) is a goodness of fit measure for risk scores models. It is a common statistical approach to evaluate risk models in survival analysis, where data may be right-censored and corresponds to rank correlation between predicted risk scores and observed time points, similarly to Kendall’s $\tau$. \vspace{-0.0cm} \section{Results} \subsection{Information extraction model} We used a hybrid approach to developing an IE model consisting of training a baseline model using MIMIC-III and n2c2 annotated data. Specifically, the named-entity recognition (NER) model comprised a transition-based system based on the chunking model \cite{lample2016neural} where tokens were represented as hashed and embedded representations of the prefix, suffix, shape and lemmatised features of words, followed by the rule-based matching using the BNF vocabulary. The IE model was implemented using \say{spaCy} python library\footnote{https://spacy.io}, including negations and temporal information identification as well as relationships classification between the word-tokens using linguistic features, such as part-of-speech and dependencies. Finally, the active learning tool \say{Prodigy}\footnote{https://prodi.gy} was used for iterative model improvement \cite{vaci2020natural}. Target domain training, validation and external validation data contained a collection of gold-annotated drug names, diagnosis and cognitive health assessment MMSE scores as shown in Table \ref{tab:annotated_summary_stats}. \begin{table}[h] \centering \resizebox{\columnwidth}{!}{ \begin{tabular}{lrrrr} Concept & Training & Validation & External val. & Total \\ \hline\hline Drug & 216 & 153 & 30 & 399 \\ MMSE & 169 & 87 & 23 & 279 \\ Diagnosis & 570 & 352 & 26 & 948 \\\hline \end{tabular} } \caption{The number of gold-annotated instances in the training, validation and external validation data sets.} \label{tab:annotated_summary_stats} \vspace{-0.3cm} \end{table} \noindent The IE model achieved a good and consistent performance on both validation and external validation data sets (Table \ref{tab:ie_results}). The annotation schema was developed following the recommendations of \citet{pustejovsky2012natural}. The token-level performance metrics were evaluated using the SemEval schema \cite{segura2013semeval} and the inter-annotator agreement (IAA) of two clinical annotators was computed using F1 score. \begin{table}[htp!] \centering \resizebox{\columnwidth}{!}{ \begin{tabular}{llll|lll|l} & \multicolumn{3}{c|}{Validation} & \multicolumn{3}{c|}{External val.}& IAA \\ Concept & Pr & Re & F1 & Pr & Re & F1 & F1 \\ \hline\hline Diagnosis & 89.6 & 96.3 & 92.8 & 84.1 & 86.3 & 84.8 & 95 \\ Drug & 98 & 98 & 98.1 & 92.4 & 68.4 & 78.3 & 96 \\ MMSE & 92.6 & 74.7 & 82.8 & 85.6 & 81.2 & 82.6 & 100 \\\hline \end{tabular} } \caption{Performance (shown in $\%$) of the information extraction model. IAA - inter annotator agreement.} \label{tab:ie_results} \end{table} \noindent \vspace{-0.7cm} \begin{table}[htp!] \centering \resizebox{\columnwidth}{!}{ \begin{tabular}{ccccc} & n & male & female & survival time \\\hline\hline died & 1962 & 841 & 1121 & 52.2(22.8) \\ censored & 1500 & 529 & 971 & 28.4(16.6) \\\hline \end{tabular}} \caption{Summary statistics of the extracted data for survival analysis. Survival time is shown as mean(std) in months. The MMSE scores were not observed for censored people later in time, while date of death was recorded in hospital.} \label{tab:my_label} \end{table} \vspace{-0.5cm} \subsection{Prognostic model} Four prognostic models were developed and compared to each other. All models estimated the survival probability of a patient diagnosed with Alzheimer's disease since their first admission to a memory clinic. We compared signature (\say{Sig}, Sec. \ref{sec:signatures}) versus non-signature (\say{Non-sig}, Sec. \ref{sec:linear_features}) models. We also estimated the added value of the sequential information contained in the treatment course with medications. Specifically, we used two sets of input variables: $\{$time, MMSE$\}$ and $\{$time, MMSE, medications$\}$, where time corresponds to the date of MMSE score or prescribed medication as presented in Table \ref{tab:longitudinal_data_example}. For the \say{Sig} model, the input variable were first transformed into signatures, where the categorical medication names were one-hot encoded and augmented with numerical MMSE scores to create a path. For the \say{Non-sig} model, the longitudinal MMSE scores were summarised by means of linear models adjusting for each patients and the median number of distinct medications were computed. Both models were trained and validated using the same folds of stratified 5-fold cross validation (with fixed random seed). The quality of predictions was assessed using the Harell's C-index and the results are summarised in Table \ref{tab:results}. The signatures were computed using the \say{esig} Python library\footnote{https://esig.readthedocs.io/}, however, alternative libraries are also available \cite{reizenstein2018iisignature, kidger2020signatory}. \begin{table}[htp!] \centering \resizebox{\columnwidth}{!}{ \begin{tabular}{lccc} Features & Sig & Non-sig \\\hline\hline $\{$time, MMSE$\}$ & 0.626(0.009) & 0.574(0.022) \\ $\{$time, MMSE, meds$\}$ & 0.621(0.011) & 0.571(0.019) \\ \hline \end{tabular}} \caption{Harell's C-index measure of four models. Values reported as mean(std) over 5-fold cross validation.} \label{tab:results} \end{table} \noindent We also estimated the time-dependent area under the curve of receiver operating characteristics \cite{lambert2016summary}. It is a natural extension of a common AUC ROC analysis to possibly censored survival times where the patients' cognitive health is usually better at the very first visit to a memory clinic, while their condition may deteriorate later. The time-dependent cumulative dynamic AUC ROC of all four models are presented in Fig. \ref{fig:auc}. The signature features outperformed the non-signature ones at all times and the inclusion of sequential information from switching medications improved AUC ROC at later times. However, both models struggle to reliably predict the future outcomes further than 3 years. This is due to the limitation of predictors and the available number of patients after 3 years rather than the capacity of our model. \begin{figure}[htp!] \centering \includegraphics[width=0.48\textwidth, height=5cm]{artwork/time_dep_auc_test_2_new.pdf} \caption{Time-dependent AUC of risk prediction over time since the first admission to a memory clinic.} \label{fig:auc} \end{figure} \vspace{-0.0cm} \section{Discussion and future direction} Unstructured longitudinal electronic health records, such as free-text clinical notes, inherently contain rich information about patients' health and outcomes over time. The right analytical tools capable of capturing sequential information can therefore maximise utilisation of longitudinal EHRs and can be valuable for supporting clinical decisions and prognostic models. In this work we implemented a signature-based approach to represent chronological events extracted using natural language processing from clinical notes. Extracted chronological events can be seen as a trajectory (path) embedded in a high-dimensional multi-modal space of events (i.e. different medications, interventions, measures, etc) and the signature uniquely characterises the path in the most succinct way. The signature-based feature extraction approach was compared to hand-crafted features, comprising a slope and an intercept of MMSE scores over time and the median number of medications for each patient. The signatures represent a hierarchical collection of features, where the first order is proportional to linear statistical moments (i.e. mean) and is not sensitive to the order of data points, as illustrated in Table \ref{tab:log_sig_of_paths}. We demonstrated that the sequential information about medications has significantly improved the time-demented AUC as captured by the signatures (Figure \ref{fig:auc}). In future works we will extend the proposed framework to include the structured information available in EHR (i.e. lab results, coded procedures or clinical encounters) and will develop an interpretability framework to make the signature-based models explainable. \section*{Acknowledgments} The study was funded by the National Institute for Health Research’s (NIHR) Oxford Health Biomedical Research Centre (BRC-1215-20005). This work was supported by the UK Clinical Records Interactive Search (UK-CRIS) system funded and developed by the NIHR Oxford Health BRC at Oxford Health NHS Foundation Trust and the Department of Psychiatry, University of Oxford. AK, NV, QL, ANH are funded by the MRC Pathfinder Grant (MC-PC-17215). HN was supported by the Alan Turing Institute under the EPSRC grant EP/N510129/1 and under the EPSRC EP/S026347/1. The views expressed are those of the authors and not necessarily those of the UK National Health Service, the NIHR, or the UK Department of Health. We highly appreciate the work and support of the Oxford CRIS Team: Tanya Smith, Lulu Kane, Adam Pill and Suzanne Fisher and Dr Peter Phiri of the Southern Health NHS Foundation Trust CRIS team. \bibliographystyle{acl_natbib}
{'timestamp': '2020-10-27T01:20:20', 'yymm': '2010', 'arxiv_id': '2010.08433', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08433'}
arxiv
\section{Introduction} \label{sectionIntro} Modern software development is typically guided by software engineering principles that have been developed and refined for decades~\cite{van2008software}. Even though such principles are yet to come to full fruition regarding the development of machine learning (ML) applications, in recent years we have witnessed a surge of work focusing on ML usability through supporting efficient ML systems~\cite{mulee-parameterSever,mllib, zaharia2018accelerating}, enhancing developer's productivity~\cite{bergstra2013hyperopt, baylor2017tfx,li2017hyperband}, and supporting the ML application development process itself~\cite{vartak2016modeldb, Northstar, polyzotis2019data, nakandala2019incremental, nakandala2020cerebro, hubis2019quantitative,CI, renggli2020model}. \paragraph*{\underline{Calls for a Feasibility Study of ML}} In this paper, we focus on one specific ``failure mode'' that we frequently witness whilst working with a range of domain experts, which we call ``{\em unrealistic expectations}.'' Unlike classical software artifacts, the quality of ML models (e.g., its accuracy) is often a reflection of the \textit{data quality} used to train or test the model. We regularly see developers that work on challenging tasks with a dataset that is \textit{too} noisy to meet the unrealistically high expectations on the accuracy that can be achieved with ML --- such a project is predestined to fail. Ideally, problems of this type should be caught \emph{before} a user commits significant amount of resources to train or tune ML models. In practice, if this were done by a \textit{human ML consultant}, she would first analyze the representative dataset for the defined task and assess the \textit{feasibility} of the target accuracy --- if the target is not achievable, one can then explore alternative options by refining the dataset, the acquisition process, or investigating different task definitions. Borrowing the term from classic software engineering, we believe that such a \textit{feasibility study} step is crucial to the usability of future ML systems for application developers. In this paper, we ask: \textit{Can we provide some systematic and theoretically understood guidance for this feasibility study process?} \paragraph*{\underline{Quantitative Understanding of ``Data Quality for ML''}} Data quality, along with its cleaning, integration, and acquisition, is a core data management problem that has been intensively studied in the last few decades~\cite{cong2007improving, chiang2008discovering, sadiq201120, fan2015data, abedjan2016detecting, schelter2018automating, ilyas2019data}. Agnostic to ML workloads, the data management community has been conducting a flurry of work aimed at understanding and quantifying data quality issues~\cite{wang1996beyond, strong1997data,scannapieco2002data,batini2009methodologies}. In addition to these fundamental results, the presence of an ML training procedure as a downstream task over data provides both challenges and opportunities. On the one hand, systematically mapping these challenges to ML model quality issues is largely missing (with the prominent exceptions of ~\cite{krishnan2016activeclean, ghorbani2019data, wu2020complaint} together with some of our own previous efforts~\cite{li2019cleanml, jia2019towards, jia2019efficient, karlavs2020nearest}). On the other hand, the ML training procedure provides a quantitative metric to measure precisely the utility of data, or its quality. In this paper, we take one of the early steps in this direction and ask: ``\textit{Can we quantitatively map the quality requirements of a downstream ML task to the requirements of the data quality of the upstream dataset?}'' \paragraph*{\underline{The Scope and Targeted Use Case}} As one of the first attempts towards understanding this fundamental problem, this paper by no means provides a complete solution. Instead, we have a very specific application scenario in mind for which we develop a deep understanding both theoretically and empirically. Specifically, we focus on the case in which a user has access to a dataset $\mathcal{D}$, large enough to be representative for the underlying task. The user is facing the following question: {\em Is my current data artefact $\mathcal{D}$ clean/good enough for \underline{some} ML models to reach a target accuracy $\alpha_\text{target}$? } If the answer to this question is ``Yes'', the user can start expensive AutoML runs and hopefully can find a model that can reach $\alpha_\text{target}$; otherwise, it would be better for the user to improve the \textit{quality} (via data cleaning for example) of the data artefact $\mathcal{D}$ before starting an AutoML run which is ``doomed to disappoint''. We call the process of answering this question a ``\textit{feasibility study}''. Our main goal is to derive a strategy for the feasibility study that is \textbf{(i)} \textit{informative and theoretically justified}, \textbf{(ii)} \textit{inexpensive}, and \textbf{(iii)} \textit{scalable}. Such a process can be useful in many scenarios. In this paper we develop a fundamental building block of the feasibility study and evaluate it focusing on one specific use case as follows --- the dataset $\mathcal{D}$ is noisy in its labels, probably caused by (1) the inherent noise of the data collection process such as \textit{crowd sourcing}~\cite{compton2012developing, gadiraju2015understanding,checco2018all,sun2020improving}, or (2) \textit{bugs} in the data preparation pipeline (which we actually see quite often in practice). The user has a target accuracy $\alpha_\text{target}$ and can spend time and money on two possible operations: (1) manually clean up some labels in the dataset, or (2) find and engineer suitable ML models, manually or automatically. \paragraph*{\underline{Challenges of the Strawman}} There are multiple strawman strategies, each of which has its own challenge. A natural, rather trivial approach is to run a \textit{cheap proxy model}, e.g., logistic regression, to get an accuracy $\alpha_\text{proxy}$, and use it to produce an estimator $\alpha_\text{est}=c\cdot\alpha_\text{proxy}$, say, for some $c \in [1, 1/\alpha_\text{proxy}]$. The challenge of this approach is to pick a universally good constant $c$, which depends not only on the data but also on the cheap proxy model. It is important, but often challenging, to provide a principled and theoretically justified way of adjusting the gap between $\alpha_\text{proxy}$ and $\alpha_\text{est}$. An alternative approach would be to simply fire up an AutoML run that systematically looks at various configurations of ML models and potentially neural architectures. Given enough time and resources, this could converge closely to the best possible accuracy that one can achieve on a given dataset; nevertheless, this can be very expensive and time consuming, thus might not be suitable for a quick feasibility study. \paragraph*{\underline{Feasibility Study: Theory vs. Practice}} The main challenges of the strawman approaches motivate us to look at this problem in a more principled way. From a theoretical perspective, our view on feasibility study is not new, rather it connects to a decades-old ML concept known as the Bayes error rate (BER)~\cite{Cover1967-zg}, \textit{the ``irreducible error'' of a given task} corresponding to the error rate of the \textit{Bayes optimal classifier}. In fact, all factors leading to an increase of the BER can be mapped to classical data quality dimensions (e.g., ``label noise'' to ``accuracy'', or ``missing features '' to ``completeness'')~\cite{renggli2021data}. Estimation of the BER has been studied intensively for almost half a century by the ML community~\cite{Fukunaga1975-zx,Devijver1985-gs,Fukunaga1987-lw,buturovic1992improving,Pham-Gia2007-xa,Berisha2016-yl, sekeh2020learning}. Until recently, most, if not all, of these works are mainly theoretical, evaluated on either synthetic and/or very small datasets of often small dimensions. Over the years, we have been conducting a series of work aimed at understanding the behavior of these BER estimators on larger scale, real-wold datasets. This paper builds on two of these efforts, notably (1) a framework to compare BER estimators on large scale real-world datasets with unknown true BER~\cite{renggli2021evaluating}, and (2) new convergence bounds for a simple BER estimator on top of pre-trained transformations~\cite{rimanic2020convergence}. Guided by the insights and theoretical understanding we gained from these prior works, which we treat as preliminaries and do not see them as a technical contribution of this work, we ask the following non-trivial questions: \begin{quote} \em Q1. How to use estimations of the BER for the purpose of systematic feasibility study for ML? \end{quote} \begin{quote} \em Q2. How can we build a scalable system to make decades of theoretical research around the BER practical and feasible on real-world datasets? \end{quote} \paragraph*{\underline{Summary of Contributions}} We present \texttt{Snoopy}\xspace --- a fast, practical and systematic feasibility study system for machine learning. We make three technical contributions. \paragraph*{\bf C1. Systems Abstractions and Designs} In \texttt{Snoopy}\xspace, we model the problem of feasibility study as estimating a \emph{lower bound} of the BER. Users provide \texttt{Snoopy}\xspace with a dataset representative for their ML task along with a target accuracy. The system then outputs a binary signal assessing whether the target accuracy is realistic or not. Being aware of failures (false-positives and false-negatives) in the binary output of our system, which we carefully outline and explain in this paper, we support the users in deciding on whether to ``trust'' the output of our system by providing additional numerical and visual aids. The technical core is a practical BER estimator. We propose a simple, but novel approach, which consults a collection of different BER estimators based on a 1NN estimator inspired by Cover and Hart\cite{Cover1967-zg}, built on top of a collection of pre-trained feature transformations, and aggregated through taking the minimum. We provide a theoretical analysis on the regimes under which this aggregation function is justified. \paragraph*{\bf C2. System Optimizations} We then describe the implementation of \texttt{Snoopy}\xspace, with optimizations that improve its performance. One such optimization is the \emph{successive-halving} algorithm~\cite{jamieson2016non}, a part of the textbook Hyperband algorithm~\cite{li2017hyperband}, to balance the resources spent on different estimators. This already outperforms naive approaches significantly. We further improve on this method by taking into consideration the convergence curve of estimators, fusing it into a new variant of successive-halving. Moreover, noticing the iterative nature between \texttt{Snoopy}\xspace and the user, we take advantage of the property of kNN classifiers and implement an incremental version of the system. For scenarios in which a user cleans some labels, \texttt{Snoopy}\xspace is able to provide real-time feedback (0.2 ms for 10K test samples and 50K training samples). \paragraph*{\bf C3. Experimental Evaluation} We perform a thorough experimental evaluation of \texttt{Snoopy}\xspace on 6 well-known datasets in computer vision and text classification against the baselines that use cheap and expensive proxy models. We show that \texttt{Snoopy}\xspace consistently outperforms the cheap, and matches the expensive strategy in terms of predictive performance for synthetic and natural label noise, whilst being computational much more efficient than both approaches. In an end-to-end use-case, where noisy datasets are iteratively cleaned up to a fraction required to achieve the target, our system enables large savings in terms of overall cost, especially in cheap label-cost regimes. In label-cost dominated regimes (i.e., large label costs or cheap compute costs), our system adds little to no overhead compared to the baselines. Furthermore, by exploring the regimes in which \texttt{Snoopy}\xspace fails to provide a correct answer, we show the benefits of additional signals given to the user. \paragraph*{\underline{Limitations}} In this paper we focus on the challenging endeavor of estimating the \emph{irreducible error} for the task definition and data acquisition process, originating from data quality issues. We focus on label noise, representing one of the most prominent source for non-zero irreducible error. The exploration of other aspects of poor data quality, such as noisy or incomplete features, are left as future work. We by no means provide a conclusive solution to prevent unrealistic or very costly endeavors of training ML models with finite data. Rather, we view our contribution as a first step towards a practical treatment of this problem, which is the key for enabling a systematic feasibility study for ML. Concretely, we focus on classification tasks which, compared to other ML tasks, benefit of a solid theoretical understanding of the irreducible error and ways of estimating it. As a result, in Section~\ref{secPreliminaries} we carefully describe limiting assumptions on the data distributions, as well as failure causes and failure examples, presented in Sections~\ref{sectionSystemDesign} and~\ref{sec:experiments} respectively, hoping that this can stimulate future research from the community. \paragraph*{\underline{Future Extension}} The feasibility study functionality targeted in this paper is ideal for new ML projects designed to replace existing ``classical'' code with certain accuracy. Nothing prevents data scientists and ML engineers to use \texttt{Snoopy}\xspace prior to any batch trained ML model though. This is particularly appealing in the context of data-centric AI, where the signal can be used to understand the impact of data actions (e.g., cleaning labels). For stream-based or continual learning there are some extra challenges. First, the window of data should typically be small in order to have a good representation of the current distribution, which renders an accurate estimation of the BER challenging. Secondly, it is unclear how a BER estimator can be designed to cope with adversarial examples. Both aspects represent interesting lines of future research. Finally, when understanding the impact of distributional drift, the test accuracy of a fixed model is typically inspected. Designing drift-aware BER estimator could to detect such a drift for any model on a distributional level is left as future work. \section{Preliminaries} \label{secPreliminaries} In this section, we give a short overview over the technical terms and the notation used throughout this paper. Let $\mathcal X$ be the feature space and $\mathcal Y$ be the label space, with $C\!=\!|\mathcal Y|$. Let $X\in\mathcal X,Y\in\mathcal Y$ be random variables. Let $p(X,Y)$ be their joint distribution, often simplified by $p(x,y)\!=\!p(X\!=\!x,\!Y\!=\!y)$. We define $\eta_y(x)\!=\!p(y|x)$ when $C>2$, and $\eta(x)\!=\!p(1|x)$ when $C\!=\!2$, assuming $\mathcal Y=\{0, 1\}$. \paragraph*{\underline{Bayes Error Rate}} \emph{Bayes optimal classifier} is the classifier that achieves the lowest error rate among all possible classifiers from $\mathcal X$ to $\mathcal Y$, with respect to $p$. Its error rate is called the \emph{Bayes error rate (BER)} and we denote it by $R_{X,Y}^*$, often abbreviated to $R_{X}^*$ when $Y$ is clear from the context. It can be expressed as $R_{X}^* = \mathbb{E}_{X} \big[ 1- \max_{y\in\mathcal Y} \eta_y(x) \big]$. \paragraph*{\underline{k-Nearest-Neighbor (kNN) Classifier}} Given a training set $\mathcal D_n:=\{ (x_1,y_1),\ldots,(x_n,y_n)\}$ and a new instance $x$, let $(x_{\pi(1)}, \ldots, x_{\pi(n)})$ be a reordering of the training instances by their distances from $x$, based on some metric (e.g., Euclidean or cosine dissimilarity). The \emph{kNN classifier} $h_{n,k}$ and its \emph{$n$-sample error rate} $(R_X)_{n,k}$ are defined by \vspace{-1em} \begin{align*} h_{n,k} (x) &= \mathop{\mathrm{arg\,max}}_{y\in\mathcal Y} \sum_{i=1}^{k} \mathbf{1}_{\{ y_{\pi(i)} = y\}},\\ (R_X)_{n,k} &= \mathbb{E}_{X,Y} \mathbf{1}_{\{ h_{n,k}(X) \neq Y\}}, \end{align*} respectively. The \emph{infinite-sample error rate} of kNN is given by $(R_X)_{\infty, k} = \lim_{n\rightarrow \infty} (R_X)_{n,k}$. Cover and Hart derived the following fundamental~\cite{Cover1967-zg}, and now well-known, relationship between the nearest neighbor algorithm and the BER (under mild assumptions on the underlying probability distribution): \begin{equation}\label{eqnCoverHart} \begin{tiny} (R_X)_{\infty,1 } \geq R_{X}^* \geq \frac{(R_X)_{\infty, 1}}{1+\sqrt{1-\frac{C (R_X)_{\infty, 1}}{C-1}}}. \end{tiny} \end{equation} Determining such a bound for $k>1$ and $C>2$ is still an open problem, and in this work we mainly focus on $k=1$. \begin{figure*}[t!] \centering \includegraphics[width=0.9\textwidth]{figures/snoopy_illustration_final.png} \vspace{-1em} \caption{Overview of \texttt{Snoopy}\xspace: Given user's input in terms of a dataset and a target, the system consults various Bayes error estimators (yellow ticks), aggregates them by taking the minimum (green tick) and outputs its belief whether the target is realistic, together with the insights in terms of convergence plots, gap towards target accuracy, and estimated number of additional samples needed to reach the target accuracy.} \label{fig:snoopy_overview} \vspace{-1.5em} \end{figure*} \paragraph*{\underline{Bayes Error Estimation}} The task of estimating the BER, given a \emph{finite} representative dataset, is inherently difficult and has been investigated by the ML community for decades --- from Fukunaga's early work in 1975~\cite{Fukunaga1975-zx} to Sekeh et al.'s work in 2020~\cite{sekeh2020learning}. Existing BER estimators can be divided into three groups: \emph{density estimators} (\emph{KDE}~\cite{Fukunaga1987-lw}, \emph{DE-kNN}~\cite{Fukunaga1973-wg}), \emph{divergence estimator} (\emph{GHP}~\cite{sekeh2020learning}), \emph{kNN classifier accuracy} (\emph{1NN-kNN}~\cite{Devijver1985-gs}, \emph{kNN-Extrapolation}~\cite{Snapp1996-fe}, 1NN inspired by~\cite{Cover1967-zg}). As mentioned earlier, we have been conducting a series of work in order to understand the theoretical and empirical behavior of deploying and comparing BER estimators on larger scale, real-world datasets, using powerful pre-trained embeddings. This paper builds on these efforts~\cite{renggli2021evaluating, rimanic2020convergence} but treats them as preliminaries --- they provide important insights into many decisions in our system, but they do not count as the technical contribution of this paper. We next summarize these efforts and the gained insights. \subsection{Evaluating Bayes Error Estimators on Real-World Datasets} Evaluating the relative performance of BER estimators on real-world dataset is far from trivial. In one of our previous endeavor~\cite{renggli2021evaluating}, we proposed \texttt{FeeBee}, a novel framework for evaluating BER estimators on real-world data. The key insights for building such a framework lies in the realization that evaluating BER estimators on a single point for tasks with unknown true BER is infeasible. Rather, one has to construct a series of points, for which the evolution of the BER is known. We do so by injecting uniformly distributed noise over the labels for different amounts of label noise and following the evolution of the BER through the following theoretical result. \begin{lem}[From~\cite{renggli2021evaluating}]\label{lemLabelFlipping} Let $Y_\rho$ be a random variable defined on $\mathcal Y$ by setting $Y_\rho = Z \cdot U(\mathcal Y) + (1-Z) \cdot Y,$ where $U$ is a uniform variable taking values in $\mathcal{Y}$, and $Z$ is a Bernoulli variable with probability $0 \leq \rho \leq 1$, both independent of $X$ and $Y$. Then $R_{X, Y_\rho}^* = R_{X,Y}^* + \rho(1-1/C-R_{X,Y}^*).$ \end{lem} The above lemma is sufficient in determining the strength of each BER estimator~\cite{renggli2021evaluating}. However, in order to apply a BER estimator in a system for a feasibility study in real-world datasets, where human annotators typically introduce more noise for classes which are harder to distinguish, we need to be able to go beyond uniform noise. Therefore, in Section~\ref{sec_noise_beyond_uniform} we provide a generalization that does not assume uniform label noise. As a major finding of \texttt{FeeBee}, we established that the \emph{1NN}-based estimator is a powerful one --- on par or better than all other estimators when it comes to performance, whilst being highly scalable and insensitive to hyper-parameters~\cite{renggli2021evaluating}. In this paper, \emph{1NN}-based estimator on top of a feature transformation is our default choice. For a fixed transformation $f$, and $n$-samples, it is defined by \vspace{-1em} \begin{equation}\label{eqn:1nn_estimator} \begin{small} \widehat{R}_{f(X),n} = \frac{(R_{f(X)})_{n, 1}}{1+\sqrt{1-\frac{C (R_{f(X)})_{n, 1}}{C-1}}}. \end{small} \end{equation} \subsection{On Convergence of Nearest Neighbor Classifiers over Feature Transformations} Since our estimator will combine the 1NN algorithm with pre-trained feature transformations, also called \textit{embeddings}, such as those publicly available, we need to understand the influence of such transformations. In our theoretical companion to this paper~\cite{rimanic2020convergence}, we provide a novel study of the behavior of a kNN classifier on top of a feature transformation, in particular its convergence rates on \emph{transformed} data, previously known only for the \emph{raw} data.\footnote{We restrict ourselves to $C=2$, as usual in theoretical results about the convergence rates of a kNN classifier.} We prove the following theorem, recalling that a real-valued function $g$ is \emph{$L$-Lipschitz} if $|g(x) - g(x')| \leq L \| x - x'\|$, for all $x,x'$, and defining $\mathcal L_{g}(f) := \mathbb{E}_X[(g \circ f)(X) - \eta(X)]^2.$ \begin{thm}[From~\cite{rimanic2020convergence}]\label{thm_theory_MainThm} Let $\mathcal X \subseteq \mathbb{R}^D$ and $\widetilde \cX\subseteq \mathbb{R}^d$ be bounded sets, and let $(X,Y)$ be a random vector taking values in $\mathcal X \times \{0,1\}$. Let $\func[g]{\widetilde \cX}{\mathbb{R}}$ be an $L_g$-Lipschitz function. Then for all transformations $\func{\mathcal X}{\widetilde \cX}$,\vspace{-0.2em} \begin{align}\label{eqnConvRatesThm} &\mathbb{E}_n \left[ (R_{f(X)})_{n,k}\right] - R_{X}^* \nonumber \\ &\hspace{5mm}=\mathcal O \left( \frac{1}{\sqrt{k}}\right) + \mathcal O\Big( L_g \left( \frac{k}{n}\right)^{1/d} \Big) + \mathcal O\left( \sqrt[4]{\mathcal L_{g}(f)} \right). \end{align} \end{thm} Motivated by the usual architecture of trained embeddings, in Theorem~\ref{thm_theory_MainThm} one should think of $g$ as a softmax prediction layer with weights $w$, which allows taking $L_g = \| w\|^2$. Equation~\ref{eqnConvRatesThm} shows that there is a trade-off between the improved convergence rates (in terms of $L_g$ and $d$) and the bias introduced by the transformation independent of kNN. \section{Design of \texttt{Snoopy}\xspace} \label{sectionSystemDesign} We next present the design of \texttt{Snoopy}\xspace. A high-level overview of the workflow of our system is given in Figure~\ref{fig:snoopy_overview}. \paragraph*{\underline{Functionality}} \texttt{Snoopy}\xspace~interacts with users in a simple way. The user provides an input dataset that is representative for the classification task at hand, along with a target accuracy $\alpha_\text{target}$. The system then estimates the ``highest possible accuracy'' that an ML model can achieve, and outputs a binary signal --- \texttt{REALISTIC}, if the system deducts that this target accuracy is achievable; \texttt{UNREALISTIC}, otherwise. We note that \texttt{Snoopy}\xspace does not provide a model that can achieve that target, only its \textit{belief} on whether the target is achievable, using an \emph{inexpensive} process. Furthermore, the goal of \texttt{Snoopy}\xspace~is \textit{not} to provide a perfect answer on feasibility, but to give information that can guide and help with the decision-making process --- the signal provided by the system may as well be wrong, as we will discuss later. The best possible accuracy is implicitly returned to the user in the form of the gap between target and projected accuracy (c.f., Section~\ref{sec:additional_guidance}). \paragraph*{\underline{Interaction Model}} The binary signal of \texttt{Snoopy}\xspace given to a user is often correct, but not always. We now dive into the user's and \texttt{Snoopy}\xspace's interaction upon receiving the signal. \textit{The Case When \texttt{Snoopy}\xspace Reports \texttt{REALISTIC}}: In general, one should trust the system's output when it reports the target to be realistic, and proceed with running AutoML. We note that wrongly reporting realistic can be a very costly mistake which any feasibility system should try to avoid. In theory, our system could also be wrong in that fashion, due to (1) a lower bound estimate based on the 1NN estimator by Cover and Hart~\cite{Cover1967-zg} that is known to be not always tight, or (2) the fact that the estimators are predicting asymptotic values. However, as presented in the next section, we construct our estimator in a theoretically justified way that aims at reducing such mistakes and in our experiments we do not observe this behavior. Even if this were the case, we expect (2) to be the dominating reason, in which case gathering more data for the task at hand and running AutoML on this larger dataset might very well confirm the system's prediction. \textit{The Case When \texttt{Snoopy}\xspace Reports \texttt{UNREALISTIC}}: In this case, our experiments showed that the system's output is also trustworthy, but with more caution. Under reasonable computational resources\footnote{For instance, reproducing the state-of-the-art model performance for well-established benchmark datasets is often a highly non-trivial task.}, \texttt{Snoopy}\xspace is often correct in preventing unrealistic expectations for a varying amount of both synthetic and natural label noise. Nonetheless, there are two possible reasons for making wrong predictions in this manner: (1) either the data is not representative enough for the task (i.e., users might need to acquire more data), or (2) the transformations applied in order to reduce the feature dimension, or to bring raw features into a numerical format in the first place (e.g., from text), increased the BER.\footnote{We have shown in our theoretical companion~\cite{rimanic2020convergence} that any deterministic transformation can only increase the BER.} We note that (1) and (2) are complementary to each other. Even though estimating the BER on raw features (if applicable) prevents (2) from happening, having ``better'' transformations can lower the number of samples required to accurately estimate the BER. In an ideal world, one could rule out (1) by checking whether the BER estimator converged on the given number of samples. That is why \texttt{Snoopy}\xspace provides insights in terms of convergence plots and finite-sample extrapolation numbers to help users understand the relation between increasing number of samples and BER estimate, giving insights into the \emph{source} of predicting \texttt{UNREALISTIC}, and increase the confidence in the prediction. \subsection{Data Quality Issues and the BER}\label{sec_noise_beyond_uniform} The power of the BER, and the reason that \texttt{Snoopy}\xspace focuses on estimating this quantity, is that it provides a link connecting data quality to the performance of (best possible) ML models. This link can be made more explicit, even in closed form, if we assume some noise model. We take one of the most prominent source of data quality issues, label noise, as an example, and illustrate this connection via a novel theoretical analysis. \paragraph*{\underline{Noise Model}} We focus on a standard noise model: class-dependent label noise~\cite{wei2022learning}. We assume that we are given a noisy random variable $Y_\rho$ through a transition matrix $t$ with \vspace{-0.5em} \begin{equation}\label{eqn_transition_matrix} t_{\widetilde y,y} := \mathbb P (Y_\rho = \widetilde y \ | Y = y, X = x) = \mathbb P (Y_\rho = \widetilde y \ | Y = y), \vspace{-0.5em} \end{equation} where the equality follows from the assumption that we are in the class-dependent label noise scenario, rather than in instance-dependent one. One can think of $\rho (y) = 1 - t_{y, y}$ to be the fraction of class $y$ that gets flipped. Let $y_x := \mathop{\mathrm{arg\,max}}_{y\in \mathcal Y} p(Y=y | x)$. We further assume that $y_x = \mathop{\mathrm{arg\,max}}_{y \in \mathcal Y} p_\rho (Y_\rho =y | x)$, meaning that the maximal label per sample $x$ is preserved after flipping, albeit possibly with lower probability (which then increases the BER). Our main result is the following theorem. \begin{thm}\label{thm_flipping} Let $Y_\rho$ be a random variable taking values in $\mathcal Y$ that satisfies (\ref{eqn_transition_matrix}). Then \vspace{-0.5em} \begin{align*} R_{X, Y_\rho}^* &= R_{X,Y}^* + \mathbb{E}_X [\rho (y_x) p(y_x | x)] - \sum_{y \neq y_x} \mathbb{E}_{X} \left[ t_{y_x, y} p (y | x) \right] \end{align*} \end{thm} One can prove Theorem~\ref{thm_flipping} using the law of total expectation, together with careful manoeuvring of the terms that involve the elements of the transition matrix.\footnote{We provide the full proof and additional discussion in the Appendix~\ref{app:label_flipping}.} Setting $\rho(y) = \rho \cdot \left( 1- 1/C \right)$, for all $y\in \mathcal Y$, and $t_{y,y'} = \rho / C$, for all $y' \neq y$, recovers Lemma~\ref{lemLabelFlipping}, and one can further deduct the following valid bounds on the evolution of the BER: \vspace{-0.5em} \begin{align*} (1-s_{X,Y}) \min_{y}\rho(y) - s_{X,Y} \max_{y,y': y\neq y'} t_{y,y'} \leq \\ R_{X,Y_\rho}^* \leq s_{X,Y} + \max_{y}\rho(y), \end{align*} where $s_{X,Y}$ denotes the error of state-of-the-art model. \paragraph*{\underline{Other Data Quality Dimensions}} Whilst we assume that the BER for zero label noise is typically small, it does not have to be equal to zero (c.f.,~\cite{renggli2021data} for examples). Nonetheless, by estimating the BER, we implicitly quantify the data quality issues along \textit{all} dimensions (e.g., missing features, or combinations of feature and label noise). Deriving alternative noise models to theoretically and empirically disentangling these factors is a challenging task and left as future work. \section{Implementation} \label{sectionSystemImplementation} The core component of \texttt{Snoopy}\xspace is a BER estimator, which estimates the irreducible error of a given task. The key design decision of \texttt{Snoopy}\xspace is to \emph{consult a collection of BER estimators and aggregate them in a meaningful way.} More precisely, for a collection of feature transformations $\mathcal F$, e.g., publicly available pre-trained feature transformations (or last-layer representations of pre-trained neural networks) on platforms like TensorFlow Hub, PyTorch Hub, and HuggingFace Transformers, we define our main estimator of the BER (on $n$ samples) using Equation~\ref{eqn:1nn_estimator} by \vspace{-0.5em} \[ \widehat{R} = \min_{f \in \mathcal F}\widehat{R}_{f(X),n}. \vspace{-0.5em} \] Finally, the system's output is \vspace{-0.5em} \begin{align*} \texttt{REALISTIC}, &\hspace{3mm}\text{ if } \widehat{R} \leq 1- \alpha_\text{target}, \\ \texttt{UNREALISTIC}, &\hspace{3mm}\text{ otherwise.} \vspace{-0.5em} \end{align*} \subsection{``Just a Lightweight AutoML System?''} At first glance, our system might seem like a ``lightweight AutoML system,'' which runs a collection of fast models (e.g., kNN classifiers) and takes the minimum to get the best possible classifier accuracy. We emphasize the difference --- the accuracy of an AutoML system always corresponds to a concrete ML model that can achieve this accuracy; however, a BER estimator does \textit{not} provide this concrete model. That is, \texttt{Snoopy}\xspace~does \textit{not} construct a model that can achieve $\widehat{R}$. This key difference between AutoML and feasibility study makes the latter inherently more computationally efficient, with almost instantaneous re-running, which we will further illustrate with experiments in Section~\ref{sec:endtoend}. \subsection{Theoretical Analysis} \label{sectionTheoreticalAnalysis} Given a collection of 1NN-based BER estimators over feature transformations, \texttt{Snoopy}\xspace~aggregates them by taking the minimum. This seemingly simple aggregation rule is far from trivial, raising obvious questions --- \textit{Why can we aggregate BER estimators by taking the minimum?} \textit{When will this estimator work well and when will it not?} In order to mathematically quantify different regimes, we need a few simple definitions. , which we illustrate in Appendix~\ref{app:justifications_min} of the supplementary material. We define the \emph{asymptotic tightness} of our estimator for a fixed transformation $f$ as \vspace{-0.5em} \begin{equation} \Delta_f = R_{f(X)}^* - \lim_{n\rightarrow \infty} \widehat{R}_{f(X),n}. \vspace{-0.5em} \end{equation} Equation~\ref{eqnCoverHart} implies $\Delta_f \geq 0$. We define the corresponding \emph{transformation bias} by \vspace{-0.5em} \begin{equation} \delta_f = R_{f(X)}^* -R_{X}^*, \vspace{-0.5em} \end{equation} with $\delta_f \geq 0$ (by~\cite{rimanic2020convergence}). Finally, the \emph{n-sample gap (of the estimator)} is given by \vspace{-0.5em} \begin{equation} \gamma_{f,n} = \widehat{R}_{f(X),n} - \lim_{n\rightarrow \infty}\widehat{R}_{f(X),n}, \vspace{-0.5em} \end{equation} with $\gamma_{f,n} \geq 0$ in expectation (also by~\cite{rimanic2020convergence}). The fundamental challenge lies in the fact that none of the three quantities above can be derived in practice: $\Delta_f$ is dependent on the underlying unknown distribution, $\delta_f$ is intractable for complex neural networks~\cite{rimanic2020convergence}, and $\gamma_{f,n}$ relies on the convergence of the estimator, which requires the number of samples to be exponential in the input dimension~\cite{Snapp1996-fe}, making it impossible to generalize to representations on real-world datasets. Nevertheless, the connection between the quantities, together with the empirical analysis from \cite{renggli2021evaluating} and Section~\ref{sec:experiments} of this work, allows us to define meaningful regimes next. \textit{\underline{When is $\widehat{R}$ optimal?}} In other words, when does the transformation that yields the minimum outperform all the others? A sufficient condition \footnote{We prove the condition to be sufficient in Appendix~\ref{app:justifications_min} in the supplementary material.} is given by \vspace{-0.7em} \begin{equation} \label{eqnCase1} \forall f \in \mathcal F:\quad \delta_f + \gamma_{f,n} - \Delta_f \geq 0. \vspace{-0.5em} \end{equation} If the sum of finite-sample gap and transformation bias (i.e., the normalized constants of the second and third terms in Equation~\ref{eqnConvRatesThm}) is larger than the asymptotic tightness of the estimator (i.e., the normalized constants of the first term in Equation~\ref{eqnConvRatesThm}) for all transformations, then all estimators yield a number larger than the true BER, and therefore the minimum can be taken. Intuitively, this means that all the curves in the convergence plot are above the true BER. We note that this has to include the identity transformation, where there is no transformation bias. If Condition~\ref{eqnCase1} holds, $\widehat{R}$ \textit{will not underestimate the BER}. The above trivially holds if for all $f\in \mathcal F$ one has $\Delta_f = 0$. Note that any classifier accuracy (non-scaled, to be used as proxy) also trivially falls into this regime, although it is usually worse than $\widehat{R}$. Furthermore, the system is guaranteed to not predict YES when the target is unreachable, thus avoiding costly mistakes. If the system wrongly predicts UNREALISTIC, it is guaranteed that its predicted error is off by at most $\delta_f + \gamma_{f,n} - \Delta_f$. We note that all empirical evidence in Section~\ref{sec:experiments} and in our companion work on BER evaluation framework~\cite{renggli2021evaluating} suggests that we are in this regime for reasonable label noise (e.g., less than 80\%) on a wide range of datasets and transformations. \begin{figure}[t!] \centering \includegraphics[width=0.92\linewidth]{figures/feebee_for_snoopy_cifar10_1nn_and_lr.pdf} \vspace{-1em} \caption{Theoretical justifications: (Left) 1NN error and its estimator values for raw features and the best transformation. (Right) Scaling down the logistic regression error on the best transformation and normalizing it by plugging it into the 1NN estimator of Equations~\ref{eqn:1nn_estimator}. Notice that the solid green and solid pink line are identical in the right plot, leading to a dark purple line.} \label{fig:feebee_for_snoopy_cifar10_1nn_and_lr} \vspace{-1.5em} \end{figure} \textit{\underline{What if $\widehat{R}$ is not optimal?}} We distinguish two different cases in this regime. In the first one, we suppose that the suggested estimator $\widehat{R}_{X,\infty}$ of Cover and Hart~\cite{Cover1967-zg} on the \emph{raw} features performs well in the asymptotic regime, i.e. that $\Delta_{id}$ is small. In that case, a sufficient condition for $\widehat{R}$ to be at least as good as $\widehat{R}_{X,\infty}$ is $\Delta_f \leq \Delta_{id}$, for all $f \in \mathcal F$. Intuitively, this states that if all transformations do not increase the asymptotic tightness of the estimator by transforming the underlying probability distribution with respect to the raw distribution, taking the minimum over all transformations is no worse than running the estimator with 1NN on infinite samples. This condition can be seen empirically by inspecting the linear shape of the 1NN-based BER estimator values with increasing label noise for different transformations (c.f., Figure~\ref{fig:feebee_for_snoopy_cifar10_1nn_and_lr} on the left). One could weaken the condition for the finite-sample regime, resulting in a sufficient condition for $\widehat{R}$ to perform better than $\widehat{R}_{X,\infty}$: \vspace{-0.5em} \begin{equation} \label{eqnCase2} \forall f \in \mathcal F:\quad \delta_f + \gamma_{f,n} - \Delta_f + \Delta_{id} \geq 0. \vspace{-0.5em} \end{equation} For the second case, when $\widehat{R}$ performs poorly, we ask: \emph{What is the worst-case error of underestimation?} Using the fact that 1NN error is trivially above the true BER (c.f., left inequality of Equation~\ref{eqnCoverHart}), we can bound the difference of the 1NN-Based estimator value. In fact, the estimator value is at most the scaling factor of Equation~\ref{eqn:1nn_estimator} away from the true BER (i.e., $1/2$ for a binary classification problem). However, our analysis and empirical verification reveals that our estimator of choice rarely ends up in the worst-case scenario. In fact, $\widehat{R}$ is usually the optimal choice and, when it is not, we often end up in the regime in which $\widehat{R}_{X,\infty}$ already performs well and $\widehat{R}$ outperforms it. \paragraph*{\underline{Downscaling classifiers other than 1NN}} As the worst-case error holds for scaling down any classifier accuracy, one could be tempted to use a downscaled version (e.g., dividing by a constant $c>1$, or by plugging the error value in place of the 1NN error into the estimator of Equation~\ref{eqn:1nn_estimator}) of other classifiers as a proxy. Contrary to the 1NN-based estimators, it is easy to show that for many datasets, any scaled version of a proxy model accuracy quickly falls into this worst-case regime (c.f., Figure~\ref{fig:feebee_for_snoopy_cifar10_1nn_and_lr} on the right, or Figure 4b in ~\cite{renggli2021evaluating}), supporting the challenges of the Strawman outlined in the introduction. \subsection{Additional Guidance}\label{sec:additional_guidance} To support users of \texttt{Snoopy}\xspace in deciding whether to ``trust'' the output of the system, regardless of the outcome, additional information is provided. It comes in the form of (a) the estimated BER and, thus, the \emph{gap} between the projected accuracy and the target accuracy, (b) the convergence plots indicating the estimated BER value with respect to increased number of training samples over all deployed BER estimators (as illustrated in Figure~\ref{fig:snoopy_overview}), and (c) an additional estimate of the required number of additional samples to reach the target accuracy for the minimal transformation. Such an estimate is fairly non-trivial. Although Snapp et. al.~\cite{Snapp1996-fe} suggest how to approximate the kNN error by fitting a parametrized function to sampled data, the number of samples required to attain high confidence and accuracy is exponential in the feature dimension. This method is thus not practical for either finite-sample extrapolation, or estimating the BER, as shown in our companion work~\cite{renggli2021evaluating}. Instead, to support users of \texttt{Snoopy}\xspace beyond purely visual aids, we approximate the estimate based on the 1NN error using a simple log-linear function~\cite{hashimoto2021model} \vspace{-0.5em} \begin{align}\label{eqnApproxExtrap} \log\left((R_X)_{n,k}\right) \approx -\alpha \log\left(n\right) + C, \vspace{-0.5em} \end{align} for two positive constants $\alpha$ and $C$. The idea of approximating the error is motivated by recent observations of scaling laws across different deep learning modalities ~\cite{kaplan2020scaling, rosenfeld2020a}. Notice that Equation~\ref{eqnApproxExtrap} should only be used to extrapolate the convergence for a small number of additional data points. The function (i.e., the exponential of the righthand side of Equation~\ref{eqnApproxExtrap}) is known to converge to $0$, implying that regardless of the label noise or true BER, it will always underestimate the BER for a too large number of samples. We show the benefits and failures of using this approximation in Section~\ref{secExpAdditionalGuidance}. \section{System Optimizations} \label{sectionEfficientImplementation} The suggested and theoretically motivated estimator from the previous section relies on the 1NN classifier being evaluated on a possibly large collection of publicly available \emph{pre-trained} feature transformations. We present optimizations that improve the performance, making it more scalable. \paragraph*{\underline{Algorithm}} There are five computational steps involved: \begin{enumerate}[label=\textbf{(\roman*)},align=parleft,left=0pt..2em] \item Take user's dataset with $n$ samples: features $X_1, X_2, \dots, X_n$ and labels $Y_1, Y_2, \dots, Y_n$. \item For pre-defined $m$ transformations $\mathcal F = \{f_1, f_2, \dots, f_m\}$, calculate the corresponding features for every sample in the dataset by applying all the transformations in $\mathcal F$. \item For each feature transformation $j \in [m]$, calculate the 1NN classifier error $R_j=(R_{f_j(X)})_{n,1}$ on the transformed features $f_j(X_i)$, for all samples $i \in [n]$. \item Based on the 1NN classifier error, derive the lower-bound estimates $\widehat{R}_{f_j(X),n}$ using Equation~\ref{eqn:1nn_estimator}. \item Report the overall estimate $\widehat{R} = \min_{j \in [m]} \widehat{R}_{f_j(X),n}.$ \end{enumerate} Note that the dataset is split into training samples and test samples. The test set is only used to estimate the accuracy of the classifier and is typically orders of magnitude smaller than the training set. The quality of \texttt{Snoopy}\xspace~depends heavily on the list of feature transformations that are fed into it. Since we take the minimum over all transformations in $\mathcal F$, increasing the size of the set only \emph{improves} the estimator. On the downside, an efficient implementation is by no means trivial with an ever-increasing number of (publicly) available transformations. \paragraph*{\underline{Computational Bottleneck}} When analyzing the previously defined algorithm, we realize that the major computational bottleneck comes from transforming the features. Especially when having large pre-trained networks as feature extractors, running inference on large datasets, in order to get the embeddings, can be very time-consuming and result in running times orders of magnitude larger than the sole computation of the 1NN classifier accuracy. More concretely, given a dataset with $n$ samples and $m$ feature transformations, the worst case complexity is $\mathcal O(m n)$, which highlights the importance of providing an efficient version of the algorithm. \paragraph*{\underline{Multi-armed Bandit Approach}} Inspired by ideas for efficient implementation of the nearest-neighbor search on hardware accelerators~\cite{johnson2019billion}, running inference on all the training data for all feature transformations simultaneously is not necessary. Rather, we define a streamed version of our algorithm by splitting the steps (ii) to (iv) into iterations of fixed batch size per transformation. This new formulation can directly be mapped to a \textit{non-stochastic best arm identification} problem, where each arm represents a transformation. The successive-halving algorithm~\cite{jamieson2016non}, which is invoked as a subroutine inside the popular Hyperband algorithm~\cite{li2017hyperband}, is designed to solve this problem efficiently. We can summarize the idea of successive-halving as follows: Uniformly allocate a fixed initial budget across all transformations and evaluate their performance. Keep only the better half of the transformations, and repeat this until a single transformation remains. The full algorithm is explained in the supplementary material in Appendix~\ref{app_SH_tangents}. \begin{figure}[t!] \centering \includegraphics[width=0.62\linewidth]{figures/Improved_SH.png} \vspace{-1em} \caption{Improved Successive-Halving: At each point for each convergence curve we construct a tangent and check whether there are more than half of the remaining curves that are better than the tangent.} \label{fig:improved_SH} \vspace{-1.5em} \end{figure} \paragraph*{\underline{Improved Successive-Halving}} We develop a variant of successive-halving that further improves the performance. The main idea comes from observing the \emph{convergence curve} of a kNN classifier. We know that under some mild assumptions, the kNN error decreases as a function of $n^{-2/d}$, where $n$ is the number of samples~\cite{snapp1991asymptotic}. Therefore, we can assume that the convergence curve is decreasing and convex. This allows us to predict a simple lower bound for the convergence curve at the end of each step -- using the tangent through the curve at the last known point, as illustrated in Figure~\ref{fig:improved_SH}. If the tangent line at the end point is worse than half of the remaining curves at the current point, the curve will not proceed to the next round. To simplify the implementation, we approximate the tangent by a line through the two last-known values of the convergence curve and develop a variant of successive-halving that uses this as a stopping condition. An important property of our improvement is that the remaining transformations after each step are the same as the ones from the original successive-halving, which implies that all theoretical guarantees of successive-halving still hold. \paragraph*{\underline{Parameters of Successive-Halving}} We eliminate the dependency on the initial budget by implementing the \textit{doubling-trick} (cf. Section 3 in~\cite{jamieson2016non}). The batch size of the iterations has a direct impact on the performance and speedup of the algorithm. This is linked to properties of the underlying hardware and the fact that approximating the tangent for points that are further apart becomes less accurate. Hence, we treat the batch size as a single hyper-parameter, which we tune for all transformations and datasets. \paragraph*{\underline{Efficient Incremental Execution}} For the specific scenario of incrementally cleaning labels until a target accuracy is reachable, we provide a simple yet effective optimization that enables re-running \texttt{Snoopy}\xspace almost instantly. After its initial execution, the system keeps track of the label of a single sample per test point -- its nearest neighbor. As cleaning labels of test or training samples does not change the nearest neighbor, calculating the 1NN accuracy after cleaning any training or test samples can be performed by iterating over the test set exactly once, thus, providing real-time feedback. \begin{table}[t] \caption{Datasets and SOTA performances.\label{tbl:datasets}} \vspace{-1em} \centering \begin{tabular}{ lrrrr } \toprule Name & Classes $C$ & Train / Test Samples & SOTA \%\\ \midrule MNIST & 10 & 60K / 10K & 0.16~\cite{byerly2020branching} \\ CIFAR10 & 10 & 50K / 10K & 0.63~\cite{kolesnikov2019large}\\ CIFAR100 & 100 & 50K / 10K & 6.49~\cite{kolesnikov2019large}\\ \midrule IMDB & 2 & 25K / 25K & 3.79~\cite{yang2019xlnet}\\ SST2 & 2 & 67K / 872 & 3.2~\cite{yang2019xlnet}\\ YELP & 5 & 500K / 50K & 27.80~\cite{yang2019xlnet}\\ \bottomrule \end{tabular} \vspace{-2em} \end{table} \section{Experiments} \label{sec:experiments} We now present the results of our empirical evaluation by describing the benefits of performing a feasibility study in general, and using the binary output of \texttt{Snoopy}\xspace over other baselines. We focus on a specific use-case scenario motivated in the introduction. We also show how the additional guidance can increase trust in the binary signal. We then analyze the generalization properties of our system on certain vision tasks and conclude this section by performing a detailed performance analysis of \texttt{Snoopy}\xspace. The code of \texttt{Snoopy}\xspace is available via \url{https://github.com/easeml/snoopy}, whereas the code to reproduce the results can be found under~\url{https://github.com/DS3Lab/snoopy-paper}. \begin{figure*}[t!] \centering \includegraphics[width=0.92\textwidth]{figures/snoopy_baselines.png} \vspace{-1em} \caption{Error Estimations vs. Time on three synthetics noise levels. The dashed horizontal lines represent the expected increase of the SOTA using Lemma~\ref{lemLabelFlipping}.} \label{fig:snoopy_vs_baselines} \vspace{-1.5em} \end{figure*} \subsection{Experimental Setup} \paragraph*{\underline{Datasets}} We perform the evaluation on two data modalities that are ubiquitous in modern machine learning and are accompanied by strong state-of-the-art (SOTA) performances summarized in Table~\ref{tbl:datasets}. Implicitly, a strong SOTA yields a low natural BER (i.e., originating from all data quality dimensions). The first group consists of visual classification tasks, including CIFAR10~\cite{dosovitskiy2020image}, CIFAR100~\cite{foret2020sharpness}, and MNIST~\cite{byerly2021no}. The second group consists of standard text classification tasks, where we focus on IMDB, SST2, and YELP~\cite{yang2019xlnet}. We remark that the SOTA values for SST2 and YELP are provided on slightly different sizes of training sets. \begin{table}[t] \caption{CIFAR-N datasets statistics.\label{tbl:dataset_cifar-n} The variable $t_{i,j}$ refers to an element of the noise transition matrix $t$ (c.f., Section~\ref{sec_noise_beyond_uniform}).} \vspace{-1em} \centering \begin{tabular}{@{}lcccc@{}} \toprule Dataset & Noise & $\max_{i} t_{i,i}$ & $\min_{i} t_{i,i}$ & $\max_{i\neq j} t_{i,j}$ \\ \midrule CIFAR10-Aggre & 9\% & 17\% & 3\% & 10\% \\ CIFAR10-Random1 & 17\% & 26\% & 10\% & 23\% \\ CIFAR10-Random2 & 18\% & 26\% & 10\% & 23\% \\ CIFAR10-Random3 & 18\% & 26\% & 10\% & 23\% \\ CIFAR100-Noisy & 40\% & 85\% & 8\% & 31\% \\ \bottomrule \end{tabular} \vspace{-2em} \end{table} We mainly focus our study on datasets with noisy labels. The ML community usually works on high-quality, noise-free benchmark datasets. As an exception, Wei et. al.~\cite{wei2022learning} published different noisy variants of the popular CIFAR datasets, called CIFAR-N. The noise levels vary between 10\% and 40\% (c.f., Table~\ref{tbl:dataset_cifar-n}). The datasets are provided with their noise transition matrix, allowing us to use the bounds derived from Theorem~\ref{thm_flipping}. The assumption therein corresponds to the each diagonal element being the maximal value per row, which is given for all datasets. Supported by our theoretical understanding of the impact of label noise on the BER and its evolution, we also synthetically inject uniform label noise for 20\% and 40\% of the label into all six datasets from Table~\ref{tbl:datasets}. \paragraph*{\underline{Feature Transformations}} We compile a wide range of more than 15 different feature transformations per data modality, such as PCA and NCA~\cite{wu2018improving}, as well as state-of-the-art pre-trained embeddings. The pre-trained feature transformations are taken from public sources such as TensorFlow Hub, PyTorch Hub, and HuggingFace, whereas PCA and NCA are taken from scikit-learn\footnote{TensorFlow Hub: \url{https://tfhub.dev}, PyTorch Hub: \url{https://pytorch.org/hub}, HuggingFace: \url{https://huggingface.co/models/} and scikit-learn: \url{https://scikit-learn.org/}}. The pre-trained embeddings can either be directly accessed via the corresponding source, or have to be extracted from the last-layer representations of pre-trained neural networks. More details about the transformations supported, for each modality individually, can be found in Appendix~\ref{secAppendixTransormations}. \paragraph*{\underline{Settings of \texttt{Snoopy}\xspace}} When running \texttt{Snoopy}\xspace, we define the time needed to reach the lowest 1NN error across all embeddings based on multiple independent runs as described in Section~\ref{secAccuracyAndEfficiency}. These runtimes include the 1NN computation and running inference on a single GPU, with the latter being the most costly part, particularly for large NLP models. In the end-to-end experiments, when re-running \texttt{Snoopy}\xspace after having restored a fixed portion of the synthetically polluted labels (set to 1\% of the dataset size), we use the fact that the ``best'' embedding did not change and, therefore, no additional inference needs to be executed. We compare with a diverse set of baselines that estimate the BER: (i) training a logistic regression (LR) model on top of all pre-trained transformations, (ii) running AutoKeras, and (iii) fine-tuning a state-of-the-art (SOTA) foundation model~\cite{bommasani2021opportunities} for each data modality. \begin{figure*}[t!] \centering \includegraphics[width=0.92\textwidth]{figures/snoopy_real_baselines.png} \vspace{-1em} \caption{Error Estimations vs. Time on multiple real noisy variant of CIFAR10 and CIFAR100 (c.f., Table~\ref{tbl:dataset_cifar-n}). The dashed horizontal lines represent bounds and the expected increase of the SOTA using Theorem~\ref{thm_flipping}.} \label{fig:snoopy_vs_real_baselines} \vspace{-1.5em} \end{figure*} \paragraph*{\underline{Baseline 1: LR Models}} As mentioned before, when training the logistic regression models we assume that the representations for all the training and test samples are calculated in advance exactly once. In the end-to-end experiments, after having restored the same fixed portion of labels (i.e., 1\% of test and train samples), re-training the LR models does not require any inference. We train all LR models on a single GPU using SGD with a momentum of 0.9, a mini-batch size of 64 and 20 epochs. We select the minimal test accuracy achieved over all combinations of learning rate in $\{0.001, 0.01, 0.1\}$ and $L_2$ regularization values in $\{0.0, 0.001, 0.01\}$. We calculate the average time needed to train a LR based on the best transformation, without label noise, on all possible hyper-parameters. The hyper-parameter search was conducted 5 independent times for any value of randomly injected noise. \paragraph*{\underline{Baseline 2: AutoML Systems}} To mimic the use of an AutoML systems on a single GPU without any prior dataset-dependent knowledge, we run AutoKeras with the standard parameters of a maximum of 100 epochs and 2 trials on top of all datasets. We additionally run auto-sklearn with two different configurations to simulate a short execution time (max 1 hour), and a longer execution time (max 10 hours). Auto-sklearn does not natively support text as input and we therefore execute it using universal sentence embedding representations omitting the time to extract those representations. We report the mean of 5 independent executions in terms of times and accuracy, noting little variance amongst the results. \paragraph*{\underline{Baseline 3: Finetune}} The goal of this baseline is to replicate the SOTA values achieved for all datasets. We remark that this baseline is equipped with a strong prior knowledge which is usually unavailable for performing a cheap feasibility study and it only serves as a reference point. Unfortunately, reproducing the exact SOTA values was not possible for any of the dataset involved in the study, which is mainly due to computational constraints and the lack of publicly available reproducible code. We therefore perform our best, mostly manual, efforts to train a model on the original non-corrupted data. For multi-channel vision tasks (i.e., CIFAR10 and CIFAR100, and its noisy variants), we fine-tune EfficientNet-B4 using the proposed set of hyper-parameters~\cite{tan2019efficientnet}, whereas for NLP tasks, we fine-tune BERT-Base with 3 different learning rates and for 3 epochs~\cite{devlin2018bert}, using a maximal sequence length of 512, batch size of 6 and the Adam optimizer. \subsection{Evaluation of BER Estimations} \label{sec:endtoend} We first evaluate \texttt{Snoopy}\xspace by comparing its BER estimation of the best achievable accuracy with other baselines and show how this benefits an end-to-end scenario. \paragraph*{\underline{\texttt{Snoopy}\xspace vs. Baselines on Synthetic Noise}} In Figure~\ref{fig:snoopy_vs_baselines} we present our main findings on three levels of realistically injected label noise --- 0\%, 20\% and 40\%, which we visualize by adding the increase of the SOTA (at the time of writing) in expectation as horizontal lines to indicate a proxy of the ground truth BER error. We see that \texttt{Snoopy}\xspace is comparable to the short execution of auto-sklean whilst producing much better estimations. Furthermore, \texttt{Snoopy}\xspace is much faster than all other methods, often by orders of magnitude. The only exception is YELP in which running over large models (e.g., \textsc{GPT2} or \textsc{XLNet}) slows down \texttt{Snoopy}\xspace in a fashion comparable to AutoKeras, whilst still outperforming it in terms of the estimated accuracy. It also produces BER estimations that are \textit{comparable, if not better} than all other approaches. In fact, it is often better than both LR and, particularly, AutoKeras. It is only slightly worse than the LR classifier on text tasks for IMDB and SST2, while being orders of magnitude faster. \paragraph*{\underline{\texttt{Snoopy}\xspace vs. Baselines on Real Noise}} In Figure~\ref{fig:snoopy_vs_real_baselines} we run the same set of experiments for real noisy variants of CIFAR10 and CIFAR100 from~\cite{wei2022learning}. We realize that \texttt{Snoopy}\xspace constantly outperforms all baselines both in terms of speed and estimation accuracy. When comparing the error values to the lower and upper bounds, we realize that whilst \texttt{Snoopy}\xspace remains inside the bounds, there is a considerable gap between them. Nonetheless, \texttt{Snoopy}\xspace produces estimates close to the expected increase of the SOTA using Theorem~\ref{thm_flipping}. \begin{figure}[t!] \centering \includegraphics[width=0.55\linewidth]{figures/taking_min.png} \vspace{-1em} \caption{Impact of fixing a single feature transformation.} \vspace{-1em} \label{fig:taking_min} \end{figure} \textit{\underline{Is Taking the Minimum Necessary?}} When analyzing the performance of the system with respect to the number of feature transformations, one might ask the question whether a single transformation always outperforms all the others and hence makes the selection of the minimal estimator obsolete. When conducting our experiments, we observed that selecting the \textit{wrong} embedding can lead towards a large gap when compared to the optimal embedding, e.g., favoring the embedding \textsc{USELarge} over \textsc{XLNet} on IMDB doubles the gap of the estimated BER to the known SOTA value~\cite{renggli2021evaluating}, whereas favoring \textsc{XLNet} over \textsc{USELarge} on SST2 increases the gap by 1.5$\times$, making proper selection necessary (c.f., Figure~\ref{fig:taking_min}). \subsection{Usefulness of the Additional Guidance} \label{secExpAdditionalGuidance} \begin{figure}[t!] \centering \includegraphics[width=0.92\linewidth]{figures/additional_guidance_plots.png} \vspace{-1em} \caption{CIFAR100 - Different noise levels and targets.} \label{fig:additional_guidance_plots} \vspace{-1em} \end{figure} \begin{figure}[t!] \centering \includegraphics[width=0.92\linewidth]{figures/additional_guidance_extrapolate.png} \vspace{-1em} \caption{CIFAR100 - (Left) Extrapolation accuracy to the full dataset based on a fraction of the samples. (Right) Approximation based on 5\% of the samples.} \label{fig:additional_guidance_extrapolate} \vspace{-1.5em} \end{figure} When evaluating the 1NN estimator accuracy for varying label noise, and its convergence under different feature transformations, \footnote{We illustrate the convergence behaviour under different transformations in Appendix~\ref{app:Convergence} in the supplementary material.} we see that even the best transformations are constantly over-estimating the lower bound when increasing label noise, validating the key arguments for taking the minimum over all estimators. All the results indicate the median, 95\% and 5\% quantiles over multiple independent runs (i.e., 10 for YELP and 30 otherwise). We observe the presence of much more instability in SST2 when compared to other datasets. This is not at all surprising since SST2 has a very small test set consisting of less than one thousand samples, as seen in Table~\ref{tbl:datasets}. This naturally results in higher variance and less confidence for the 1NN classifier accuracy compared to the larger number of test samples for the other datasets. Figure~\ref{fig:additional_guidance_plots} illustrates a convergence plot for a fixed embedding (EfficientNet-B5) and the clean CIFAR100 dataset injected with 20\% and 40\% label noise respectively. The two target accuracies visualized by a horizontal line represent exactly the noise level, and the noise level plus 10\%. Note that the noise level is only reachable if the original BER of the dataset is zero. From the visualizations, the target of 0.5 on the dataset with 0.4 noise is highly likely. By using the approximation from Equation~\ref{eqnApproxExtrap}, we realize that less than 10K more samples should suffice to attain this accuracy. Conversely, for a target of 0.3 and 0.2 noise, although possibly realizable, the number of additional samples to verify the quality of the extrapolation is already more than 260K. Note that Equation~\ref{eqnApproxExtrap} converges to zero, and therefore any target can be realizable. Targeting exactly the label noise for each of the datasets yields an extrapolated number of more than 16M and 84M, which both should be seen as not trustworthy approximations based on the much smaller number of available samples in the training set. This thus implies that the target accuracy is not achievable based on the given transformations and numbers of samples. To illustrate this fact, we subsample the low label noise dataset and the same embedding for a fixed fraction. We then extrapolate the achievable target for the full dataset (i.e., 50K training samples) and plot the difference between the extrapolated target and the true BER estimate in Figure~\ref{fig:additional_guidance_extrapolate} on the left. The right part of Figure~\ref{fig:additional_guidance_extrapolate} illustrates the extrapolation based on 5\% of the samples. Notice that this provided example illustrates when to trust the estimated number of additional samples required using Equation~\ref{eqnApproxExtrap} (i.e., when the number if relatively low), not the BER estimate of \texttt{Snoopy}\xspace. The same results can easily be shown for any other dataset. \subsection{End-to-end Use Case} \label{secEndToEnd} \textit{How can we take advantage of \texttt{Snoopy}\xspace to help practical use cases?} In this section, we focus on a specific end-to-end use case of a feasibility study in which the user's task contains a target accuracy and a representative, but noisy dataset. The goal is to reach the target accuracy. At each step, the user can perform one of the following three actions: (1) clean a portion of the labels, (2) train a high-accuracy model using AutoKeras or fine-tune a state-of-the-art pre-trained model, (3) perform a feasibility study by either using the cheap LR model or \texttt{Snoopy}\xspace. To simulate the cleaning process on a noisy dataset, which usually requires human interactions of an expert labeler, we focus on the manually polluted datasets with synthetic label noise, where we can simply \textit{restore} the original label from the dataset. Being aware of different human costs for cleaning labels in real-world scenarios (i.e., depending on the application and the required expertise), we compare the impact of different cost scenarios outlined below. We report the mean (accuracy and run-time) over at least 5 independent runs. \paragraph*{\underline{Different User Interaction Models}} We differentiate two main scenarios in our end-to-end experimental evaluation: (1) \textit{without feasibility study} and (2) \textit{with feasibility study}. Without a feasibility study, users will start an expensive, high-accuracy run (i.e., running the fine-tuning baseline) using the input data. If the achieved accuracy is below the desired target, users will clean a fixed portion of the data (1\%, 5\%, 10\%, or 50\%, which we call \emph{steps}) and re-run the expensive training system. This is repeated until a model reaches the desired accuracy or all labels are cleaned. With a feasibility study, users alternate between running the feasibility study system and cleaning a portion of the data (set to 1\% of the data) until the feasibility study returns a positive signal or all labels are cleaned. Finally, a single expensive training run is performed. The lower bound on computation is given by training the expensive model exactly once. \begin{figure}[t!] \centering \includegraphics[width=0.95\linewidth]{figures/end2end_figures/cifar100_end2end_cheap_labels.png} \vspace{-1em} \caption{CIFAR100 - End-to-end use case, cheap labels.} \label{fig:end2end_cifar100_cheap} \vspace{-1em} \end{figure} \begin{figure}[t!] \centering \includegraphics[width=0.95\linewidth]{figures/end2end_figures/cifar100_end2end_expensive_labels.png} \vspace{-1em} \caption{CIFAR100 - End-to-end use case, expensive labels.} \label{fig:end2end_cifar100_expensive} \vspace{-1.5em} \end{figure} \paragraph*{\underline{Different Cost Scenarios}} We measure the cost in hypothetical ``dollar price'' for different regimes, depending on the \textit{human-labeling} costs and on the \textit{machine} costs. For the former, we define two scenarios: 'free', 'cheap' (0.002 dollars per label, resulting in 500 labels per dollar) and 'expensive' (0.02 dollars per label, resulting in 50 labels per dollar). For the latter, we fix the \textit{machine} cost to 0.9\$ per hour (the current cost of a single GPU Amazon EC2 instance). \paragraph*{\underline{Key Findings}} We only present the results on CIFAR100 here and leave the rest to Appendix~\ref{secAppendixExtendedEval} ---we observe similar results on all datasets for a wide range of initial noise levels and target accuracies. We show the results in Figures~\ref{fig:end2end_cifar100_cheap} and~\ref{fig:end2end_cifar100_expensive}, for 2 different cost setups described above (cheap and expensive), each over 2 values of the initial noise (0.40, 0.20) and, respectively, 2 target accuracies (0.60, 0.80). Each dot represents the result of one run of the expensive training process. \paragraph*{(I) Feasibility Study Helps.} When comparing the costs of repetitively training an expensive model to those of using an efficient and accurate system that performs a feasibility study, such as \texttt{Snoopy}\xspace, we see significant improvements across all results (c.f., blue vs. brown lines in Figure~\ref{fig:end2end_cifar100_cheap}). Without a system that performs a feasibility study, users are facing a dilemma. On the one hand, if one does not train an expensive model frequently enough, it might clean up more labels than necessary, to achieve the target accuracy, e.g., FineTune (step 50\%), which makes it intense on the human-labeling costs. This can be seen by the size of the vertical gap between the end point of a method and the horizontal line indicating the minimum number of samples to be cleaned to achieve the target accuracy. On the other hand, if one trains an expensive model too frequently, visible in the number of stairs for expensive fine-tune lines or the steepness of the curves for faster methods, it becomes computationally expensive, wasting a lot of computation time. With a feasibility study, the user can balance these two factors better. As running low-cost proxy models is significantly cheaper than training an expensive model, the user can get feedback more frequently (having in mind the efficient incremental implementation from Section~\ref{sectionEfficientImplementation}). Finally, notice that when we enter the label-cost dominated regime (e.g., Figure~\ref{fig:end2end_cifar100_expensive}), one seeks at cleaning the minimum amount of labels necessary, ignoring the computational costs. Nevertheless, finding the right step size is critical, making it a difficult task. \paragraph*{(II) \texttt{Snoopy}\xspace Outperforms Baselines.} When comparing different estimators that can be used in a feasibility study, in most cases, \texttt{Snoopy}\xspace is more effective compared to running a cheaper model such as LR, with its accuracy as a proxy. \texttt{Snoopy}\xspace offers significant savings compared to LR when the labeling costs are high. The LR model will often be of a lower accuracy than an expensive approach; hence, it requires to clean more labels than necessary to reach the target. We note that there are cases (e.g., for IMDB) where the best LR model yields a lower error than the BER estimator used by \texttt{Snoopy}\xspace. In such cases, there exists a regime where the costs of using the LR proxy are comparable or superior to using \texttt{Snoopy}\xspace despite being more expensive to compute. However, we see this as an exception and Figure~\ref{fig:end2end_cifar100_cheap} (and the evaluations on other datasets in Appendix~\ref{secAppEnd2End}) clearly show that the LR proxy is usually significantly more costly than using \texttt{Snoopy}\xspace. \begin{figure}[t!] \centering \includegraphics[width=0.42\linewidth]{figures/vtab_results.png} \hfill \includegraphics[width=0.42\linewidth]{figures/vtab_public.png} \vspace{-0.5em} \caption{\texttt{Snoopy}\xspace vs. Maximal fine-tune accuracies on VTAB (\textbf{Left}) for proprietary expert models derived from ~\cite{renggli2020model} and (\textbf{Right}) for public models from Huggingface: Showing \texttt{Snoopy}\xspace's generalization ability on small datasets and embeddings trained on different tasks.} \label{fig:vtab_results} \vspace{-1em} \end{figure} \subsection{Generalization to Other Tasks} In this section we examine two potential limitations of \texttt{Snoopy}\xspace, when deployed on a new task: (i) \textit{its dependence on large datasets}, and (ii) \textit{the necessity of having ``good'' pre-trained feature transformations for the given task}. For this, we use the results of~\cite{renggli2020model} on the popular visual task adaptation benchmark (VTAB)~\cite{zhai2019large} which is known to be a \textit{diverse} collection of datasets (19 different tasks), each being \textit{small} (1K training samples), and our collection of pre-trained transformations \textit{does not contain} any trained on these datasets. Additionally, we fine-tune the same 19 datasets on a set of 235 publicly available PyTorch models from Huggingface. To validate that \texttt{Snoopy}\xspace does not suffer from the above limitations, in Figure~\ref{fig:vtab_results} we illustrate the difference between \texttt{Snoopy}\xspace's predictions and the best achieved post-fine-tune accuracies. We observe that on most datasets, \texttt{Snoopy}\xspace produces a useful estimate of the fine-tune accuracy (except for some negative transfer results enabled by the low data regime) for both proprietary expert models and publicly available models. The estimates of the later are slightly shifted to the right as expected. Even though this is sufficient to say that the currently available embeddings are supporting \texttt{Snoopy}\xspace's performance, we expect this figure to improve over time as more and better embeddings become publicly available via repositories such as Huggingface, which also start including learned representation for different modalities such as tabular data. \subsection{Efficiency of \texttt{Snoopy}\xspace} \label{secAccuracyAndEfficiency} We saw that the gain of using \texttt{Snoopy}\xspace comes from having an (i) \textit{efficient estimator} of (ii) \textit{high accuracy}. Those two requirements are naturally connected. While having access to more and ``better'' (pre-trained) transformations is key for getting a high accuracy of our estimator, it requires the implementation of our algorithm to scale with respect to the ever-increasing number of transformations. \begin{figure} \centering \includegraphics[width=0.93\linewidth]{figures/optimizations/cifar10-cifar100-strategies.png} \vspace{-1em} \caption{Different selection strategies for \textbf{(Left)} CIFAR10, \textbf{(Right)} CIFAR100.} \label{fig:strategy_cifar10_cifar100} \vspace{-1em} \end{figure} \paragraph*{\underline{Runtime Analysis}} To showcase the importance of the \emph{successive-halving} (SH) algorithm, with and without the \emph{tangent method} presented in Section~\ref{sectionEfficientImplementation}, we compare different strategies for deploying the 1NN estimator in Figures~\ref{fig:strategy_cifar10_cifar100}. The strategies are evaluated with respect to the runtime (averaged across multiple independent runs on a single Nvidia Titan Xp GPU) needed to reach an estimation within 1\% of the \textit{best} possible value using all the training samples. Running the estimator only on the transformation yielding the minimal result is referred to as the \emph{perfect} strategy providing a lower bound, whereas we also test the \emph{uniform allocation} baseline described in~\cite{jamieson2016non}. We report the runtime by selecting the best batch size out of 1\%, 2\%, or 5\% of the training samples. We observe that running the entire feasibility study using \texttt{Snoopy}\xspace on CIFAR100 on a single GPU takes slightly more than 16 minutes, whereas the largest examined NLP dataset YELP requires almost 8.5 hours, with a clear improvement of SH with the tangent method over the one without. Putting these numbers into context, fine-tuning EfficientNet-B4 on CIFAR100 on the same GPU with one set of hyper-parameters (out of the 56 suggested by the authors~\cite{tan2019efficientnet}) requires almost 10 hours (without knowing whether other embeddings would perform better), whereas training large NLP models usually requires several hundred accelerators~\cite{rasley2020deepspeed}. \begin{figure}[t!] \centering \includegraphics[width=0.55\linewidth]{figures/incremental.png} \vspace{-1em} \caption{Incremental execution (log scale): On all datasets, rerunning \texttt{Snoopy}\xspace incrementally is several orders of magnitude faster than running from scratch.} \label{fig:incremental} \vspace{-1.5em} \end{figure} \paragraph*{\underline{Incremental Execution}} In Figure~\ref{fig:incremental}, not surprisingly, we see the benefit of \texttt{Snoopy}\xspace's ability to quickly rerun incremental evaluation described in Section~\ref{sectionEfficientImplementation}. Compared to running from scratch, we see that incremental execution is faster by several orders of magnitude on all datasets. \section{Conclusion} \label{sectionConclusion} \vspace{-0.5em} We present \texttt{Snoopy}\xspace, a novel system that enables a systematic feasibility study for ML application development. By consulting a range of estimators of the Bayes error and aggregating them in a theoretically justified way, \texttt{Snoopy}\xspace suggests whether a predefined target accuracy is achievable. We demonstrate system optimizations that support the usability of \texttt{Snoopy}\xspace, and scale with the increase in the number and diversity of available pre-trained embeddings in the future. { \small \textbf{Acknowledgements.} CZ and the DS3Lab gratefully acknowledge the support from the Swiss State Secretariat for Education, Research and Innovation (SERI) under contract number MB22.00036 (for European Research Council (ERC) Starting Grant TRIDENT 101042665), the Swiss National Science Foundation (Project Number 200021\_184628, and 197485), Innosuisse/SNF BRIDGE Discovery (Project Number 40B2-0\_187132), European Union Horizon 2020 Research and Innovation Programme (DAPHNE, 957407), Botnar Research Centre for Child Health, Swiss Data Science Center, Alibaba, Cisco, eBay, Google Focused Research Awards, Kuaishou Inc., Oracle Labs, Zurich Insurance, and the Department of Computer Science at ETH Zurich. } \bibliographystyle{IEEEtran}
{'timestamp': '2022-08-31T02:16:43', 'yymm': '2010', 'arxiv_id': '2010.08410', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08410'}
arxiv
\section{Introduction} Card-based protocols were proposed by den Boer~\cite{boer90} as a means for secure two-party computation. In this scenario, we have two players --- Alice and Bob --- who hold inputs $x$ and $y$ respectively. Their goal is to securely compute a given function $f$ on those inputs. By secure computation, we mean that the players learn nothing from observing the computation except for what is implied by the output $f(x,y)$. Den Boer introduced a model where the inputs $x$ and $y$ are encoded by a sequence of playing cards and the players operate on the cards to compute the function. They can use additional cards for computation. In particular, den Boer showed how to securely compute AND of two bits using five cards in total. Niemi and Renvall~\cite{niemi97} extended the results to show how to compute arbitrary Boolean function $f$. They represent each input bit by two face-down cards: 1 is represented as $\heartsuit\clubsuit$, and 0 as $\clubsuit\heartsuit$. They use the same representation throughout the computation and show how to securely compute AND of bits encoded in this \emph{2-card} representation with the output being encoded in the same way. Since NOT can be obtained by swapping the two cards representing a given bit this allows them to compute any function. They can evaluate any Boolean circuit on the inputs by a protocol of length proportional to the size of the circuit and using a number of auxiliary cards that corresponds to the \emph{width} of the circuit. Nishida et al.~\cite{nishida15} reduced the number of auxiliary cards to 6 for any Boolean function. For most functions, the protocol will be of exponential length as it essentially evaluates the DNF of $f$. Several other works studied the number of cards necessary for computing various elementary functions such as AND and XOR~\cite{danny17,koch15,koch18,kastner17,nishida15,stiglic01,mizuki09,mizuki12,mizuki14a,koch15,abe18,koch18}. Motivated by the question what can be efficiently computed by such protocols and how many cards one needs to compute various functions, in this work, we investigate \emph{efficient} protocols that are protocols of polynomial length. Our contribution is two-fold: We classify a large class of protocols with respect to the computational complexity of functions they compute, and we propose other encodings of inputs which require fewer cards than the 2-card representation. We summarize our results next: \smallskip\noindent{\bf 1.} We show that \emph{oblivious} protocols of polynomial length that do not modify their input (they are \emph{read-only}) and use only a constant number of auxiliary cards compute precisely the functions in ${\sf NC^1}$, the class of functions computed by Boolean circuits of logarithmic depth. (Alternatively, ${\sf NC^1}$ is the class of functions computed by Boolean formulas of polynomial size.) By oblivious protocol we mean a protocol whose actions depend only on the current visible state. \smallskip\noindent{\bf 2.} Oblivious read-only protocols of polynomial length with a logarithmic number of auxiliary cards correspond to the class of functions computable by polynomial-size branching programs. (This class is also known as ${\sf L}/poly$, the non-uniform version of deterministic log-space.) \smallskip\noindent{\bf 3.} We also investigate protocols that use a constant number of auxiliary cards but are allowed to use the cards representing the input for their computation provided that they guarantee that by the end of the computation the input will be restored to its original value. We show that such protocols can compute functions that are believed to be outside of ${\sf NC^1}$. For example, they can compute languages that are complete for ${\sf NL}$, the non-deterministic log-space. Hence, read-only protocols are presumably weaker than protocols that may modify their input. \smallskip\noindent{\bf 4.} We study alternative encodings of inputs that are more efficient that the 2-card encoding. We look at 1-card encoding where 1 is represented by $\heartsuit$ and 0 by $\clubsuit$. In this encoding, Alice and Bob need only one card per bit to commit the bit. We show similar complexity results for this encoding as for the 2-card encoding: read-only protocols with a constant number of auxiliary cards are ${\sf NC^1}$, with a logarithmic number of cards it is the non-uniform log-space, and if we allow using the input cards for computation we get potentially more powerful protocols. \smallskip A disadvantage of the 1-card protocol is that it still needs a supply of $n$ cards $\heartsuit$ and $n$ cards $\clubsuit$ to represent any $n$-bit input. Although, if one restricted his attention to inputs that contain the same number of 1's and 0's, it would suffice to have $n/2$ cards $\heartsuit$ and $n/2$ cards $\clubsuit$. Such inputs form a substantial fraction of all $n$-bit inputs, they are $\Theta(2^{n}/\sqrt{n})$ many. \smallskip\noindent{\bf 5.} We propose a new $1/2$-card encoding which requires only $n/2$ cards $\heartsuit$ and $n/2$ cards $\clubsuit$ to represent any $n$-bit input. The $1/2$-card encoding is obtained from the 2-card encoding by removing from each pair of cards one card, in total one half of the $\heartsuit$-cards and one half of the $\clubsuit$-cards. There is an empty space left instead of each removed card. There is a way for each player to encode his input so that the other player learns no information about the opponent's input. We show that using this encoding we can simulate any read-only protocol that uses 2-card encoding. Hence, any ${\sf NC^1}$ function on $n$ bits can be securely computed using only $n+O(1)$ cards, counting also the input cards. We do not know how to securely perform protocols for $1/2$-card encoding that would modify their input. \subsection{Previous Work} As mentioned above, a study of card-based protocols was started by den Boer~\cite{boer90} who introduced a secure 5-card protocol for computing AND. However, this protocol does not produce output in a face-down 2-card format, thus it can not be used for designing protocols for arbitrary function. Since then a lot of work was done in improving AND protocols and other primitive functions. Cr{\'e}peau and Kilian~\cite{crepeau94} provided a 1-party card-based protocol where the player can pick a random permutation $\pi$ with no fixed point and the player has no information about $\pi$. Their technique can be used for designing a 2-party computation of a general function. Niemi and Renvall~\cite{niemi97} introduced an AND protocol, which takes two bits $b_1, b_2$ represented in the 2-card format as input and outputs two cards which represent $b_1 \wedge b_2$ in face-down 2-card format. They also introduced a protocol for copying a bit in the 2-card format, which is used during simulation of circuits. Their protocols with a protocol for NOT (which is trivial) can be used for computing any Boolean function $f$ and the number of used cards is at most linear in the size of a circuit (using AND and NOT gates) computing $f$. They also introduced a protocol to copy a single card with almost perfect security -- the card suit is revealed only with a small probability. Such protocol cannot exist with perfect security as was proved by Mizuki and Shizuya~\cite{mizuki14}. The copying and AND protocols were further improved and simplified in~\cite{stiglic01,mizuki09,mizuki12,mizuki14a,koch15,abe18,koch18}. Nishida et al.~\cite{nishida15} proved that any Boolean function $f: \{0,1\}^n \times \{0,1\}^n \to \{0,1\}$ can be computed with $4n$ cards encoding the input and 6 additional helping cards. Mizuki~\cite{mizuki16} proved that $2n + 2$ is needed to compute AND of $n$ bits. Francis et al.~\cite{danny17} provided protocols and tight lower bounds on the number of cards needed for computing any two-bit input two-bit output function. Other lower bounds for AND of 2 bits and of $n$ bits in various regimes were provided by Koch et al.~\cite{koch15, koch18} and by Kastner et al.~\cite{kastner17}. The security of card-based protocols is provided by shuffling the cards --- one player shuffles the cards (applies some random permutation to them) in a way so that the other player has no information about the new order of shuffled cards. Koch et al.~\cite{koch15} provided a 4-card AND protocol. However, they used a non-uniform distribution for picking a random permutation, which is difficult to perform by humans. Nishimura et al.~\cite{nishimura16} suggested an ``easy-for-human'' procedure how to apply a shuffling permutation picked from a non-uniform distribution using envelopes. One can distinguish two types of attack. \begin{enumerate} \item Passive: honest-but-curious player -- she follows the protocol but she wants to retrieve as much information as possible about the other player input. \item Active: malicious player -- she can deviate from the protocol. \end{enumerate} Koch and Walzer~\cite{koch21} proved that if a passive-secure protocol $\Pi$ uses only uniform closed shuffles (each shuffling permutation is picked uniformly from some permutation group) then the protocol $\Pi$ can be transformed into an active-secure protocol. \section{Preliminaries} \subsection{Card-based Protocols} \label{sec:PrelimProtocol} In this section we define \emph{card-based protocols} which securely compute some Boolean function on a joint input of Alice and Bob. Alice gets an input $x \in \{0,1\}^n$ and Bob gets an input $y \in \{0,1\}^n$, and their goal is to compute $f(x,y)$ for some function $f: \{0,1\}^n \times \{0,1\}^n \to \{0,1\}$, while not revealing anything about their input to the other player. The protocol proceeds first by Alice and Bob committing their input into a sequence of cards, and then operating on the cards together with some auxiliary cards. At the end of the protocol, the players learn the output $f(x,y)$. In this section we consider the usual \emph{2-card encoding} of the input, where each input is represented as a sequence of cards, two cards per bit: value $1$ is represented by $\heartsuit\clubsuit$ and value $0$ is represented by $\clubsuit\heartsuit$ where the cards are put face-down on the table. Hence each player needs $2n$ cards to commit his input. All the cards have the same back, say blue. In the beginning, face-down cards representing the player inputs are in front of the players. Between them, there is a \emph{deck} of $s$ prescribed auxiliary cards of $\heartsuit$ and $\clubsuit$. There is available some empty space on the table to operate with the cards. We assume that the cards are placed on the table in some specific positions (locations), numbered $1,\dots,m$, where: \begin{itemize} \item $1,\dots,2n$ are positions of Alice's input cards, \item $2n+1,\dots,4n$ are positions of Bob's cards, \item $4n+1,\dots,4n+s$ are the initial positions of the helping cards in the deck, \item $4n + s +1,\dots, m$ are initially empty positions. \end{itemize} We call the positions $1,\dots,4n$ as the input positions and the remaining positions as the \emph{work space}. We say a position is \emph{occupied} if there is a card on it, otherwise, it is \emph{empty}. We denote an empty position by $\times$. Let $q=m-4n$ denote the amount of the work space. We assume $q=O(s)$. Thus, there are $4n + s$ cards on the table and $4n + q = m$ positions. The players can move their input cards and cards from the deck to the work space and back. Formally, the basic \emph{actions} which can be executed by the players are: \begin{description} \item[Move($p, i, j$)]: The player $p$ moves a card from the position $i$ to position $j$. \item[Shuffle($p, T, \Gamma$)]: The player $p$ applies a random permutation from $\Gamma$ to the cards on the table on positions $T \subseteq \{4n+1,\dots,m\}$. \item[Turn($p,i$)]: The player $p$ turns the $i$-th card on the table face-up if it is face-down, and vice versa. \end{description} The protocol specifies which action to take next based on the sequences of visible states seen on the table so far. The current visible state of the table is what an external viewer could observe, that is which positions are currently occupied and what is the top of each card laying on the table. If there are $c$ distinct cards then there are at most $(c+2)^m$ distinct visible states. Hence, based on the sequence of visible states from the beginning of the game the protocol specifies which action to take next or whether to end. In the end, the protocol specifies which cards represent the output of the run of the protocol. (They might be face-down.) We say the protocol $\Pi$ \emph{computes} a function $f: \{0,1\}^n \times \{0,1\}^n \to \{0,1\}$ if for all inputs $x,y \in \{0,1\}^n$, on the inputs $x$ and $y$ the protocol outputs $f(x,y)$. The length of the protocol is the maximum number of actions executed by the protocol over all inputs $(x,y) \in \{0,1\}^n \times \{0,1\}^n$ and all possible outcomes of shuffling. We say that a protocol is \emph{oblivious} if the action executed next depends only on the current visible state and the number of actions taken so far. The shuffling operation provides randomness for the execution of the protocol. Hence, the sequence of visible states the protocol passes through is a random variable. We will say that a protocol is \emph{secure} if for any pair of inputs $(x,y)$ and $(x',y')$ to Alice and Bob, where $f(x,y)=f(x',y')$, the distribution of the sequence of visible states of the protocol on inputs $(x,y)$ and $(x',y')$ is the same. Notice, that this implies that neither of the players learns anything about the input of the other player except for what is implied by $f(x,y)$. Often we will be interested in protocols that provide their output encoded in face-down cards. In such a scenario we will require for the security of the protocol that the distributions of visible states during the protocol will be identical for all input pairs $(x,y)$. We say the protocol is \emph{robust} if a cheating player, that is a player who deviates from the protocol, is either caught by reaching an invalid visible state (where cards have unexpected values or positions) or the distribution of visible states does not leak any information about the other player input except for what would be leaked by honest players. In particular, if say Bob is cheating and Alice is honest, for a robust protocol we require that for any input $x$ of Bob and any two inputs $y,y'$ to Alice, where $f(x,y)=f(x,y')$, the distribution of the sequence of visible states during the game on inputs $(x,y)$ and $(x,y')$ is the same. We will be designing only robust oblivious protocols. We say the protocol is \emph{read-only} if the value of cards placed on the input positions $1,\dots,4n$ is always the same whenever a position is occupied. Let $s$-${\sf SP}$ be the class of function families $\{ f_n: \{0,1\}^n \times \{0,1\}^n \to \{0,1\} \}_{n\ge 0}$ for which we have a sequence of secure read-only oblivious protocols, one for each $n$, which are of length polynomial in $n$, with deck size $s$ and work space size $2s$. (At the beginning the first $s$ work space positions are occupied by the deck of cards, and the remaining $s$ positions are empty). We might allow $s$ to be a function of $n$. We define ${\sf SP}= \bigcup_{s\ge 1} s\textit{-}{\sf SP}$. That is a function belongs to ${\sf SP}$ if it has polynomial length protocols which use a constant number of auxiliary cards and constant size work space. \subsection{Branching Programs} A \emph{branching program} $B$ for a Boolean function $f: \{0,1\}^n \to \{0,1\}$ is defined as follows. It consists of a directed acyclic graph $G$ such that each vertex has out-degree either 2 or 0. The set of edges $E$ of the graph $G$ is split into two sets, zero-edges $E_0$ and one-edges $E_1$, in such a way that every vertex $v$ of out-degree 2 is incident to exactly one outgoing zero-edge and exactly one outgoing one-edge. Each vertex of out-degree 2 is labeled by an index $\ell \in [n]$. A branching program $B$ is \emph{layered} if the vertices are partitioned into layers $L_1,\dots,L_d$. The edges go only from a layer $L_i$ to a layer $L_{i+1}$ (for all $i < d$). Vertices of out-degree 0 are exactly vertices in the layer $L_d$. The number of layers $d$ is the \emph{length} of $B$ and the \emph{width} $w$ of $B$ is the maximum size of its layers, i.e., $w = \max_i |L_i|$. A layered branching program is \emph{oblivious} if vertices in the same layer have the same label. A branching program is a \emph{permutation branching program} if each layer has exactly $w$ vertices and for every two consecutive layers $L_j$ and $L_{j + 1}$ zero-edges and one-edges form matching $M^0_j$ and $M^1_j$, respectively. We can view the matchings $M^0_j$ and $M^1_j$ as two permutations $\pi^0_j, \pi^1_j: [w] \to [w]$. Note that we can rearrange all layers such that all permutations $\pi^0_j$ are identities. One vertex of in-degree 0 is an \emph{initial} vertex $\bar{v}$. Some vertices of out-degree 0 are denoted as \emph{accepting} vertices. The computation of a branching program $B$ on an input string $x \in \{0,1\}^n$ proceeds as follows. It starts in the initial vertex $\bar{v}$ which is the first \emph{active} vertex. Suppose $v$ is an active vertex and $\ell \in [n]$ is the label of $v$. If the out-degree of $v$ is 2, then the next active vertex is determined by the zero- or one-edge according to the value of $x_\ell$. More formally, let $e = \{v,v'\}$ be the edge in $E_{x_\ell}$. Then, the vertex $v'$ is the new active vertex. We repeat this procedure until a vertex $u$ of out-degree 0 is reached. An input $x \in \{0,1\}^n$ is accepted if and only if $u$ is an accepting vertex. The branching program $B$ computes a function $f: \{0,1\}^n \to \{0,1\}$ if it accepts exactly those $x \in \{0,1\}^n$ such that $f(x) = 1$. The class of functions {{\sf PB}} contains all the functions computable by layered branching programs of constant width and polynomial length. A permutation branching program is \emph{restricted} if it has exactly one accepting vertex $v_\text{acc}$ and exactly one rejecting vertex $v_\text{rej}$ in the last layer $L_d$. The computation of a restricted permutation branching program ends always in the vertices $v_\text{acc}$ or $v_\text{rej}$ and it accepts an input if it ends in the accepting vertex $v_\text{acc}$. A class $\PBP{w}$ contains Boolean functions which are computable by restricted permutation branching programs of width $w$ and polynomial length. We use the famous Barrington's theorem~\cite{barrington89}, which says that constant-width (permutation) branching programs are as powerful as ${\sf NC^1}$-circuits. \begin{theorem}[Barrington~\cite{barrington89}] \label{thm:Barrington} ${\sf PB} \subseteq {\sf NC^1} \subseteq \PBP{5}$. \end{theorem} \section{Simulating Branching Programs} In this section, we prove one of our main theorems that read-only oblivious protocols of polynomial length that use constant work space compute the same functions as polynomial-size constant-width branching programs. \begin{theorem}\label{thm:OneCard} ${\sf SP}={\sf NC^1}$. \end{theorem} To simulate a branching program by ${\sf SP}$-protocol we need an oblivious implementation of copying a bit in the committed 2-card format. We use a procedure by Stiglic~\cite{stiglic01}. It is straightforward to implement the procedure to be oblivious. We include the proof for the sake of completeness. \begin{restatable}{theorem}{copybit} \label{thm:CopyBit} There is a secure oblivious protocol that takes a bit $b$ in 2-card representation placed in the work space and produces two 2-card copies of the bit in the work space. The protocol needs an auxiliary deck with three cards $\heartsuit$ and three $\clubsuit$ with the same back as the input bit. \end{restatable} \begin{proof} \begin{enumerate} \item Alice arranges the cards from the auxiliary deck face-up to create the following configuration. \[ \underbrace{\,?\,\cq}_b \heartsuit\clubsuit\heartsuit\clubsuit\heartsuit\clubsuit \] \item She turns the last six cards. Both, Alice and Bob, apply a random cyclic shift (denoted by $\langle,\rangle$) to them. \[ \underbrace{\,?\,\cq}_b \langle\underbrace{\,?\,\cq}_{b'}\underbrace{\,?\,\cq}_{b'}\underbrace{\,?\,\cq}_{b'}\rangle \] \item They apply a random cyclic shift to the first four cards. \[ \langle \,?\,\cq\,?\,\cq \rangle \underbrace{\,?\,\cq}_{b'}\underbrace{\,?\,\cq}_{b'} \] \item She turns the first four cards face-up. \begin{enumerate} \item If the sequence is alternating (i.e., $\heartsuit\clubsuit\heartsuit\clubsuit$ or its shift) then $b = b'$. Thus, the last 4 cards represent two copies of $b$. \[ \heartsuit\clubsuit\heartsuit\clubsuit \underbrace{\,?\,\cq}_{b}\underbrace{\,?\,\cq}_{b} \] \item Otherwise (i.e., $\heartsuit\clubsuit\cz\heartsuit$ or its shift) then $b = 1 - b'$. Thus, the last 4 cards represent two copies of negation of $b$. In that case, she switches the fifth with the sixth card and the seventh with the eighth card to represent two copies of $b$ as well. \[ \heartsuit\clubsuit\cz\heartsuit \underbrace{\,?\,\cq}_{1 - b}\underbrace{\,?\,\cq}_{1 - b} \] \end{enumerate} Alice and Bob might want to turn over and shuffle the first four left-over auxiliary cards after step 4. The last four cards represent two copies of $b$ face-down in the 2-card format. To make the protocol oblivious we must implement both 4.a) and 4.b) by the same number of actions. To do so we include additional actions in 4.a) which have no effect such as shuffling a single card. \end{enumerate} It is clear the described protocol is secure. The only step where they can gain some information about $b$ is Step 4, when Alice turns some cards. However, the cyclic shifts in Steps 2 and 3 were done by both players. Thus, Alice reveals the alternating sequence ($\heartsuit\clubsuit\heartsuit\clubsuit$) in Step 4 with the probability exactly $\frac{1}{2}$ (independently on the value of $b$) even if one of the players would be cheating. Thus, the protocol is secure. \end{proof} To prove ${\sf NC^1} \subseteq {\sf SP}$ we use as the first step Barrington's theorem~\cite{barrington89}. By Barrington's theorem, each function $f : \{0,1\}^n \times \{0,1\}^n \to \{0,1\}$ from ${\sf NC^1}$ can be computed by a polynomial length width-5 restricted permutation branching program. We will build a protocol that simulates the actions of the branching program layer by layer. We will keep track of the image of the initial vertex of the branching program. For that, we will use five cards $\heartsuit\clubsuit\cz\clubsuit\cz$, where the position of $\heartsuit$ corresponds to the image of the initial vertex (the active vertex), and we will apply the permutations prescribed by the branching program on those five cards. If the input variable assigned to a particular level of the branching program is set to 1 we are expected to perform the permutation otherwise we are supposed to do nothing, i.e., apply the identity permutation. Any permutation can be decomposed into a sequence of simple transpositions (swaps) so we will use swaps conditioned by the input variable to either permute the five cards or leave them the way they are. We will implement the following primitive: Alice and Bob want to conditionally swap two cards $\alpha,\beta$ according to the value of bit $b$ represented in the face-down 2-card form in the work space without revealing the value of $b$. They also want to make sure that if $b = 1$ the swap occurs and if $b = 0$ the swap does not occur. \begin{theorem} \label{thm:SwapCards} Let $\tilde{\alpha},\tilde{\beta}$ be two sequences of face-down cards of the same length in the work space, and let $\gamma\,\delta$ be a face-down 2-card representation of $b$ in the work space. There is a secure oblivious protocol such that during the protocol players swap the sequences $\alpha$ and $\beta$ if and only if $b = 1$. The protocol uses two auxiliary cards $\clubsuit$. \end{theorem} \begin{proof} The swapping protocol works as follows. \begin{enumerate} \item Alice rearranges the input cards together with two auxiliary face-up cards $\clubsuit$ as follows: \[ \clubsuit \gamma~\tilde{\alpha}~\clubsuit \delta~\tilde{\beta} \] Thus, if $b = 0$ we have $\clubsuit \clubsuit \tilde{\alpha} \clubsuit\heartsuit \tilde{\beta}$ and if $b = 1$ we have $\clubsuit\heartsuit \tilde{\alpha} \clubsuit\cz \tilde{\beta}$. The players do not know which situation are they in. \item Both, Alice and Bob, apply a random cyclic shift to the cards, e.g.: \[ \tilde{\alpha}~\clubsuit\delta~\tilde{\beta}~\clubsuit\gamma \] \item Alice turns the cards $\gamma$ and $\delta$ representing $b$ face-up. She knows what cards to turn, as the cards $\gamma$ and $\delta$ are preceded by $\clubsuit$ face-up. At the end she reorders the sequence (keeping the cyclic order) so that $\clubsuit\cz$ are the first cards, e.g.: \[ \tilde{\alpha} \clubsuit\heartsuit \tilde{\beta} \clubsuit\cz \rightarrow \clubsuit\cz \tilde{\alpha} \clubsuit\heartsuit \tilde{\beta} \] If $b = 0$ then $\gamma \delta = \clubsuit\heartsuit$ and the sequences $\tilde{\alpha}\tilde{\beta}$ are not swapped. On the other hand if $b = 1$ then $\gamma \delta = \heartsuit\clubsuit$ and the sequences are swapped. \end{enumerate} Note that the cards in $\tilde{\alpha}$ and $\tilde{\beta}$ are face-down during the whole protocol. It is also clear that this is a secure and robust protocol, and it can be implemented obliviously. In Step 3 the cards $\delta$ and $\gamma$ representing the bit $b$ are revealed. However, because of random cyclic shifts in Step 2 (again done by both players), these cards are in the order $\heartsuit\clubsuit$ with probability $\frac{1}{2}$, independently of the value of $b$. Thus the swapping protocol is secure. \end{proof} Now we are ready to prove the first inclusion of Theorem~\ref{thm:OneCard}. \begin{theorem} \label{thm:OneCard1} $\PBP{5} \subseteq {\sf SP}.$ \end{theorem} \begin{proof} Let $f: \{0,1\}^n \times \{0,1\}^n \to \{0,1\}$ be a function in $\PBP{5}$. Then, the function $f$ can be computed by a branching program $P$ with the following properties: \begin{enumerate} \item Each layer has exactly 5 vertices. The input vertex is the first vertex in the first layer. The computation ends either in the accepting vertex $v_\text{acc}$ or in the rejecting vertex $v_\text{rej}$. \item The permutation from each layer $i$ to the layer $i + 1$ corresponding to 0 is the identity. \end{enumerate} Alice and Bob represent the first layer as $\heartsuit\clubsuit\cz\clubsuit\cz$, each card represents one vertex in the layer. The card $\heartsuit$ represents the active vertex in the layer (the initial vertex in the first layer). We call these 5 cards the \emph{program cards}. Alice and Bob put the program cards at the work space and turn them face-down. Alice and Bob simulate the program $P$ layer by layer. They apply permutations determined by $P$ to the program cards according to the player's input bits. Suppose we have a representation of the active vertex in the $i$-th layer and we want to calculate the active vertex at the $(i+1)$-th layer. Without loss of generality the label of the $i$-th layer is Alice's bit $x_\ell$ (otherwise the roles of Alice and Bob are reversed). Thus, we want to apply some permutation $\rho_i \in S_5$ to the program cards if $x_\ell = 1$ and keep the order of the program cards if $x_\ell = 0$. We decompose the permutation $\rho_i$ into transposition $\tau_1 \circ \dots \circ \tau_r$. For $j=1,\dots,r$, Alice will apply the transposition $\tau_j$ to the program cards. She runs the protocol $\Gamma_1$ of Theorem~\ref{thm:CopyBit} to get cards $\gamma,\delta$ representing her bit $x_\ell$ in the work space. More formally, after the execution of $\Gamma_1$, there are two pairs of cards such that each pair represent the bit $x_j$ in the 2-card format. She puts one pair back to the input positions, i.e., the protocol $\Pi$ is indeed read-only. We denote the cards of the second pair as $\gamma$ and $\delta$. Alice will use them for a conditional swap. She runs the protocol $\Gamma_2$ given by Theorem~\ref{thm:SwapCards} (applied to the cards $\gamma,\delta$ and to the two program cards which should be affected by the transposition $\tau_j$). That is, Alice swaps the two cards that $\tau_j$ is acting on if and only if $x_\ell = 1$. After applying this procedure for all transpositions $\tau_1, \dots, \tau_r$, the permutation $\rho_i$ got applied to the program cards if and only if $x_\ell = 1$ (otherwise the order of the program cards does not change). Alice and Bob repeat this procedure for each layer of the branching program. Let $\alpha$ be the card representing the accepting vertex $v_\text{acc}$ and $\beta$ be the card representing the rejecting vertex $v_\text{rej}$ at the end of the simulation. The cards $\alpha, \beta$ represent the output of the program. If the input is accepted, then the accepting vertex $v_\text{acc}$ is active at the end of the simulation and thus the card $\alpha$ has suit $\heartsuit$ and the card $\beta$ has suit $\clubsuit$. Thus, the cards $\alpha, \beta$ represent 1. On the other hand, if the input is rejected, then the rejecting vertex $v_\text{rej}$ is active. Thus, the cards $\alpha, \beta$ have suits $\clubsuit$ and $\heartsuit$, respectively, and they represent 0. The protocol $\Pi$ is clearly {{\sf SP}}-protocol as the players only sequentially apply the copying protocol $\Gamma_1$ and the swapping protocol $\Gamma_2$ to the program cards. We claim the simulation protocol $\Pi$ is secure. Both protocols $\Gamma_1$ and $\Gamma_2$ are secure. The only helping cards which are used during the whole run of the protocol $\Pi$ are program cards which are placed face-up from the deck and then turned face-down for the rest of the protocol. \end{proof} Now we prove the opposite inclusion of Theorem~\ref{thm:OneCard}. \begin{theorem} \label{thm:OneCard2} ${\sf SP} \subseteq {\sf PB}$. \end{theorem} \begin{proof} Consider a family of functions $\{ f_n: \{0,1\}^n \times \{0,1\}^n \to \{0,1\} \}_{n\ge 0}$ for which we have a sequence of secure read-only oblivious protocols, one for each $n$, which are of length polynomial in $n$, with deck size $s$ and work space size $2s$. Let $c$ be the number of different cards used by the protocol. At any moment, the work space can be in at most $(2c+1)^{2s}$ different states which we call the internal states of the protocol. For any $n\ge 1$ we will build a width-$(2c+1)^{2s}$ branching program of the same length $T_n$ as the protocol for $f_n$. Each layer of the branching program consists of vertices where each vertex corresponds to one internal state of the protocol. We need to define edges between the layers of the branching program. Let $v$ be a vertex at layer $t \in \{0,\dots, T_n-1\}$. It corresponds to some internal state which in turn determines a visible state that together with $t$ determines the action taken by the protocol at such a state. We define the edges based on the type of that action. If the action is a move of a card from some input position into the work space then node $v$ queries the value of the corresponding input variable and the outgoing edges lead to nodes corresponding to internal states that reflect a move of the card into the work space. If the action is a shuffle operation then node $v$ queries variable $x_1$ and irrespective of its value both outgoing edges go to the node in the next layer corresponding to the internal state obtained by applying one of the allowed permutations. (The particular choice of the permutation does not matter.) Similarly, for a move of a card within the work space or out from the work space, the edges will go into a node that reflects the internal state after the move. In the last layer, we designate vertices that correspond to accepting states of the protocol as accepting all other nodes will be rejecting. It should be clear from the construction that the resulting branching program computes $f_n$ and has the required properties. \end{proof} Theorem~\ref{thm:OneCard} is a corollary of Theorems~\ref{thm:OneCard1} and~\ref{thm:OneCard2} and Barrington's theorem (Theorem~\ref{thm:Barrington}). \section{Simulating Turing Machines} In this section, we will look at computation that obliviously and securely computes on committed inputs in 2-card representation. The exact split of the input between Alice and Bob is irrelevant in this section so we assume that the total length of the input is $n$ bits. The protocols are expected to preserve the committed inputs: Although they may be allowed to modify the committed input during the computation, by the end of the computation the committed input must be restored to its original form. The protocols do not leak any information about the committed inputs except for what can be derived from the output cards if they are inspected. The protocols can be carried out by either player. To guarantee robustness and security shuffle operations should be always done by both players. (We use only uniformly random shuffle and random cyclic shift so performing them twice does not change their output distribution.) \begin{theorem}\label{thm:s-space} Let $s(n)\ge \log n$ be a non-decreasing function. Let $f$ be a function computable by a Turing machine in space $s(n)$. Then $f$ is in $O(s(n))$-{\sf SP}. \end{theorem} Let $\textit{SEL}:\{0,1\}^n \to \{0,1\}$ be the function such that $\textit{SEL}(c,b,a)=a$ if $c=0$ and $\textit{SEL}(c,b,a)=b$ otherwise. \begin{proof} We describe the algorithm for the protocol in high-level form and leave details of the construction to the interested reader. Let $f$ be computable by a Turing machine $M$. Without loss of generality, we assume $M$ uses a binary alphabet, on inputs of length $n$ it uses work space exactly $s(n)$ bits and computes for $t(n)$ steps. The output of $M$ is determined by the first bit of its work tape. We will simulate the computation of $M$ step by step. The protocol will use $8 s(n) + 4\log n + O(1)$ auxiliary cards. Two blocks $w$ and $w'$ will represent $2 s(n)$ bits, each, and two blocks $p$ and $j$ will represent $\log n$ bits each. In addition to that there is a block $q$ of $O(1)$ bits, and some additional auxiliary bits. We need a constant number of positions to be empty. All the bits are encoded in 2-card representation. The block $w$ represents the content of the work tape of $M$, 2 bits per tape cell, where the second bit indicates the presence of the work tape head on that particular tape cell. The block $p$ encodes in binary the current position of the input head of $M$. The block $q$ encodes the internal state of $M$. The protocol simulates one step of $M$ as follows: first, it determines the value $b$ of the bit scanned by the input head, then it calculates into $w'$ the content of the work tape of $M$ after this step. Then it updates the internal state, the input head position $p$, and switches $w'$ and $w$. To determine $b$ the protocol looks at each input bit $x_i$ one by one and records the one that has an index corresponding to $p$. Set $b$ to 0. For $i=1,\dots,n$, the protocol copies $x_i$ into some work space $b'$, it sets $j$ to represent $i$, obliviously compares $p$ and $j$ while recording the result into $c$. (Comparing bit strings can be done by an ${\sf NC^1}$ circuit so there is an oblivious protocol for that of poly-logarithmic length.) From $c$, $b$ and $b'$ we can calculate the new value of $b$ by evaluating $\textit{SEL}(c,b,b')$. This can be done obliviously. After processing all the input bits, $b$ has the value of the currently scanned input bit. Now, we can determine $w'$, the content of the work tape of $M$ after this step of the computation. We compute $w'$ cell by cell. The value of each cell is a function of the input bit $b$, $M$'s state $q$, and the previous content of the cell in $w$ together with the content of adjacent cells. Hence, the value of each bit of $w'$ is a function of constantly many bits and can be computed obliviously. After computing $w'$, we can also calculate $d$, the direction in which the input head of $M$ should move, and the new state $q'$ of $M$. This can be done by scanning $w$ for the work tape position, and recording the relevant information for $q'$ and $d$ when we pass over the current work cell similarly to determining the value of the input bit $b$. From $p$ and $d$, we obliviously calculate the next position of the input head into $j$. (Each bit of $j$ can be computed by an ${\sf NC^1}$ circuit from $p$ and $d$.) Finally, we switch the contents of $w$ and $w'$, $p$ and $j$, and $q$ and $q'$. We repeat this procedure $t(n)$ times. In the end, the first bit of $w$ indicates the output of $M$. As each step of the computation can be implemented securely, obliviously, and robustly, we obtain a secure, oblivious, and robust protocol for $f$ that uses $O(s(n))$ work space and $O(s(n))$ auxiliary cards. \end{proof} As the card-based protocols allow for non-uniformity by protocols using $O(\log n)$ work space we can simulate not only log-space Turing machines but also polynomial-size branching programs (the \emph{non-uniform log-space}). The above proof can be extended to Turing machines taking advice: the protocol can provide the advice bit by bit during the phase when the input is scanned bit by bit to determine $b$. (We assume that the advice is provided to the Turing machine on bit positions with index $>n$. For those positions instead of copying the non-existent input bits, the protocol hardwires the appropriate bit into $b'$. As the advice is the same for each input, this can be done publicly.) By essentially the same proof as Theorem~\ref{thm:OneCard2} we can obtain a simulation of oblivious, read-only secure protocols that use a logarithmic amount of work space by branching programs of polynomial size. Let $O(\log n)$-${\sf SP} = \bigcup_k (k+k\log n)$-${\sf SP}$. We get: \begin{theorem} The class of functions computable by polynomial-size branching programs equals to $O(\log n)$-{\sf SP}. \end{theorem} \subsection{Read-write Protocols} So far we have looked only at read-only protocols. If we remove the condition to be read-only we get a potentially larger class of functions computable by such protocols. When the protocol is not read-only, we still require the protocol to restore its input into the original state by the end of the computation. We also require the protocol to be secure so not to leak any information about the input except for what is implied by the protocol output cards. We give examples of functions that can be computed by protocols modifying their input which we conjecture are outside of the read-only protocol class with similar bound on the work space. Proving this conjecture would amount to separating ${\sf NC^1}$ from log-space, a major open problem in complexity theory. Let $s(n)$ be a non-decreasing function such that $\log n \le s(n) \le n/2\log^* n$. Let $g:\{0,1\}^n \to \{0,1\}$ be in ${\sf NC^1}$, and $h:\{0,1\}^{n-s(n) \log^* n} \to \{0,1\}$ be a function computable by a Turing machine in space $O(s(n))$ and polynomial time. Define $f:\{0,1\}^n \to \{0,1\}$ as follows: $$ f(x) = \left\{ \begin{array}{ll} g(x) & \mbox{if } x_{n+1-s(n)\log^* n}\cdots x_n \ne 0\cdots 0, \\ h(x_1\cdots x_{n-s(n)\log^* n}) & \mbox{otherwise.} \end{array} \right. $$ \begin{theorem}\label{thm:RWSim} The function $f$ defined above is computable by secure robust oblivious protocols of polynomial length that use a constant amount of work space. \end{theorem} \begin{proof} The protocol for $f$ proceeds as follows. It first computes the OR of the input bits $x_{n+1-s(n)\log^* n}\cdots x_n$ using a protocol for ${\sf NC^1}$ functions where the output $c$ of the protocol is encoded in 2-card representation in its work space. Then it computes the value $g$ of $g(x)$ encoded in 2-card representation in the work space. Finally, it uses the cards representing input bits $x_{n+1-s(n)\log^* n}\cdots x_n$ to simulate the computation of a Turing machine for $h$ as in the proof of Theorem~\ref{thm:s-space}. The simulation is done so that if $c=1$ then nothing is done to the input (the simulation is vacuous) and if $c=0$ the simulation is really happening. The simulation uses the input bits $x_{n+1-s(n)\log^* n}\cdots x_n$ to store $w,w',p$ and $j$ (from the simulation), everything else is done in the actual work space of constant size. Whenever the simulation wants to write some value $a$ into an input position used for the simulation, it copies the value into the work space, it copies there the current value $d$ of the destination position, computes $\textit{SEL}(c,a,d)$ and replaces cards in the destination by the output of $\textit{SEL}(c,a,d)$. (Hence, if $c=0$ nothing has happened.) Reading a value can be done by copying the particular bit into the work space and then working with the copied cards. This way the input is undisturbed if $c=1$ and it is overwritten if $c=0$. At the end of simulation, the protocol copies the output bit $h$, which is the first bit of $w$ into the actual work space, and writes value 0 to all input bits $x_{n+1-s(n)\log^* n}\cdots x_n$ conditionally on $c=0$. (Bit values read from the storage, taking part in the vacuous computation, will be the same throughout the computation. So the simulations of the ${\sf NC^1}$ circuits implementing various steps of the computation will be secure.) Finally, the protocol computes $\textit{SEL}(c,h,g)$ which is the output of the protocol. All parts of the protocol can be done securely and obliviously. (This is true also when $c=0$ and the simulation of the Turing machine is bogus.) The protocol restores its committed input by the end of the computation. \end{proof} One can also use the technique of catalytic computation to construct protocols for functions not know to be in ${\sf NC^1}$. Buhrman et al. \cite{BCKLS,Cleve-phd} show how to use memory which contains some information for computation while restoring the memory to its original content by the end of the computation. For example, they can solve the connectivity on directed graphs this way, the problem $\textit{CONN}(G)$: Given an $n\times n$ adjacency matrix of a directed graph $G$ decide whether there is a path from vertex $1$ to vertex $n$. They present a polynomial-size program for $\textit{CONN}(G)$, which uses $3n^2+1$ work registers and $n^2$ input registers, each holding one bit of information. The program consists of instruction of the form \[ r_i \leftarrow r_i \oplus u \cdot v, \] where $u$ and $v$ are arbitrary registers different from $r_i$ or constants 0 and 1. The program is oblivious, so it is a straight line program consisting of such instructions. The program has the property that all registers are guaranteed to have the initial value by the end of the computation except for one specified work register which contains the output value. It is straightforward to implement each such an instruction by secure and robust protocol since the instructions are computable in ${\sf NC^1}$. This allows to design an oblivious, secure protocol of polynomial length with constant work space for a function $f' : \{0,1\}^{4n^2} \to \{0,1\}$ that is defined as: $f'(G_1,G_2,G_3,G_4)=1$ if and only if from the vertex $1$ we can reach the vertex $n$ in each of the graphs represented by adjacency matrices $G_1,G_2,G_3$ and $G_4$. Such a function is unlikely to be contained in ${\sf NC^1}$, as $\textit{CONN}(G)$ is known to be complete for \emph{nondeterministic} log-space computation. Hence, it is unlikely that protocols that are allowed to modify their input could be simulated by read-only protocols using similar resources. \section{More Efficient Input Encodings} \subsection{1-Card Encoding} In this section, we consider other ways how Alice and Bob can commit their input which use fewer cards. The first natural encoding is to represent each bit $1$ by face-down card $\heartsuit$ and bit $0$ by $\clubsuit$. These cards would be stored in front of the players in input positions $1,\dots,2n$. Whenever the players want to operate with the committed bit they need to extend it to 2-card representation. There are two ways we know how to do it. Niemi and Renvall \cite{niemi97} gave a protocol that is able to extend the bit without knowing its value. However, there is a small probability of leaking the value of the bit being extended. The probability is inversely proportional to the number of cards used for the protocol. Hence, one would need a large number of helping cards in order to make sure that the probability of leaking information is negligible. That would erase any savings from the 1-card representation. The other way which we use here is to allow the player who owns the particular input bit to extend it using a designated deck of two face-down cards $\clubsuit$ and $\heartsuit$. Once the bit is extended it can be copied by the protocol from Theorem~\ref{thm:CopyBit}, the first card of the first copy can be put back in the input position, the second card can be put back into the auxiliary deck, and the second copy can be used for further computation. The auxiliary deck containing the same cards as earlier should be shuffled by both players at the end of this procedure. The protocol is robust since a player cheating by extending the input bit by a wrong card will be caught in Step 4 of the copying protocol. For this procedure, we need to augment our set of actions by the action of extending a bit by a complementary card from a designated deck. This action can be performed by shuffling the auxiliary deck, then peeking at the value of the card we are extending, and selecting the complementary card by peeking at each card in the deck. With this operation in mind, we need to extend the definition of protocol security. We say a protocol is \emph{secure from Alice} if for any pair of inputs $(x,y)$ and $(x,y')$ to Alice and Bob, the distribution of the sequence of visible states of the protocol together with the sequence of cards seen by Alice while peeking at them during the extension action on inputs $(x,y)$ and $(x,y')$ is the same. Similarly, the protocol is \emph{secure from Bob} if for any pair of inputs $(x,y)$ and $(x',y)$ to Alice and Bob, the distribution of visible states and cards peeked at by Bob will be the same on both inputs $(x,y)$ and $(x',y)$. The protocol is secure if it is secure from both Alice and Bob. Using the extension action we can perform all read-only protocols that used the 2-card bit commitment of inputs even for inputs committed in 1-card representation. They will be secure as long as the player performing each extension is the owner of the input bit as seeing his/her input bits does not affect the security definition. Hence, the power of the model stays essentially the same with this modification. Security becomes more of an issue for protocols that are allowed to modify their inputs. Yet, we can prove a result similar to Theorem~\ref{thm:RWSim} for slightly modified function $f'$. Let $g:\{0,1\}^n \to \{0,1\}$ be in ${\sf NC^1}$, and $h:\{0,1\}^{n-s(n) \log^* n} \to \{0,1\}$ be a function computable by a Turing machine in space $O(s(n))$ and polynomial time, where $\log n \le s(n) \le n/2\log^* n$.. Define $f':\{0,1\}^n \to \{0,1\}$ as follows: $$ f'(x) = \left\{ \begin{array}{ll} g(x) & \mbox{if } x_{n+1-s(n)\log^* n}\cdots x_n \ne 0101\cdots 01, \\ h(x_1\cdots x_{n-s(n)\log^* n}) & \mbox{otherwise.} \end{array} \right. $$ We assume $s(n)\log^* n$ is even, and the first half of $x_{n+1-s(n)\log^* n}\cdots x_n$ is held by Alice and the other half by Bob. The other bits can be split between the players arbitrarily. \begin{restatable}{theorem}{rwsim} \label{thm:RWSim1} The function $f'$ defined above is computable by secure robust oblivious protocols of polynomial length that use a constant amount of work space and 1-card encoding of input bits. \end{restatable} \begin{proof} The protocol for $f'$ proceeds similarly to the one in Theorem~\ref{thm:RWSim}. It first verifies whether the input bits $x_{n+1-s(n)\log^* n}\cdots x_n$ differ from $0101\cdots 01$ (assuming their number is even) using protocol for ${\sf NC^1}$ functions. The output $c$ of the verification is encoded in 2-card representation in the work space. Then the protocol computes the value $g$ of $g(x)$ encoded in 2-card representation in the work space. Up until this point, we use the protocol described above to extend input bits into 2-card representations by the player who owns the input bit. Now we want to use the cards representing input bits $x_{n+1-s(n)\log^* n}\cdots x_n$ to simulate computation of a Turing machine $M$ for computing $h=h(x_1,\dots,x_{n- s(n)\log^* n})$ as in the previous proofs. We will use these input cards for storage when $c=0$ and when $c=1$ we will keep them intact. In the former case, we will eventually reset the input bits/cards to the initial state. Let $I$ be positions of cards which represent bits $x_1\cdots x_{n - s(n)\log^* n}$ at the beginning of the protocol. Thus, the cards on the positions $I$ represent (in the 1-card encoding) the input for $M$. These cards will be in a read-only regime during the whole computation. Let $J$ be the positions of cards representing $x_{n+1-s(n)\log^* n}\cdots x_n$. The cards on $J$ will represent in 2-card encoding the content of tapes of $M$ during the computation. Thus, $|J| = s(n)\log^* n$ but the cards on $J$ will represent $\frac{1}{2}s(n)\log^* n$ bits. As $x_{n+1-s(n)\log^* n}\cdots x_n = 0101\cdots 01$ (if $c = 0$), the cards on $J$ represent $\frac{1}{2}s(n)\log^* n$ zeros at the beginning of the protocol. The simulation proceeds in a similar way as the simulation in proof of Theorem~\ref{thm:RWSim}. For reading bits from $I$ that encode the input bits to $M$ we use the same 1-card extension protocol as above to copy them into work-space. Now, we need procedures that will read and write bits in 2-card representations from positions $J$. However, if $c = 1$ some two consecutive positions would not represent a bit correctly (the two cards on them would have the same suit). The read/write procedures need to work and be secure even in this case. The players cannot simply inspect the cards on positions $J$ because they may represent some intermediate results of the computation. First, we describe how to read a bit $b$ encoded in $J$. We want to create a 2-card representation of bit $b$ in work space if $c = 0$ or a valid 2-card representation of some bit if $c = 1$. The bit $b$ is represented by 2 cards $\alpha, \beta$ on positions in $J$. Note that $\alpha$ and $\beta$ can be of the same suit if $c = 1$. Suppose Alice owns the positions in $J$ representing the bit $b$, the case of Bob's positions is symmetric. First, Alice will add complementary cards to $\alpha$ and $\beta$ as follows. Alice prepares the sequence: $\clubsuit\cz \alpha \clubsuit\heartsuit \beta$, then she turns the second and fifth card face-down to get a sequence \[ \clubsuit ? \alpha \clubsuit ? \beta. \] Bob shuffles the six cards cyclically at random. Now, Alice extends the card preceding each $\clubsuit$ that is face-up (cards $\alpha$ and $\beta$) by a complementary card to the right taken from an auxiliary deck. Alice sees the suit of the cards $\alpha$ and $\beta$ during this action but she does not know their actual order. Bob shuffles the cards cyclically again and turns face-up the cards following the two $\clubsuit$ that are face-up. Now, by a cyclic shift, they rearrange the cards so that they look like \[ \clubsuit\cz \alpha \overline{\alpha} \clubsuit\heartsuit \beta \overline{\beta}, \] where $\overline{\alpha}$ and $\overline{\beta}$ are cards complementary to $\alpha$ and $\beta$, respectively. They can copy each of the card pairs $\alpha,\overline{\alpha}$ and $\beta,\overline{\beta}$ to verify that Alice used complementary cards and the pairs $\alpha,\overline{\alpha}$ and $\beta,\overline{\beta}$ indeed represent two bits in 2-card encodings. By following this protocol, Alice learns whether the two cards $\alpha,\beta$ have the same suit or are distinct. If the suits are the same she also learns the suit. However, in that situation $c=1$ and she already knew all this information. In the later case, she knows that the bits at those input positions are distinct, but she knew that already. She does not learn their relative order because of the shuffle by Bob. Thus, she does not know whether they were altered since the beginning of the protocol or not. To finish the read procedure, Alice copies the pair $\alpha,\overline{\alpha}$ (by the protocol of Theorem~\ref{thm:CopyBit}) to get two copies represented by cards $\alpha',\overline{\alpha'},\alpha'',\overline{\alpha''}$. She returns the cards $\alpha''$ and $\beta$ back to the positions in $J$ from which she moved the cards $\alpha$ and $\beta$ at the beginning. The cards $\alpha'$ and $\overline{\alpha'}$ are used further in the computation. Other cards ($\overline{\alpha''}, \overline{\beta}$) are moved back to the auxiliary deck. If the cards $\alpha$ and $\beta$ have different suits then the cards $\alpha',\overline{\alpha'}$ represent the bit $b$, as the card $\alpha$ and $\alpha'$ have the same suit. If the cards $\alpha$ and $\beta$ have the same suit then the cards $\alpha',\overline{\alpha'}$ are a valid representation of some bit $b'$. However, in that case $c = 1$ and the value of $b'$ is irrelevant for the computation. Bit values read from the storage, taking part in the bogus computation, will be consistent throughout the computation. Thus, the simulations of the ${\sf NC^1}$ circuits implementing various steps of the computation are secure. Now, we describe how to store a bit in 2-card encodings on to some positions in $J$. Again, suppose we want to store a bit $b$ on to positions owned by Alice and occupied by cards $\gamma_1$ and $\gamma_2$. Let $\alpha$ and $\beta$ be cards representing $b$. We want a procedure that will do the following. If $c = 0$ then the cards $\gamma_1$ and $\gamma_2$ are replaced by cards of the same suits as $\alpha$ and $\beta$, respectively. Otherwise, if $c = 1$ then the new cards need to have the same suits as $\gamma_1$ and $\gamma_2$. First, Alice will add complementary cards to $\gamma_1$ and $\gamma_2$ to get a sequence $\gamma_1,\overline{\gamma_1},\gamma_2,\overline{\gamma_2}$ (she proceeds in the same was as in the read procedure above). Let $d_1$ and $d_2$ be bits represented by $\gamma_1,\overline{\gamma_1}$ and $\gamma_2,\overline{\gamma_2}$, respectively. She creates two copies of $b$, negates the second one, and computes $a_1 = \textit{SEL}(c,b,d_1)$ and $a_2 = \textit{SEL}(c,1-b,d_2)$. Let $\delta_1,\overline{\delta_1}$ and $\delta_2,\overline{\delta_2}$ be cards representing $a_1$ and $a_2$ respectively. If $c = 0$ then the cards $\delta_1,\delta_2$ represent the bit $b$. If $c = 1$ then the cards $\delta_1$ and $\delta_2$ have the same suits as the cards $\gamma_1$ and $\gamma_2$, respectively. Thus, Alice moves the cards $\delta_1$ and $\delta_2$ into the positions of the cards $\gamma_1$ and $\gamma_2$ and moves the rest of the cards to the deck. To avoid leakage of information from the way Alice picks the cards from the auxiliary deck when picking a card of a particular suit, she proceeds as follows. She knows how many cards of that suit are in the deck. Thus, she shuffles the cards at random and then proceeds left to right to pick one of the cards of that suit uniformly at random. To achieve that she picks each card of the desired suit with probability $1/(k+1)$, where $k$ is the number of unseen cards of the desired suit still in the deck. This process guarantees that Alice will pick a card from a completely random position. In this way the protocol can use $x_{n+1-s(n)\log^* n}\cdots x_n$ to compute $h=h(x)$. After obtaining value $h$ it outputs $\textit{SEL}(c,h,g)$. \end{proof} Hence, also in the case of the 1-card representation of the input one can take advantage of the input cards to compute functions that seem unattainable with read-only protocols. \subsection{1/2-Card Encoding} In the 1/2-card encoding we represent value 1 by either $\heartsuit \times$ or $\times \clubsuit$, and value 0 by either $\clubsuit \times$ or $\times \heartsuit$. Here $\times$ represents an empty bit position. To commit her input Alice picks $n/2$ of her input bits, and for those input bits, she leaves the empty spot $\times$ in the position of $\heartsuit$, for the remaining bits she leaves the empty spot in place of $\clubsuit$ (in the 2-card encoding of the bit). This way, she uses exactly $n/2$ cards $\clubsuit$ and $\heartsuit$ to commit her input. It is easy to verify that for each bit there is exactly $1/2$ probability that the missing card will be on the left. Hence, the positions of the missing cards do not leak any information about her input. Bob proceeds in the same way to commit his input. After committing their inputs they can run any read-only protocol similar to the case of 1-card encoding. Whenever an input bit is needed it is copied into a 2-card representation by essentially the same protocol as in the case of 1-card encoding. This means that we need only $n+O(1)$ cards to compute any ${\sf NC^1}$ function on $n$-bit inputs. We do not know how to implement protocols which could modify their inputs. Modifying an input bit would require either picking the empty spot in the representation at random (which could lead to using substantially more cards of each type) or reusing the cards that are there. In the latter case we do not know how to do it without leaking information.
{'timestamp': '2020-10-19T02:19:35', 'yymm': '2010', 'arxiv_id': '2010.08445', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08445'}
arxiv
\section{Introduction}\label{section-introduction} Query evaluation is a fundamental task in databases and a vast literature is devoted to the complexity of this problem. However, for more demanding tasks such as producing the whole set of answers or computing aggregates on the query result (such as counting the number of answers), complexity bounds are often simply extrapolated from those for query evaluation; and until recently, few specific methods and tools had been developed to tackle these problems. Given a database $\A$ and a first-order query $q$, it may be not satisfactory enough to express complexity results in terms of the sizes of $\A$ and $q$ as it is often the case. The fact that the solution set $q(\A)$ may be of size exponential in the query is intuitively not sufficient to make the problem hard, and alternative complexity measures had to be found for query answering. In this direction, one way to define tractability is to assume that tuples of the query result can be generated one by one with some regularity, for example by ensuring a fixed delay between two consecutive outputs once a necessary precomputation has been done to construct a suitable index structure. This approach, that considers query answering as an enumeration problem, has deserved some attention over the last few years. In this vein, the best that one can hope for is constant delay, i.e., the delay depends only on the size of $q$ (but not on the size of $\A$). Surprisingly, a number of query evaluation problems have been shown to admit constant delay algorithms, usually preceded by a preprocessing phase that is linear or almost linear. This is the case when queries are evaluated over the class of structures of bounded degree~\cite{DurandG07, KS11}, over the class of structures of ``bounded expansion''~\cite{KazanaS13} and, more generally, over the class of nowhere dense structures~\cite{DBLP:conf/pods/SchweikardtSV18}. Similar results have been shown for monadic second-order logic over structures of bounded tree-width~\cite{Courcelle09,Bagan06,WL12} or for fragments of first-order logic over arbitrary structures~\cite{BDG07,Brault-Baron12}. However, as shown in~\cite{BDG07}, the fact that evaluation of boolean queries is easy does not guarantee the existence of such efficient enumeration algorithms in general: under some reasonable complexity assumption, there is no constant delay algorithm with linear preprocessing enumerating the answers of acyclic conjunctive queries (although it is well-known that the model checking of boolean acyclic queries can be done in linear time~\cite{Yannakakis81}). In this paper, we investigate the complexity of the enumeration, counting, and testing problems for first-order queries over classes of low degree. A class of relational databases has low degree if for all $\delta>0$, all sufficiently large databases in the class have degree at most $n^{\delta}$, where $n$ is the size of the database. Databases of bounded degree or of degree bounded by $(\log n)^c$, for any fixed constant $c$, are examples of low degree classes. However, it turns out to be incomparable with the class of nowhere dense databases mentioned above. It has been proved in~\cite{Grohe-STACS01} that over a class of databases of low degree, first-order boolean queries can be checked in pseudo-linear time, i.e., for all $\epsilon>0$ there is an algorithm running in time bounded by $O(n^{1+\epsilon})$ checking the given first-order query. In this paper, we prove that counting the number of answers to a query can be done in pseudo-linear time, and that enumerating the answers to a query can be done with constant delay after a pseudo-linear time preprocessing. We also prove that testing membership of a tuple to a query result can be done in constant time after a pseudo-linear time preprocessing. We adopt a uniform approach to prove all these results by using at the heart of the preprocessing phases a quantifier elimination method that reduces our different problems to their analog but for colored graphs and quantifier-free queries. With such a tool, we can then focus within each specific task on very simple instances. Over a class of databases of low degree, the difficulty is to handle queries requiring that in all its answers, some of its components are far away from each other. When this is not the case, for instance when in all answers all its components are within short distance from the first component, then the low degree assumption implies that there are only few answers in total and those can be computed in pseudo-linear time. In the difficult case, the number of answers may be exponential in the arity of the query and the naive evaluation algorithm may spend too much time processing tuples with components close to each other. To avoid this situation, we introduce suitable functions that can be precomputed in pseudo-linear time, and that allow us to jump in constant time from a tuple with components close to each other to a correct answer. \textbf{Related work.} \ Enumerating the answers to a boolean query $q$ over a database \A is more general than testing whether $q$ holds on \A, a problem also known as the model checking problem. An enumeration algorithm with constant delay after a preprocessing phase taking pseudo-linear time, or even polynomial time, induces a model checking algorithm that is \emph{fixed-parameter tractable} (FPT), i.e, works in time $f(q){\cdot}\size{\A}^c$ for some constant $c$ and some function $f$ depending only on the class of databases. There is a vast literature studying the model checking problem for first-order logic aiming at finding FPT algorithms for larger and larger classes of databases. Starting from classes of databases of bounded degree, or bounded treewidth, FPT algorithms were derived for classes of databases having bounded expansion~\cite{DvorakKralThomas10} (see also~\cite{KazanaS13}). Actually, recently an FPT algorithm has been obtained for classes of databases known as ``nowhere dense'', generalizing all the previously known results~\cite{GKS13}. This last result is in a sense ``optimal'' as it is known that if a class of databases is closed under substructures and has no FPT model checking algorithm then it is somewhere dense~\cite{KD09}, modulo some reasonable complexity hypothesis. Classes of databases of low degree do not belong to this setting. It is easy to see that they are neither nowhere dense nor closed under substructures (see Section~\ref{subsection:LowDegree}). Our algorithms build on the known model checking algorithm for low degree databases~\cite{Grohe-STACS01}. They generalize the known enumeration algorithms for databases of bounded degree~\cite{DurandG07, KS11}. This paper is the journal version of~\cite{DBLP:conf/pods/DurandSS14}. There is an important difference with the conference version. In the conference version we needed the extra hypothesis that even though we would use only a memory of pseudo-linear size, a total amount of memory of quadratic size was necessary for our algorithms to work. This extra memory is no longer necessary here thanks to the data structure constructed in Theorem~\ref{thm-storing-complete}. This makes the technical lemma slightly more complicated to state, but does not affect the general results. \medskip \textbf{Organization.} \ We fix the basic notation and formulate our main results in Section~\ref{section-prelim}. In Section~\ref{section-main} we present the algorithms for counting, testing, and enumerating answers to first-order queries over classes of structures of low degree. These algorithms rely on a particular preprocessing which transforms a first-order query on a database into a quantifier-free query on a colored graph. The result is stated in Section~\ref{subsection:qeli}, while its proof is presented in Section~\ref{section-main-proofs}. We conclude in Section~\ref{section-conclusion}. \section{Preliminaries and Main Results}\label{section-prelim} We write $\NN$ to denote the set of non-negative integers, and we let $\NNpos\deff\NN\setminus\set{0}$. $\QQ$ denotes the set of rationals, and $\QQpos$ is the set of positive rationals. \subsection{Databases and queries} A database is a finite relational structure. A \emph{relational signature} $\sigma$ is a finite set of relation symbols $R$, each of them associated with a fixed \emph{arity} $\ar(R)\in\NNpos$. A \emph{relational structure} \A over $\sigma$, or a $\sigma$-structure (we omit to mention $\sigma$ when it is clear from the context) consists of a non-empty finite set $\dom(\A)$ called the \emph{domain} of \A, and an $\ar(R)$-ary relation $R^\A\subseteq \dom(\A)^{\ar(R)}$ for each relation symbol $R\in\sigma$. The degree of a structure \A, denoted $\degree(\A)$, is the degree of the Gaifman graph associated with \A (i.e., the undirected graph with vertex set $\dom(\A)$ where there is an edge between two nodes if they both occur in a tuple that belongs to a relation of \A). With this definition, in a structure with $n$ domain elements and of degree $d$, each $r$-ary relation may have at most $n\cdot (d{+}1)^{r-1}$ tuples. In the sequel we only consider structures of degree $\geq 2$. As structures of degree~1 are quite trivial, this is without loss of generality. We define the \emph{size} $\size{\A}$ of $\A$ as $\size{\A}= |\sigma|+|\dom(\A)|+\sum_{R\in\sigma} |R^{\A}|{\cdot} \ar(R)$. It corresponds to the size of a reasonable encoding of \A. We assume that the input structure \A is presented in a way such that given a relation symbol $R$ in the signature we can directly access the list of tuples in $R^\A$ (i.e.\ without reading the remaining tuples). The cardinality of \A, i.e.\ the cardinality of its domain, is denoted by $|\A|$. By \emph{query} we mean a formula of $\FO(\sigma)$, the set of all first-order formulas of signature $\sigma$, for some relational signature $\sigma$ (again we omit $\sigma$ when it is clear from the context). For $\varphi\in \FO$, we write $\varphi(\bar x)$ to denote a query whose free variables are $\bar x$, and the number of free variables is called the \emph{arity of the query}. A \emph{sentence} is a query of arity 0. Given a structure \A and a query $\varphi$, an \emph{answer} to $\varphi$ in \A is a tuple $\bar a$ of elements of $\dom(\A)$ such that $\A \models \varphi(\bar a)$. In the special case where $\varphi$ is a sentence, it is either true of false in \A, and the former is denoted $\A \models \varphi$ and the latter is denoted $\A\not\models\varphi$. We write $\varphi(\A)$ for the set of answers to $\varphi$ in \A, i.e. $\varphi(\A)=\setc{\bar a}{\A \models \varphi(\bar a)}$. As usual, $|\varphi|$ denotes the size of $\varphi$. Let \Class be a class of structures. The model checking problem of \FO over \Class is the computational problem of given a {\bf sentence} $\varphi\in\FO$ and a database $\A\in\Class$ to test whether $\A\models \varphi$. Given a $k$-ary query $\varphi$, we care about ``enumerating'' $\varphi(\A)$ efficiently. Let \Class be a class of structures. The \emph{enumeration problem of $\varphi$ over \Class} is, given a database $\A\in\Class$, to output the elements of $\varphi(\A)$ one by one with no repetition. The time needed to output the first solution is called the \emph{preprocessing time}. The maximal time between any two consecutive outputs of elements of $\varphi(\A)$ is called \emph{the delay}. We are interested here in enumeration algorithms with pseudo-linear preprocessing time and constant delay. We now make these notions formal. \subsection{Model of computation and enumeration}\label{subsection:RAM} We use Random Access Machines (RAMs) with addition and uniform cost measure as a model of computation. For further details on this model and its use in logic see~\cite{FlumGrohe-ParameterizedComplexity,GrandjeanOlive04}. In the sequel we assume that the input relational structure comes with a linear order on the domain. If not, we use the one induced by the encoding of the structure as an input to the RAM\@. Whenever we iterate through all nodes of the domain, the iteration is with respect to the initial linear order. The linear order induces a lexicographical order on tuples of elements of the domain. Our algorithms over RAMs will take as input a query $\varphi$ of size $k$ and a structure \A of size $n$. We adopt the data complexity point of view and say that a problem can be solved in \emph{linear time} (respectively, \emph{constant time}) if it can be solved by an algorithm outputting the solution within $f(k){\cdot} n$ steps (respectively, $f(k)$ steps), for some function $f$. We also say a problem can be solved in \emph{pseudo-linear time} if, for all $\epsilon\in \QQpos$, there is an algorithm solving it within $f(k,\epsilon){\cdot} n^{1+\epsilon}$ steps, for some function $f$. We will often compute partial $k$-ary functions $f$ associating a value to a tuple of nodes of the input graph. Such functions can be easily implemented in the RAM model using $k$-dimensional cubes allowing to retrieve the value of $f$ in constant time. This requires a memory usage of $O(n^k)$ and an initialization process of $O(n^k)$. However our functions will have a domain of size pseudo-linear and can be computed in pseudo-linear time. The following theorem states that we can use the RAM model to build a data structure that stores our functions in a more efficient way. {The data structure is a trie of depth $\frac{1}{\e}$ and of degree $n^\e$ where each pair (key,value) is a tuple $\bar a$ in the domain of $f$ and its image $b=f(\bar a)$. The details can be found in~\cite{DBLP:conf/pods/SchweikardtSV20}.} \begin{thm}[Storing Theorem]\label{thm-storing-complete} For every fixed $n,k\in\NN$ and $\epsilon>0$, there is a data structure that stores the value of a $k$-ary function $f$ of domain $\dom(f)\subseteq [n]^k$ with: \begin{itemize} \item computation time and storage space $O(|\dom(f)|\cdot n^{\e})$, \item lookup time only depending on $k$ and $\e$, \end{itemize} Here, lookup means that given a tuple $\bar a\in [n]^k$, the algorithm either answers $b$ if $\bar a\in\dom(f)$ and $f(\bar a)=b$, or \void otherwise. \end{thm} An important consequence of Theorem~\ref{thm-storing-complete} is that, modulo a preprocessing in time pseudo-linear in the size of the database, we can test in constant time whether an input tuple is a fact of the database: \begin{cor}\label{cor-test} Let \A be a database over the schema $\sigma$. Let $\e >0$. One can compute in time $O(d^r n^{1+\e})$ a data structure such that on input of a tuple $\bar a$ and a relation symbol $R \in \sigma$ one can test whether $\A \models R(\bar a)$ in time $O(1)$, where $n=|\dom(\A)|$, $d=\degree(\A)$, and $r$ is a number that only depends on $\sigma$. \end{cor} \begin{proof} Immediate from Theorem~\ref{thm-storing-complete}, as the number of tuples in an $r$-ary relation of a $\sigma$-structure whose Gaifman graph has degree $d$ is at most $(d{+}1)^{r-1}n$. \end{proof} Note that a simple linear time preprocessing would provide a data structure allowing for a test as in Corollary~\ref{cor-test} in time $O(d)$ {(to see how, just think of the special case where $\A$ only contains one binary relation $R$. In this case, the preprocessing can build an adjacency list representation where upon input of an $a$ we can access in time $O(1)$ the first element of a list of all those $b$ satisfying $R(a,b)$. This list has length at most $d$. Upon input of a tuple $(a,b)$ we access $a$'s adjacency list and check if it contains $b$).} {With the help of the Storing Theorem we get a test in constant time,} i.e.\ depending only on $\e$ and $\sigma$ and not on $d$. We say that the \emph{enumeration problem} of \FO over a class \Class of structures can be solved with \emph{constant delay after a pseudo-linear preprocessing}, if it can be solved by a RAM algorithm which, on input $\e >0$, $q\in\FO$ and $\A\in\Class$, can be decomposed into two phases: \begin{itemize} \itemsep1pt \parskip0pt \parsep0pt \item a preprocessing phase that is performed in time $f(\e,|q|)\cdot \size{\A}^{1+\epsilon}$ for some function $f$, and \item an enumeration phase that outputs $q(\A)$ with no repetition and a delay depending only on $q$, $\e$, and \Class between any two consecutive outputs. The enumeration phase has full access to the output of the preprocessing phase and can use extra memory whose size depends only on $q$, $\e$ and \Class. \end{itemize} \noindent Notice that if we can enumerate $q$ with constant delay after a pseudo-linear preprocessing, then all answers can be output in time $g(|q|,\epsilon)\cdot(\size{\A}^{1+\epsilon}+|q(\A)|)$, for some function $g$, and the first solution is computed in pseudo-linear time. In the particular case of boolean queries, the associated model checking problem must be solvable in pseudo-linear time. \begin{exa}\label{example-def} To illustrate these notions, consider the binary query $q(x,y)$ over colored graphs computing the pairs of nodes $(x,y)$ such that $x$ is \emph{blue}, $y$ is \emph{red}, and there is no edge from $x$ to $y$. It can be expressed in \FO by \begin{equation*} B(x) \land R(y) \land \lnot E(x,y). \end{equation*} A naive algorithm for evaluating $q$ would iterate through all blue nodes, then iterate through all red nodes, check if they are linked by an edge and, if not, output the resulting pair, otherwise try the next pair. With our RAM model, after a linear preprocessing, we can easily iterate through all blue nodes with a constant delay between any two of them and similarly for red nodes. By Corollary~\ref{cor-test}, we can test in constant time whether there is an edge between any two nodes. The problem with this algorithm is that many pairs of appropriate color may be false hits. Hence the delay between two consecutive outputs may be arbitrarily large. If the degree is assumed to be bounded by a fixed constant, then the above algorithm enumerates all answers with constant delay, since the number of false hits for each blue node is bounded by the degree. We will see that for structures of low degree we can modify the algorithm in order to achieve the same result. \end{exa} \subsection{Classes of structures of low degree}\label{subsection:LowDegree} Intuitively a class \Class of structures has \emph{low degree} if for all $\delta>0$, all but finitely many structures \A of \Class have degree at most $|\A|^\delta$ (see~\cite{Grohe-STACS01}). More formally, $\Class$ has low degree if for every $\delta \in \QQpos$ there is an $n_\delta\in\NNpos$ such that all structures $\A\in\Class$ of cardinality $|\A|\geq n_\delta$ have $\degree(\A)\leq |\A|^\delta$. If there is a computable function associating $n_\delta$ from $\delta$ then we furthermore say that the class is effective. For example, for every fixed number $c>0$, the class of all structures of degree at most $(\log n)^c$ is of low degree and effective. Clearly, an arbitrary class $\Class$ of structures can be transformed into a class $\Class'$ of low degree by padding each $\A\in \Class$ with a suitable number of isolated elements (i.e., elements of degree 0). Therefore classes of low degree are usually \emph{not} closed under taking substructures. In particular if we apply the padding trick to the class of cliques, we obtain a class of low degree that is not in any of the classes with known low evaluation complexity such as the ``nowhere dense'' case mentioned in the introduction. Notice that $\degree(\A)\leq |\A|^\delta$ implies that $\size{\A}\leq c{\cdot}|\A|^{1+\delta\cdot r}$, where $r$ is the maximal arity of the signature and $c$ is a number only depending on $\sigma$. It is known that on classes of graphs of low degree, model checking of first-order sentences can be done in pseudo-linear time. We will actually need the following stronger result: \begin{thm}[Grohe~\cite{Grohe-STACS01}]\label{thm:grohe-low-degree} There is a computable function $h$ such that on input of a structure $\A\in\Class$ of degree $d$ and a sentence $q\in\FO$, one can test in time $h(|q|){\cdot} |\A| {\cdot} d^{h(|q|)}$ whether $\A\models q$. In particular, if $\Class$ is a class of structures of low degree, then there is a function $g$ such that, given a structure $\A\in\Class$, a sentence $q\in\FO$, and $\epsilon>0$, one can check if $\A\models q$ in time $g(|q|,\epsilon){\cdot}|\A|^{1+\epsilon}$. If $\Class$ is effective then $g$ is computable. \end{thm} \subsection{Our results} We are now ready to state our main results, which essentially lift Theorem~\ref{thm:grohe-low-degree} to non-boolean queries and to counting, testing, and enumerating their answers. Our first result is that we can count the number of answers to a query in pseudo-linear time. \begin{thm}\label{thm:counting} Let \Class be a class of structures of low degree. There is a function $g$ such that, given a structure $\A\in\Class$, a query $q\in\FO$, and $\e>0$, one can compute $|q(\A)|$ in time $g(|q|,\epsilon){\cdot} |\A|^{1+\epsilon}$. If \Class is effective then g is computable. \end{thm} Our second result is that we can test whether a given tuple is part of the answers in constant time after a pseudo-linear time preprocessing. \begin{thm}\label{thm:testing} Let \Class be a class of structures of low degree. There is a function $g$ such that, given a structure $\A\in\Class$, a query $q\in\FO$, and $\e>0$, one can compute in time $g(|q|,\epsilon){\cdot} |\A|^{1+\epsilon}$ a data structure such that, on input of any $\bar a$, one can then test in time $g(|q|,\epsilon)$ whether $\bar a\in q(\A)$. If \Class is effective then g is computable. \end{thm} Finally, we show that we can enumerate the answers to a query with constant delay after a pseudo-linear time preprocessing. \begin{thm}\label{thm:enum} Let \Class be a class of structures of low degree. There is a function $g$ such that, given a structure $\A\in \Class$, a query $q\in \FO$ and $\e>0$, the enumeration problem of $q$ over \A can be solved with delay $g(|q|,\epsilon)$ after a preprocessing running in time $g(|q|,\epsilon){\cdot} |\A|^{1+\epsilon}$. If \Class is effective then g is computable. \end{thm} \subsection{Further notation} We close this section by fixing technical notations that will be used throughout this paper. For a structure $\A$ we write $\dist^\A(a,b)$ for the distance between two nodes $a$ and $b$ of the Gaifman graph of $\A$. For an element $a\in\dom(\A)$ and a number $r\in\NN$, the \emph{$r$-ball} around $a$ is the set $N_r^\A(a)$ of all nodes $b\in\dom(\A)$ with $\dist^\A(a,b)\leq r$. The \emph{$r$-neighborhood} around $a$ is the induced substructure $\N_r^\A(a)$ of $\A$ on $N_r^\A(a)$. Note that if $\A$ is of degree $\leq d$ for $d\geq 2$, then $|N_r^\A(a)|\leq \sum_{i=0}^r d^i < d^{r+1}$. \section{Evaluation algorithms}\label{section-main} In this section, we present our algorithms for counting, testing, and enumerating the solutions to a query (see Sections~\ref{subsection:Counting},~\ref{subsection:Testing}, and~\ref{subsection:Enumeration}). They all build on the same preprocessing algorithm which runs in pseudo-linear time and which essentially reduces the input to a quantifier-free query over a suitable signature (see Section~\ref{subsection:qeli}). However, before presenting these algorithms, we start with very simple cases. \subsection{Computing the neighborhoods} Unsurprisingly, all our algorithms will start by computing the neighborhood $\N_r^\A(a)$ for all the elements $a$ of the input structure \A for a suitable constant $r$ depending only on $q$. We actually do not need to compute $\N^\A_r(a)$ but only $\N^{\A\downarrow q}_r(a)$ where $\Aq$ is the restriction of $\A$ to the relational symbols occurring in $q$. The next lemma states that all these neighborhoods can be computed in reasonable time. \begin{lem}\label{lemma-compute-neigh} There is an algorithm which, at input of a structure \A, a query $q$ and a number $r$ computes $\N^{\A\downarrow q}_r(a)$ for all elements $a$ of the domain of \A in time $O(|q| \cdot n \cdot d^{h(r,|q|)})$, where $n=|\dom(\A)|$, $d=\degree(\A)$ and $h$ is a computable function. \end{lem} \begin{proof} We first compute the Gaifman graph associated to $\Aq$. We consider each relation symbol $R$ occurring in $q$. We scan $R^\A$ and for each of its tuples we add the corresponding clique to the Gaifman graph. As each element $a$ of $\dom(\A)$ can appear at the first component of at most $(d+1)^{\ar(R)-1}$ tuples of $R^\A$, the total time is $|q| \cdot n \cdot (d+1)^{k-1}$ where $k$ is the maximal arity of the relation symbols occurring in $q$. This yields a graph with $n$ nodes and degree $d$ corresponding to the Gaifman graph of $\Aq$. From this graph we easily derive, in time $O(n \cdot d)$, a structure associating to each node $a \in \dom(\A)$ the set of its immediate neighbors, i.e $N_1^{\A\downarrow q}(a)$. With $r$ steps of transitive closure computation we get a structure associating to each node $a\in\dom(\A)$ the set $N^{\A\downarrow q}_r(a)$ of nodes at distance at most $r$ from $a$. This can be done in time $O(n\cdot d^r)$. With an extra scan over the database we can derive $\N_r^{\A\downarrow q}(a)$ from $N^{\A\downarrow q}_r(a)$. Altogether we get the desired time bounds. \end{proof} \subsection{Connected conjunctive queries}\label{subsection:warm-up} As a warm-up for working with classes of structures of low degree, we first consider the simple case of queries which we call \emph{connected conjunctive queries}, and which are defined as follows. A \emph{conjunction} is a query $\gamma$ which is a conjunction of relational atoms and potentially negated \emph{unary} atoms. Note that the query of Example~\ref{example-def} is not a conjunction as it has a binary negated atom. With each conjunction $\gamma$ we associate a \emph{query graph} $H_\gamma$. This is the undirected graph whose vertices are the variables $x_1,\ldots,x_k$ of $\gamma$, and where there is an edge between two vertices $x_i$ and $x_j$ iff $\gamma$ contains a relational atom in which both $x_i$ and $x_j$ occur. We call the conjunction $\gamma$ \emph{connected} if its query graph $H_\gamma$ is connected. A \emph{connected conjunctive query} is a query $q(\ov{x})$ of the form $\exists \ov{y}\, \gamma(\ov{x},\ov{y})$, where $\gamma$ is a \emph{connected conjunction} in which all variables of $\ov{x},\ov{y}$ occur (here, $|\ov{y}|=0$ is allowed). The next simple lemma implies that over a class of structures of low degree, connected conjunctive queries can be evaluated in pseudo-linear time. It will be used in several places throughout this paper: in the proof of Proposition~\ref{prop:connected-cqs_low-degree}, and in the proofs for our counting and enumeration results in Sections~\ref{subsection:Counting} and~\ref{subsection:Enumeration}. \begin{lem}\label{lemma:connected-cqs} There is an algorithm which, at input of a structure $\A$ and a connected conjunctive query $q(\ov{x})$ computes $q(\A)$ in time $O(|q|{\cdot}n{\cdot}d^{h(|q|)})$, where $n=|\dom(\A)|$, $d=\degree(\A)$, and $h$ is a computable function. \end{lem} \begin{proof} Let $q(\ov{x})$ be of the form $\exists \ov{y}\, \gamma(\ov{x},\ov{y})$, for a connected conjunction $\gamma$. Let $k=|\ov{x}|$ be the number of free variables of $q$, let $\ell=|\ov{y}|$, and let $r=k+\ell$. In view of Lemma~\ref{lemma-compute-neigh} we can assume that all the neighborhoods $\N^{\A\downarrow q}(a)$ have been computed. In order to simplify the notations, in the rest of the proof we will write $\N_r^{\A}(a)$ instead of $\N_r^{\A\downarrow q}(a)$. Note that since $\gamma$ is connected, for every tuple $\ov{c}\in\gamma(\A)$ the following is true, where $a$ is the first component of $\ov{c}$. All components $c'$ of $\ov{c}$ belong to the $r$-neighborhood $\N^\A_r(a)$ of $a$ in $\dom(\A)$. Thus, $q(\A)$ is the disjoint union of the sets \[ S_a \ \deff \ \big\{\, \ov{b} \in q(\N^{\A}_r(a)) \, : \, \text{the first component of $\ov{b}$ is $a$}\,\big\}, \] for all $a\in \dom(\A)$. For each $a\in \dom(\A)$, the set $S_a$ can be computed as follows: \begin{me} \item Initialize $S_a\deff \emptyset$. \item Use a brute-force algorithm that enumerates all $k$-tuples $\ov{b}$ of elements in $\N^{\A}_r(a)$ whose first component is $a$. For each such tuple $\ov{b}$, use a brute-force algorithm that checks whether $\N^{\A}_r(a) \models q(\ov{b})$. If so, insert $\ov{b}$ into $S_a$ Note that the number of considered tuples $\ov{b}$ is $\leq d^{(r+1)(k-1)}$. And checking whether $\N^{\A}_r(a) \models q(\ov{b})$ can be done in time $O(|\gamma|{\cdot}d^{(r+1)\ell})$: for this, enumerate all $\ell$-tuples $\ov{c}$ of elements in $\N_r^{\A}(a)$ and take time $O(|\gamma|)$ to check whether $\gamma(\ov{x},\ov{y})$ is satisfied by the tuple $(\ov{b},\ov{c})$. Thus, we are done after $O(|\gamma|{\cdot} d^{r^2})$ steps. \end{me} In summary, we can compute $q(\A) = \bigcup_{a\in A} S_a$ in time $O(n{\cdot}|q|{\cdot} d^{h(|q|)})$, for a computable function~$h$. \end{proof} As an immediate consequence we can compute in pseudo-linear time the answers to a connected conjunctive query over a class of structures of low degree. \begin{prop}\label{prop:connected-cqs_low-degree} Let $\Class$ be a class of structures of low degree. Given a structure $\A\in\Class$, a connected conjunctive query $q$, and $\e>0$, one can compute $q(\A)$ in time $g(|q|,\e)\cdot |\A|^{1+\e}$ for some function $g$ which is computable when $\Class$ is effective. \end{prop} \begin{proof} We use the algorithm provided in Lemma~\ref{lemma:connected-cqs}. To see that the running time is as claimed, we use the assumption that $\Class$ is of low degree: for every $\delta>0$ there is an $m_\delta\in\NNpos$ such that every structure $\A\in \Class$ of cardinality $|\A|\geq m_\delta$ has $\degree(\A)\leq |\A|^\delta$. For a given $\epsilon>0$ we let $\delta\deff \frac{\epsilon}{h(|q|)}$ and define $n_\epsilon\deff m_\delta$. Then, every $\A\in\Class$ with $|\A|\geq n_\epsilon$ has $\degree(\A)\leq |\A|^{\epsilon/h(|q|)}$. Thus, on input of $\A$ and $q$, the algorithm from Lemma~\ref{lemma:connected-cqs} has running time $O(|q|{\cdot} |\A|^{1+\epsilon})$ if $|\A| \geq n_\epsilon$ and takes time bounded by $O(|q|{\cdot} n_\epsilon^{1+h(q)})$ otherwise. This gives the bounds claimed by the proposition with a computable function $g$ as soon as we can compute $n_\e$. \end{proof} The method of the proof of Proposition~\ref{prop:connected-cqs_low-degree} above will be used several times in the paper. \subsection{Quantifier elimination and normal form}\label{subsection:qeli} In this section, we make precise the quantifier elimination approach that is at the heart of the preprocessing phase of the query evaluation algorithms of our paper. A signature is \emph{binary} if all its relation symbols have arity at most 2. A \emph{colored graph} is a finite relational structure over a binary signature. \begin{prop}~\label{prop-quantifier-elim-detailed} There is an algorithm which, at input of a structure $\A$, a first-order query $\varphi(\ov{x})$, and $\e>0$, produces a binary signature $\tau$ (containing, among other symbols, a binary relation symbol $E$), a colored graph $\G$ of signature $\tau$, an $\FO(\tau)$-formula $\psi(\ov{x})$, a mapping $f$, and a data structure such that the following is true for $k=|\ov{x}|$, $n=|\dom(\A)|$, $d=\degree(\A)$ and $h$ some computable function: \begin{enumerate} \item\label{item:psi-form:prop-quantifier-elim-detailed} $\psi$ is quantifier-free. Furthermore, $\psi$ is of the form \,$(\psi_{1} \und \psi_{2})$, where $\psi_{1}$ states that no distinct free variables of $\psi$ are connected by an $E$-edge, and $\psi_{2}$ is a positive boolean combination of unary atoms. \item\label{item:psi-comput:prop-quantifier-elim-detailed} $\tau$ and $\psi$ are computed in time and space $h(|\varphi|){\cdot} n{\cdot} d^{h(|\varphi|)}$.\\ Moreover, $|\tau|\leq h(|\varphi|)$ and $|\psi|\leq h(|\varphi|)$. \item\label{item:G:prop-quantifier-elim-detailed} $\G$ is computed in time and space $h(|\varphi|){\cdot} n{\cdot} d^{h(|\varphi|)}$. \\ Moreover, $\degree(\G)\leq d^{h(|\varphi|)}$. \item\label{item:f:prop-quantifier-elim-detailed} $f$ is an injective mapping from $\dom(\A)^k$ to $\dom(\G)^k$ such that $f$ is a bijection between $\varphi(\A)$ and $\psi(\G)$. The data structure representing $f$ can be computed in time and space $h(|\varphi|){\cdot} n^{1+\e}{\cdot} d^{h(|\varphi|)}$ and can then be used as follows: on input of any tuple $\bar a \in \dom(\A)^k$, the tuple $f(\ov{a})$ can be computed in time $O(k^2)$; and on input of any tuple $\ov{v}\in \psi(\G)$, the tuple $f^{-1}(\ov{v})$ can be computed in time $O(k^2)$. \end{enumerate} \end{prop} \noindent The proof of Proposition~\ref{prop-quantifier-elim-detailed} is long and technical and of a somewhat different nature than the results we now describe. It is postponed to Section~\ref{section-main-proofs}. However, this proposition is central in the proofs of the results below. \subsection{Counting}\label{subsection:Counting} Here we consider the problem of counting the number of solutions to a query on low degree structures. A \emph{generalized conjunction} is a conjunction of relational atoms and negated relational atoms (hence, also atoms of arity bigger than one may be negated, and the query of Example~\ref{example-def} is a generalized conjunction). \begin{exa}\label{example-counting} Before moving to the formal proof of Theorem~\ref{thm:counting}, consider again the query $q$ from Example~\ref{example-def}. Recall that it computes the pairs of blue-red nodes that are not connected by an edge. To count its number of solutions over a class of structures of low degree we can proceed as follows. We first consider the query $q'(x,y)$ returning the set of blue-red nodes that \emph{are} connected. In other words, $q'$ is \begin{equation*} B(x) \land R(y) \land E(x,y). \end{equation*} Notice that this query is a connected conjunction. Hence, by Proposition~\ref{prop:connected-cqs_low-degree} its answers can be computed in pseudo-linear time and therefore we can also count its number of solutions in pseudo-linear time. It is also easy to compute in pseudo-linear time the number of pairs of blue-red nodes. The number of answers to $q$ is then the difference between these two numbers. \end{exa} The proof sketch for Theorem~\ref{thm:counting} goes as follows. Using Proposition~\ref{prop-quantifier-elim-detailed} we can assume modulo a pseudo-linear preprocessing that our formula is quantifier-free and over a binary signature. Each connected component is then treated separately and we return the product of all the results. For each connected component we eliminate the negated symbols one by one using the trick illustrated in Example~\ref{example-counting}. The resulting formula is then a connected conjunction that is treated in pseudo-linear time using Proposition~\ref{prop:connected-cqs_low-degree}. \begin{lem}\label{lemma:counting-graphs} There is an algorithm which, at input of a colored graph $\G$ and a generalized conjunction $\gamma(\ov{x})$, computes $|\gamma(\G)|$ in time $O(2^m{\cdot}|\gamma|{\cdot}n{\cdot}d^{h(|\gamma|)})$, where $h$ is a computable function, $m$ is the number of negated binary atoms in $\gamma$, $n=|\dom(\G)|$, and $d=\degree(\G)$. \end{lem} \begin{proof} By induction on the number $m$ of \emph{negated} binary atoms in $\gamma$. The base case for $m{=}0$ is obtained as follows. We start by using $O(|\gamma|)$ steps to compute the query graph $H_\gamma$ and to compute the connected components of $H_\gamma$. In case that $H_\gamma$ is connected, we can use Lemma~\ref{lemma:connected-cqs} to compute the entire set $\gamma(\G)$ in time $O(|\gamma|{\cdot}n{\cdot}d^{h(|\gamma|)})$, for a computable function $h$. Thus, counting $|\gamma(\G)|$ can be done within the same time bound. In case that $\gamma$ is not connected, let $H_1,\ldots,H_\ell$ be the connected components. For each $i\in\set{1,\ldots,\ell}$ let $\ov{x}_i$ be the tuple obtained from $\ov{x}$ by removing all variables that do not belong to $H_i$. Furthermore, let $\gamma_i(\ov{x}_i)$ be the conjunction of all atoms or negated unary atoms of $\gamma$ that contain variables in $H_i$. Note that $\gamma(\ov{x})$ is equivalent to $\Und_{i=1}^\ell \gamma_i(\ov{x}_i)$, and \[ |\gamma(\G)| \ \ = \ \ \prod_{i=1}^\ell |\gamma_i(\G)|. \] Since each $\gamma_i$ is connected, we can compute $|\gamma_i(\G)|$ in time $O(|\gamma_i|{\cdot}n{\cdot}d^{h(|\gamma_i|)})$ by using the algorithm of Lemma~\ref{lemma:connected-cqs}. We do this for each $i\in\set{1,\ldots,\ell}$ and output the product of the values. In summary, we are done in time $O(|\gamma|{\cdot}n{\cdot}d^{h(|\gamma|)})$ for the base case $m=0$. For the induction step, let $\gamma$ be a formula with $m{+}1$ negated binary atoms. Let $\nicht R(x,y)$ be a negated binary atom of $\gamma$, and let $\gamma_1$ be such that \begin{eqnarray*} \gamma & \ = \ & \gamma_1 \ \und \ \nicht R(x,y), \qquad\text{and let} \\ \gamma_2 & \ \deff \ & \gamma_1 \ \und \ R(x,y). \end{eqnarray*} Clearly, $|\gamma(\G)| = |\gamma_1(\G)| - |\gamma_2(\G)|$. Since each of the formulas $\gamma_1$ and $\gamma_2$ has only $m$ negated binary atoms, we can use the induction hypothesis to compute $|\gamma_1(\G)|$ and $|\gamma_2(\G)|$ each in time $O(2^m{\cdot}|\gamma|{\cdot}n{\cdot}d^{h(|\gamma|)})$. The total time used for computing $|\gamma(\G)|$ is thus $O(2^{m+1}{\cdot}|\gamma|{\cdot}n{\cdot}d^{h(|\gamma|)})$. \end{proof} By using Proposition~\ref{prop-quantifier-elim-detailed}, we can lift this to arbitrary structures and first-order queries: \begin{prop}\label{prop:counting} There is an algorithm which at input of a structure $\A$ and a first-order query $\varphi(\ov{x})$ computes $|\varphi(\A)|$ in time $h(|\varphi|){\cdot}n{\cdot}d^{h(|\varphi|)}$, for a computable function $h$, where $n=|\dom(\A)|$ and $d=\degree(\A)$. \end{prop} \begin{proof} We first use the algorithm of Proposition~\ref{prop-quantifier-elim-detailed} to compute the according graph $\G$ and the quantifier-free formula $\psi(\ov{x})$. This takes time $h(|\varphi|){\cdot}n{\cdot}d^{h(|\varphi|)}$ for a computable function $h$. And we also know that $|\psi|\leq h(|\varphi|)$. By Proposition~\ref{prop-quantifier-elim-detailed} we know that $|\varphi(\A)|=|\psi(\G)|$. Next, we transform $\psi(\ov{x})$ into disjunctive normal form \[ \Oder_{i\in I}\gamma_i(\ov{x}), \] such that the conjunctive clauses $\gamma_i$ exclude each other (i.e., for each $\ov{v}\in\psi(\G)$ there is exactly one $i\in I$ such that $\ov{v}\in \gamma_i(\G)$). Clearly, this can be done in time $O(2^{|\psi|})$. Each $\gamma_i$ has length at most $|\psi|$, and $|I|\leq 2^{|\psi|}$. Obviously, $|\psi(\G)|=\sum_{i\in I} |\gamma_i(\G)|$. % We now use, for each $i\in I$, the algorithm from Lemma~\ref{lemma:counting-graphs} to compute the number $s_i=|\gamma_i(\G)|$ and output the value $s=\sum_{i\in I}s_i$. By Lemma~\ref{lemma:counting-graphs} we know that for each $i\in I$ computing $s_i$ can be done in time $O(2^m{\cdot}|\gamma_i|{\cdot}\tilde{n}{\cdot}\tilde{d}^{h_0(|\gamma_i|)})$, where $m$ is the number of binary atoms in $\gamma$, $\tilde{n}=|\dom(\G)|$, $\tilde{d}=\degree(\G)$, and $h_0$ is some computable function. By Proposition~\ref{prop-quantifier-elim-detailed} we know that $\tilde{n}\leq h(|\varphi|){\cdot}n{\cdot}d^{h(|\varphi|)}$ and $\tilde{d}\leq d^{h(|\varphi|)}$. Since also $|\gamma_i|\leq |\psi|\leq h(|\varphi|)$, the computation of $s_i$, for each $i\in I$, takes time $h_1(|\varphi|){\cdot}n{\cdot}d^{h_1(|\varphi|)}$, for some computable function $h_1$ (depending on $h$ and $h_0$). To conclude, since $|I|\leq 2^{|\psi|}$, the total running time for the computation of $|\varphi(\A)| = \sum_{i\in I}s_i$ is $h_2(|\varphi|){\cdot}n{\cdot}d^{h_2(|\varphi|)}$, for a suitably chosen computable function $h_2$. Hence, we meet the required bound. \end{proof} Theorem~\ref{thm:counting} is an immediate consequence of Proposition~\ref{prop:counting}, following arguments similar with the proof of Proposition~\ref{prop:connected-cqs_low-degree}: For a given $\epsilon>0$ we let $\delta\deff \frac{\epsilon}{h(|\varphi|)}$, where $h$ is the function of Proposition~\ref{prop:counting}, and define $n_\epsilon\deff m_\delta$. Then, every $\A\in\Class$ with $|\A|\geq n_\epsilon$ has $\degree(\A)\leq |\A|^{\epsilon/h(|\varphi|)}$. Thus, on input of $\A$ and $\varphi$, the algorithm from Proposition~\ref{prop:counting} has running time $O(h(|\varphi|){\cdot} |\A|^{1+\epsilon})$ if $|\A| \geq n_\epsilon$ and takes time bounded by $h(|\varphi|)\cdot n_\epsilon^{1+h(|\varphi|)}$ otherwise. This gives the bounds claimed by the proposition with a computable function $g$ as soon as we can compute $n_\e$. \subsection{Testing}\label{subsection:Testing} Here we consider the problem of testing whether a given tuple is a solution to a query. By Proposition~\ref{prop-quantifier-elim-detailed} it is enough to consider quantifier-free formulas. Those are treated using the data structure computed by Corollary~\ref{cor-test}. \begin{prop}\label{prop:testing} There is an algorithm which at input of a structure $\A$, a first-order query $\varphi(\ov{x})$, and an $\e>0$ has a preprocessing phase of time $g(|\varphi|,\e){\cdot}n^{1+\e}{\cdot}d^{g(|\varphi|,\e)}$ in which it computes a data structure such that, on input of any $\ov{a}\in\dom(\A)^k$ for $k=|\ov{x}|$, it can be tested in time $g(|\varphi|,\e)$ whether $\ov{a}\in\varphi(\A)$, where $g$ is a computable function, $n=|\dom(\A)|$, and $d=\degree(\A)$. \end{prop} \begin{proof} Fix $\e >0$. We first use the algorithm of Proposition~\ref{prop-quantifier-elim-detailed} to compute the graph $\G$, the quantifier-free formula $\psi(\ov{x})$ and the data structure for function $f$. For some computable function $h$, all of this is done within time $h(|\varphi|){\cdot}n^{1+\e}{\cdot}d^{h(|\varphi|)}$, and furthermore, $|\psi|\leq h(|\varphi|)$ and $\degree(\G)\leq d^{h(|\varphi|)}$. Note that $\size{\G}\leq h(|\varphi|){\cdot}n{\cdot}d^{h(|\varphi|)}$. By construction, we furthermore know for all $\ov{a}\in\dom(\A)^k$ that $\ov a \in \varphi(\A) \iff f(\ov a)\in \psi(\G)$. Recall from Proposition~\ref{prop-quantifier-elim-detailed} that $\psi(\ov{x})$ is a quantifier-free formula built from atoms of the form $E(y,z)$ and $C(y)$ for unary relation symbols $C$. Thus, checking whether a given tuple $\ov{v}\in\dom(\G)^k$ belongs to $\psi(\G)$ can be done easily, provided that one can check whether unary atoms $C(u)$ and binary atoms $E(u,u')$ hold in $\G$ for given nodes $u,u'$ of $\G$. Let $\tilde{n}=|\dom(\G)|$ and $\tilde{d}=\degree(\G)$. Recall that $\tilde{n}\leq h(|\varphi|){\cdot}n{\cdot}d^{h(|\varphi|)}$ and $\tilde{d}\leq d^{h(|\varphi|)}$. We apply Corollary~\ref{cor-test} to $\G$ and $\e$. This gives an extra preprocessing time of $O({\tilde{d}}^{\tilde{r}}\cdot\tilde{n}^{1+\e})$, where $\tilde{r}$ only depends on $\tau$, i.e., $\tilde{r}$ is bounded by $\tilde{h}(|\varphi|)$ for some computable function $\tilde{h}$. Inserting the known bounds on $\tilde{r}$, $\tilde{n}$, and $\tilde{d}$ shows that this extra preprocessing time is in $O(g(|\varphi|,\e) \cdot n^{1+\e} \cdot d^{g(|\varphi|,\e)})$ for some computable function $g$. Finally, the testing algorithm works as follows. Given a tuple $\ov{a}\in\dom(\A)^k$, we first construct $\ov{v}\deff f(\ov a)$ and then check whether $\ov{v}\in \psi(\G)$. Building $\ov{v}\deff f(\ov a)$ can be done in time $O(k^2)$ (see Proposition~\ref{prop-quantifier-elim-detailed}), and by Corollary~\ref{cor-test} checking whether $\ov{v}\in \psi(\G)$ depends only on $\psi$, $\e$ and $\sigma$. Hence, we meet the required bound for testing. \end{proof} Theorem~\ref{thm:testing} is an immediate consequence of Proposition~\ref{prop:testing} using the usual argument: For a given query $\phi$ and an $\epsilon>0$ we let $\delta\deff \frac{\epsilon}{2g(|\varphi|,\e/2)}$, where $g$ is the function of Proposition~\ref{prop:testing}, and define $n_\epsilon\deff m_\delta$. Then, every $\A\in\Class$ with $|\A|\geq n_\epsilon$ has $\degree(\A)\leq |\A|^{\epsilon/2g(|\varphi|,\e/2)}$. Thus, on input of $\A$, $\varphi$ and $\e/2$, the testing algorithm from Proposition~\ref{prop:testing} has preprocessing time $O(g(|\varphi|,\e/2){\cdot} |\A|^{1+\epsilon})$ if $|\A| \geq n_\epsilon$ and takes time bounded by $g(|\varphi|,\e/2)\cdot n_\epsilon^{1+\e/2+g(|\varphi|,\e/2)}$ otherwise, and it has testing time $O(g(|\varphi|,\e/2))$. This gives the bounds claimed by the theorem with a computable function as soon as we can compute $n_\e$. \subsection{Enumeration}\label{subsection:Enumeration} Here we consider the problem of enumerating the solutions to a given query. We first illustrate the proof of Theorem~\ref{thm:enum} with our running example. \begin{exa}\label{example-enum} Consider again the query $q$ of Example~\ref{example-def}. In order to enumerate $q$ with constant delay over a class of low degree we proceed as follows. During the preprocessing phase we precompute those blue nodes that contribute to the answer set, i.e.\ such that there is a red node not connected to it. This is doable in pseudo-linear time because our class has low degree and each blue node is connected to few red nodes. We call green the resulting nodes. We then order the green nodes and the red nodes in order to be able to iterate through them with constant delay. Finally, we compute the binary function $\fun{skip}(x,y)$ associating to each green node $x$ and red node $y$ such that $E(x,y)$ the smallest red node $y'$ such that $y<y'$ and $\lnot E(x,y')$, where $<$ is the order on red nodes precomputed above. From Proposition~\ref{prop:connected-cqs_low-degree} it follows that computing $\fun{skip}$ can be done in pseudo-linear time. It is crucial here that the domain of $\fun{skip}$ has pseudo-linear size and this is a consequence of the low degree. The enumeration phase now goes as follows: We iterate through all green nodes. For each of them we iterate through all red nodes. If there is no edge between them, we output the result and continue with the next red node. If there is an edge, we apply $\fun{skip}$ to this pair and the process continues with the resulting red node. Note that the new red node immediately yields an answer. Note also that all the red nodes that will not be considered are safely skipped as they are linked to the current green node. \end{exa} The proof of Theorem~\ref{thm:enum} can be sketched as follows. By Proposition~\ref{prop-quantifier-elim-detailed} it is enough to consider quantifier-free formulas looking for tuples of nodes that are disconnected and have certain colors. Hence the query $q$ described in Example~\ref{example-def} corresponds to the binary case. For queries of larger arities we proceed by induction on the arity. If $q$ is given by the formula $\varphi(\bar x y)$ we know by induction that, modulo some preprocessing pseudo-linear in the size of the input database $D$, we can enumerate with constant delay all tuples $\bar a$ satisfying $D \models \exists y \varphi(\bar x y)$. For each such tuple $\bar a$ it remains to enumerate all $b$ such that $D\models \varphi(\bar a b)$. We then proceed as in Example~\ref{example-enum}. Starting from an arbitrary node $b$ of the appropriate color, we iterate the following reasoning. If the current node $b$ is not connected to $\bar a$, then $\bar a b$ forms an answer and we proceed to the next $b$. If $b$ is connected to $\bar a$ then we need to jump in constant time to the next node of the appropriate color forming a solution. This is done by precomputing a suitable function $\fun{skip}$ that depends on the arity of the query and is slightly more complex that the one described in Example~\ref{example-enum}. The design and computation of this function is the main technical originality of the proof. The fact that the database has low degree implies that for each tuple $\bar a$ there are few nodes $b$ that are connected to $\bar a$. This makes the computation efficient. The technical details are summarized in the following proposition. \begin{prop}\label{prop:enumeration} There is an algorithm which at input of a structure $\A$, a first-order query $\varphi(\ov{x})$, and $\e>0$ enumerates $\varphi(\A)$ with delay $h(|\varphi|,\e)$ after a preprocessing of time $h(|\varphi|,\e){\cdot}n^{1+\e}{\cdot}d^{h(|\varphi|,\e)}$, where $n=|\dom(\A)|$, $d=\degree(\A)$, and $h$ is a computable function. \end{prop} \begin{proof} The proof is by induction on the number $k\deff |\ov{x}|$ of free variables of $\varphi$. % In case that $k=0$, the formula $\varphi$ is a sentence, and we are done using Theorem~\ref{thm:grohe-low-degree}. In case that $k>0$ we proceed as follows. We first use the algorithm of Proposition~\ref{prop-quantifier-elim-detailed} to compute the according colored graph $\G$, the quantifier-free formula $\psi(\ov{x})$, and the data structure representing $f$. This takes time $g(|\varphi|){\cdot}n^{1+\e}{\cdot}d^{g(|\varphi|)}$ for a computable function $g$. And we know that $|\psi|\leq g(|\varphi|)$, that $\G$ has degree $\tilde{d}\leq d^{g(|\varphi|)}$, and that $\dom(\G)$ has $\tilde{n}$ elements, where $\tilde{n}\leq g(|\varphi|){\cdot}n{\cdot}d^{g(|\varphi|)}$. From Item~\ref{item:psi-form:prop-quantifier-elim-detailed} of Proposition~\ref{prop-quantifier-elim-detailed} we know that the formula $\psi(\ov{x})$ is of the form\,$(\psi_{1} \und \psi_{2})$, where $\psi_{1}$ states that no distinct free variables of $\psi$ are connected by an $E$-edge and $\psi_{2}$ is a positive boolean combination of unary atoms. We now prove the Proposition in the case of $\G$, i.e.\ we enumerate $\psi(\G)$ and go back to $\A$ using $f$ in constant time by Item~\ref{item:f:prop-quantifier-elim-detailed} of Proposition~\ref{prop-quantifier-elim-detailed}. We assume an arbitrary linear order $\leq_\G$ among the nodes of $\G$. In case that $k=1$, $\psi(x_1)=\psi_2(x_1)$ is a positive boolean combination of unary atoms. We can use Lemma~\ref{lemma:connected-cqs} for each unary atom in order to compute $\psi(\G)$ in time $O(|\psi|{\cdot}\tilde{n}{\cdot}\tilde{d}^{g(|\psi|)})$ for a computable function $g$. From this the constant delay enumeration is immediate. Altogether the preprocessing time is in $h(\varphi){\cdot}n^{1+\e}{\cdot}d^{h(\varphi)}$, for a computable function $h$ as required. The delay is $O(1)$, and we are done for $k=1$. The case $k>1$ requires much more elaborate constructions. We let $\ov{x}=(x_1,\ldots,x_k)$ and $\ov{x}_{k-1}\deff (x_1,\ldots,x_{k-1})$. We first transform $\psi$ into a normal form $\Oder_{j\in J}\theta_j(\ov{x})$ such that the formulas $\theta_j$ exclude each other (i.e., for each $\ov{v}\in\psi(\G)$ there is exactly one $j\in J$ such that $\ov{v}\in\theta_j(\G)$), and each $\theta_j(\ov{x})$ is of the form \[ \begin{array}{c} \phi_j(\ov{x}_{k-1}) \ \und \ P_j(x_k) \ \und\ \gamma(\ov{x}), \qquad\text{where} \\[2ex] \displaystyle \gamma(\ov{x}) \ \ \deff \ \ \Und_{i=1}^{k-1} \big(\,\nicht E(x_i,x_k)\, \und\, \nicht E(x_k,x_i)\,\big), \end{array} \] $P_j(x_k)$ is a boolean combination of unary atoms regarding $x_k$, and $\phi_j(\ov{x}_{k-1})$ is a formula with only $k{-}1$ free variables. Note that the transformation into this normal form can be done easily, using the particularly simple form of the formula $\psi$. As the $\theta_j$ are mutually exclusive, we can enumerate $\psi(\G)$ by enumerating for each $j\in J$, $\theta_j(\G)$. In the following, we therefore restrict attention to $\theta_j$ for a fixed $j\in J$. For this $\theta_j$ we shortly write \[ \theta(\ov{x}) \ = \ \ \phi(\ov{x}_{k-1}) \ \und \ P(x_k) \ \und\ \gamma(\ov{x}). \] We let \ \( \theta'(\ov{x}_{k-1}) \ \deff \ \exists x_k\, \theta(\ov{x}). \) \ By induction hypothesis (since $\theta'$ only has $k{-}1$ free variables) we can enumerate $\theta'(\G)$ with delay $h(|\theta'|,\e)$ and preprocessing $h(|\theta'|,\e){\cdot}{\tilde n}^{1+\e}{\cdot}\tilde{d}^{h(|\theta'|,\e)}$ Since $P(x_k)$ is a boolean combination of unary atoms on $x_k$, we can use Lemma~\ref{lemma:connected-cqs} to compute $P(\G)$ in time $O(|P|{\cdot}\tilde{n}{\cdot}\tilde{d}^{g(|P|)})$ for a computable function $g$. Afterwards, we have available a list of all nodes $v$ of $\G$ that belong to $P(\G)$. In the following, we will write $\leq_\G^P$ to denote the linear ordering of $P(\G)$ induced by $\leq_\G$ on $P(\G)$, and we write $\first_\G^P$ for the first element in this list, and $\next^P_\G$ for the successor function, such that for any node $v\in P(\G)$, $\next_\G^P(v)$ is the next node in $P(\G)$ in this list (or the value $\void$, if $v$ is the last node in the list). We extend the signature of $\G$ by a unary relation symbol $P$ and a binary relation symbol $\next$, and let $\hat{\G}$ be the expansion of $\G$ where $P$ is interpreted by the set $P(\G)$ and $\next$ is interpreted by the successor function $\next_\G^P$ (i.e., $\next(v,v')$ is true in $\hat{\G}$ iff $v'=\next_\G^P(v)$). Note that $\hat{\G}$ has degree at most $\hat{d}=\tilde{d}{+}2$. We now start the key idea of the proof, i.e., the function that will help us skipping over irrelevant nodes. To this end consider the first-order formulas $E_1,\ldots,E_k$ defined inductively as follows, where $E'(x,y)$ is an abbreviation for $(E(x,y)\oder E(y,x))$. The reason for defining these formulas will become clear only later on, in the proof. \[ E_1(u,y) \ \deff \ \ E'(u,y), \qquad\text{and} \] \[ \begin{array}{l} E_{i+1}(u,y) \ \deff \ E_i(u,y) \ \ \oder \ \ \exists z\exists z'\exists v \, \big(E'(z,u) \und \next(z',z) \und E'(v,z') \und E_i(v,y) \big). \end{array} \] \noindent A simple induction shows that for $E_i(u,y)$ to hold, $y$ must be at distance $\leq 3(i{-}1)+1 < 3i$ from $u$. In our algorithm we will have to test, given $i\leq k$ and nodes $u,v\in\dom(\G)$, whether $(u,v)\in E_i(\hat{\G})$. Since $E_i$ is a first-order formula, Proposition~\ref{prop:testing} implies that, after a preprocessing phase using time $g'(|E_i|,\e){\cdot}\tilde{n}^{1+\e}{\cdot}\hat{d}^{g'(|E_i|,\e)}$ (for some computable function $g'$), testing membership in $E_i(\hat{\G})$, for any given $(u,v)\in\dom({\G})^2$, is possible within time $g'(|E_i|,\e)$. The last step of the precomputation phase computes the function $\fun{skip}$ that associates to each node $y\in P(\G)$ and each set $V$ of at most $k{-}1$ nodes that are related to $y$ via $E_k$, the smallest (according to the order $\leq_\G^P$ of $P(\G)$) element $z\geq_\G^P y$ in $P(\G)$ that is \emph{not} connected by an $E$-edge to any node in $V$. More precisely: For any node $y\in P(\G)$ and any set $V$ with $0\leq |V| < k$ and $(v,y)\in E_k(\hat{\G})$ for all $v\in V$, we let \begin{equation*} \fun{skip}(y,V)\ := \ \ \min\{z \in P(\G) \ : \ y \,{\leq_\G^P} z \ \text{ and } \ \forall v\in V:\ (v,z)\not\in E'(\G)\}, \end{equation*} respectively, $\fun{skip}(y,V)\deff\void$ if no such $z$ exists. Notice that the nodes of $V$ are related to $y$ via $E_k$ and hence are at distance $<3k$ from $y$. Hence for each $y$, we only need to consider at most ${\hat{d}}^{(3k^2)}$ such sets $V$. For each set $V$, $\fun{skip}(y,V)$ can be computed by running consecutively through all nodes $z\geq_\G^P y$ in the list $P(\G)$ and test whether $E'(z,v)$ holds for some $v\in V$. This can be done in constant time as we have done the preprocessing for testing for all of the $E_i$. Since $|V|\leq k$ and each $v\in V$ is of degree at most $\tilde{d}$ in $\G$, the value $\fun{skip}(y,V)$ can be found in time $O(k^2{\cdot} \tilde{d})$. Therefore, the entire $\fun{skip}$-function can be computed, and stored in a data structure by Theorem~\ref{thm-storing-complete}, in time $O(\tilde{n}^{1+\e} {\cdot} {\hat{d}}^{(3k^2)}{\cdot} g''(|\varphi|,\e))$ for some computable function $g''$. Later, given $y$ and $V$ as above, the value $\fun{skip}(y,V)$ can be looked-up within constant time. We are now done with the preprocessing phase. Altogether it took \begin{enumerate} \item the time to compute $\psi$ and $\G$, which is $g(|\varphi|){\cdot}n^{1+\e}{\cdot}d^{g(|\varphi|)}$, for a computable function $g$ \item the time to compute $\Oder_{j\in J}\theta_j$, which is $g(|\varphi|)$, for a computable function $g$ \item for each $j\in J$ and $\theta\deff \theta_j$, it took \begin{enumerate} \item the preprocessing time for $\theta'(\G)$,\\ which is by induction $h(|\theta'|,\e){\cdot}\tilde{n}^{1+\e}{\cdot}\tilde{d}^{h(|\theta'|,\e)}$, for the computable function $h$ in the Proposition's statement \item the time for computing $P(\G)$, which is\\ $g(|\varphi|){\cdot}\tilde{n}{\cdot}\tilde{d}^{g(|\varphi|)}$, for a computable function $g$ \item for all $i\leq k$, the preprocessing time for testing membership in $E_i(\hat{\G})$, which can be done in time $g'(|E_i|,\e){\cdot}\tilde{n}^{1+\e}{\cdot}\hat{d}^{g'(|E_i|,\e)}$, for a computable function $g'$ \item and the time for computing the $\fun{skip}$-function and to compute the associated data structure, which is $g''(|\varphi|,\e){\cdot}\tilde{n}^{1+\e}{\cdot} \tilde{d}^{g''(|\varphi|,\e)}$, for a computable function $g''$. \end{enumerate} \end{enumerate} \noindent It is straightforward to see that, by suitably choosing the computable function $h$, all the preprocessing steps can be done within time $h(|\varphi|,\e){\cdot}n^{1+\e}{\cdot}d^{h(|\varphi|,\e)}$. \medskip We now turn to the enumeration procedure. As expected we enumerate all tuples $\bar u \in \psi(\G)$ and return $f^{-1}(\bar u)$. In order to enumerate $\psi(\G)$ it suffices to enumerate $\theta_j(\G)$ for each $j$. Fix $j$ and let $\theta=\theta_j$ and $\theta'$ be as in the preprocessing phase. The enumeration of $\theta(\G)$ is done as follows. \begin{enumerate} \item[1.] Let $\ov{u}$ be the first output produced in the enumeration of $\theta'(\G)$.\\ If $\ov{u}=\void$ then STOP with output $\void$,\\ else let $(u_1,\ldots,u_{k-1})=\ov{u}$ and goto line 2. \item[2.] Let $y\deff \first^P_\G$ be the first element in the list $P(\G)$. \item[3.] Let $V\deff\setc{v\in\set{u_1,\ldots,u_{k-1}}}{(v,y)\in E_k(\hat{\G})}$. \item[4.] Let $z\deff\fun{skip}(y,V)$. \item[5.] If $z\neq\void$ then OUTPUT $(\ov{u},z)$ and goto line~9. \item[6.] If $z= \void$ then \begin{enumerate} \item[7.] Let $\ov{u}'$ be the next output produced in the enumeration of $\theta'(\G)$. \item[8.] If $\ov{u}'=\void$ then STOP with output $\void$, \\ else let $\ov{u}\deff \ov{u}'$ and goto line 2. \end{enumerate} \item[9.] Let $y\deff \next^P_\G(z)$. \item[10.] If $y=\void$ then goto line 7, else goto line 3. \end{enumerate} \noindent We prove that the above process enumerates $\theta(\G)$ with constant delay. To see this, notice first that the algorithm never outputs any tuple more than once. Before proving that this algorithm enumerates exactly the tuples in $\theta(\G)$, let us first show that it operates with delay at most $h(|\varphi|,\e)$. By the induction hypothesis, the execution of line~1 and each execution of line~7 takes time at most $h(|\theta'|,\e)$. Furthermore, each execution of line~3 takes time $(k{-}1){\cdot}g'(|E_k|,\e)$. Concerning the remaining lines of the algorithm, each execution can be done in time $O(1)$. Furthermore, before outputting the first tuple, the algorithm executes at most 5 lines (namely, lines 1--5; note that by our choice of the formula $\theta'$ we know that when entering line~5 before outputting the first tuple, it is guaranteed that $z\neq\void$, hence an output tuple is generated). Between outputting two consecutive tuples, the algorithm executes at most 12 lines (the worst case is an execution of lines 9, 10, 3, 4, 5, 6, 7, 8, 2, 3, 4, 5; again, by our choice of the formula $\theta'$, at the last execution of line~5 it is guaranteed that $z\neq \void$, hence an output tuple is generated). Therefore, by suitably choosing the function $h$, we obtain that the algorithm enumerates with delay at most $h(|\varphi|,\e)$. \medskip We now show that any tuple outputed is a solution. To see this consider a tuple $\bar u z$ outputed at step 5. By construction we have $z\in P(\hat{\G})$ and $\bar u \in \phi(\hat{\G})$. Hence in order to show that $\bar uz \in \theta(\hat{\G})$, it remains to verify that $z$ is not connected to any of the elements in $\bar u$. By definition of $\fun{skip}$ it is clear that $z$ is not connected to the elements of $V$. Assume now that $z=y$. Then by definition of $V$, $z$ is also not connected to all the elements not in $V$ and we are done. We can therefore assume that $z>^P_\G y$. Let $z'$ be the predecessor of $z$ in $P$ (i.e. $\next(z')=z$, possibly $z'=y$). Assume towards a contradiction that $z$ is connected to an element $x$ of $\bar u$. From the remark above, we know that $x \not\in V$. As $z'$ was skipped by $\fun{skip}$ this means that $(z',v) \in E'({\G})$ for some $v\in V$. Consider $c \in V$. By definition of $V$ we have $(c,y)\in E_k(\hat{\G})$. It turns out that $(c,y) \in E_{k-1}(\hat{\G})$. This is because when one $E_j$ does not produce anything outside of $E_{j-1}$ then all the $E_{j'}$ for $j'>j$ also do not produce anything outside of $E_{j-1}$. Hence, as $|V|<k$, we must have $(c,y) \in E_{k-1}(\hat{\G})$ and in particular $(v,y) \in E_{k-1}(\hat{\G})$. Altogether, $z,z',v$ witness the fact that $(x,y)\in E_k(\hat{\G})$ contradicting the fact that $x$ is not in $V$. \medskip It remains to show that all tuples are outputed. {This is done by induction. By induction we know that we consider all relevant $\bar u$. By definition, the function $\fun{skip}$ skips only elements $y$ such that $\bar u y$ is not a solution. Therefore we eventually output all solutions.} \end{proof} Theorem~\ref{thm:enum} follows immediately from Proposition~\ref{prop:enumeration} using the usual argument: For a given $\epsilon>0$ we let $\delta\deff \frac{\epsilon}{2h(|\varphi|,\e/2)}$, where $h$ is the function of Proposition~\ref{prop:enumeration}, and define $n_\epsilon\deff m_\delta$. Then, every $\A\in\Class$ with $|\A|\geq n_\epsilon$ has $\degree(\A)\leq |\A|^{\epsilon/2h(|\varphi|,\e)}$. Thus, on input of $\A$, $\varphi$ and $\e/2$, the enumeration algorithm from Proposition~\ref{prop:testing} has preprocessing time $O(h(|\varphi|,\e/2){\cdot} |\A|^{1+\epsilon})$ if $|\A| \geq n_\epsilon$ and takes time bounded by $h(|\varphi|,\e/2)\cdot n_\epsilon^{1+\e/2+h(|\varphi|,\e/2)}$ otherwise and delay time $h(|\varphi|,\e)$. This gives the bounds claimed by the proposition with a computable function as soon as we can compute $n_\e$. \section{Proof of quantifier elimination and normal form}\label{section-main-proofs} This section is devoted to the proof of Proposition~\ref{prop-quantifier-elim-detailed}. The proof consists of several steps, the first of which relies on a transformation of $\varphi(\ov{x})$ into an equivalent formula in Gaifman normal form, i.e., a boolean combination of basic-local sentences and formulas that are local around $\ov{x}$. A formula $\lambda(\ov{x})$ is \emph{$r$-local} around $\ov{x}$ (for some $r\geq 0$) if every quantifier is relativized to the $r$-neighborhood of $\ov{x}$. A \emph{basic-local sentence} is of the form \[ \exists y_1\cdots \exists y_\ell \!\!\Und_{1\leq i<j\leq \ell}\!\!\! \dist(y_i,y_j)> 2r \ \ \und \ \Und_{i=1}^\ell \theta(y_i), \] where $\theta(y)$ is $r$-local around $y$. By Gaifman's well-known theorem we obtain an algorithm that transforms an input formula $\varphi(\ov{x})$ into an equivalent formula in Gaifman normal form~\cite{Gaifman-82}. The rest of the proof can be sketched as follows. Basic-local sentences can be evaluated on classes of structures of low degree in pseudo-linear time by Theorem~\ref{thm:grohe-low-degree}, so it remains to treat formulas that are local around their free variables. By the Feferman-Vaught Theorem (cf., e.g.~\cite{Makowsky04}), we can further decompose local formulas into formulas that are local around \emph{one} of their free variables. The latter turns out to have a small answer set that can be precomputed in pseudo-linear time. The remaining time is used to compute the structures useful for reconstructing the initial answers from their components. We now give the details. \begin{proof}[Proof of Proposition~\ref{prop-quantifier-elim-detailed}] \ \\ \noindent \emph{Step~1: transform $\varphi(\ov{x})$ into a local formula $\varphi'(\ov{x})$.} We first transform $\varphi(\ov{x})$ into an equivalent formula $\varphi^G(\ov{x})$ in Gaifman normal form. For each basic-local sentence $\chi$ occurring in $\varphi^G(\ov{x})$, check whether $\A\models\chi$ and let $\chi'\deff \true$ if $\A\models\chi$ and $\chi'\deff \false$ if $\A\not\models\chi$. Let $\varphi'(\ov{x})$ be the formula obtained from $\varphi^G(\ov{x})$ by replacing every basic-local sentence $\chi$ occurring in $\varphi^G(\ov{x})$ with $\chi'$. By using Gaifman's theorem and Theorem~\ref{thm:grohe-low-degree}, all this can be done in time $O(h(|\varphi|){\cdot} n{\cdot} d^{{h}(|\varphi|)})$, for a computable function $h$. Clearly, for every $\ov{a}\in \dom(\A)^k$ we have $\A\models\varphi'(\ov{a})$ iff $\A\models\varphi(\ov{a})$. Note that there is a number $r\geq 0$ such that $\varphi'(\ov{x})$ is $r$-local around $\ov{x}$, and this number is provided as a part of the output of Gaifman's algorithm. \medskip \noindent \emph{Step~2: transform $\varphi'(\ov{x})$ into a disjunction $\Oder_{P\in \Part}\psi'_P(\ov{x})$.} Let $\ov{x}=(x_1,\ldots,x_k)$. A \emph{partition} of the set $\set{1,\ldots,k}$ is a list $P=(P_1,\ldots,P_\ell)$ with $1\leq \ell\leq k$ such that \begin{mi} \item $\emptyset\neq P_j \subseteq \set{1,\ldots,k}$, for every $j\in\set{1,\ldots,\ell}$, \item $P_1\cup\cdots\cup P_\ell=\set{1,\ldots,k}$, \item $P_j\cap P_{j'}=\emptyset$, for all $j,j'\in\set{1,\ldots,\ell}$ with $j\neq j'$, \item $\min P_j < \min P_{j+1}$, for all $j\in\set{1,\ldots,\ell{-}1}$. \end{mi} Let $\Part$ be the set of all partitions of $\set{1,\ldots,k}$. Clearly, $|\Part|\leq k!$. For each $P=(P_1,\ldots,P_\ell)\in\Part$ and each $j\leq \ell$ let $\ov{x}_{P_j}$ be the tuple obtained from $\ov{x}$ by deleting all those $x_i$ with $i\not\in P_j$. For every partition $P=(P_1,\ldots,P_\ell)\in\Part$ let $\rho_P(\ov{x})$ be an $\FO(\sigma)$-formula stating that each of the following is true: \begin{enumerate} \item The $r$-neighborhood around $\ov{x}$ in $\A$ is the disjoint union of the $r$-neighborhoods around $\ov{x}_{P_j}$ for $j\leq \ell$. I.e., \[ \delta_{P}(\ov{x}) \ \deff \ \Und_{1\leq j<j'\leq \ell}\ \Und_{(i,i')\in P_j\times P_{j'}} \dist(x_i,x_{i'})>2r{+}1. \] \item For each $j\leq \ell$, the $r$-neighborhood around $\ov{x}_{P_j}$ in $\A$ is connected, i.e., satisfies the formula \[ \gamma_{P_j}(\ov{x}_{P_j}) \ \deff \ \Oder_{\substack{E \subseteq P_j{\times} P_j \text{ such that the} \\ \text{graph }(P_j,E) \text{ is connected}}} \ \Und_{(i,i')\in E} \dist(x_i,x_{i'})\leq 2r{+}1. \] \end{enumerate} \noindent Note that the formula \ \( \rho_P(\ov{x}) \ \deff \ \delta_{P}(\ov{x}) \und \Und_{j=1}^\ell\gamma_{P_j}(\ov{x}_{P_j}) \) \ is $r$-local around $\ov{x}$. Furthermore, $\varphi'(\ov{x})$ obviously is equivalent to the formula \ \( \Oder_{P\in\Part} \big( \, \rho_P(\ov{x}) \und \varphi'(\ov{x}) \, \big). \) Using the Feferman-Vaught Theorem (see e.g.~\cite{Makowsky04}), we can, for each $P=(P_1,\ldots,P_\ell)\in\Part$, compute a decomposition of $\varphi'(\ov{x})$ into $r$-local formulas $\vartheta_{P,j,t}(\ov{x}_{P_j})$, for $j\in\set{1,\ldots,\ell}$ and $t\in T_P$, for a suitable finite set $T_P$, such that the formula $\big(\rho_P(\ov{x})\und\varphi'(\ov{x})\big)$ is equivalent to \begin{equation*}\label{eq:FefermanVaught-formula} \rho_P(\ov{x}) \ \und \ \Oder_{t\in T_P}\ \big( \ \vartheta_{P,1,t}(\ov{x}_{P_1}) \ \und \ \cdots \ \und \ \vartheta_{P,\ell,t}(\ov{x}_{P_\ell}) \ \big) \end{equation*} which, in turn, is equivalent to \,$\psi'_{P} \deff (\psi'_{P,1} \und \psi'_{P,2})$, where $\psi'_{P,1}\deff \delta_P(\ov{x})$ and \[ \psi'_{P,2} \ \ \deff\ \ \Big(\,\Und_{j=1}^\ell\gamma_{P_j}(\ov{x}_{P_j})\,\Big) \ \, \und \ \, \Oder_{t\in T_P} \Big(\, \Und_{j=1}^\ell \vartheta_{P,j,t}(\ov{x}_{P_j})\,\Big). \] In summary, $\varphi'(\ov{x})$ is equivalent to $ \Oder_{P\in\Part} \psi'_{P}(\ov{x}), $ and for every tuple $\ov{a}\in \dom(\A)^k$ with $\A\models\varphi'(\ov{a})$, there is exactly one partition $P\in\Part$ such that $\A\models\psi'_{P}(\ov{a})$ (since $\A \models \rho_P(\ov{a})$ is true for only one such $P\in \Part$). \medskip \noindent \emph{Step~3: defining $\G$, $f$, and $\psi$.} We define the domain $G$ of $\G$ to be the disjoint union of the sets $A$ and $V$, where $A\deff\dom(\A)$, and $V$ consists of a ``dummy element'' $\dummy$, and an element $v_{(\ov{b},\iota)}$ \begin{itemize} \item for each $\ov{b}\in A^1\cup\cdots\cup A^k$ such that $\A\models \gamma_{P}(\ov{b})$ where $P\deff\set{1,\ldots,|b|}$ and \item for each injective mapping $\iota:\set{1,\ldots,|\ov{b}|}\to\set{1,\ldots,k}$. \end{itemize} Note that the first item ensures that the $r$-neighborhood around $\ov{b}$ in $\A$ is connected. The second item ensures that we can view $\iota$ as a description telling us that the $i$-th component of $\ov{b}$ shall be viewed as an assignment for the variable $x_{\iota(i)}$ (for each $i\in\set{1,\ldots,|\ov{b}|}$). We let $f$ be the function from $A^k$ to $V^k$ defined as follows: For each $\ov{a}\in A^k$ let $P=(P_1,\ldots,P_\ell)$ be the unique element in $\Part$ such that $\A\models\rho_P(\ov{a})$. For each $j\leq \set{1,\ldots,\ell}$, we write $\ov{a}_{P_j}$ for the tuple obtained from $\ov{a}$ by deleting all those $a_i$ with $i\not\in P_j$. Furthermore, we let $\iota_{P_j}$ be the mapping from $\set{1,\ldots,|P_j|}$ to $\set{1,\ldots,k}$ such that $\iota(i)$ is the $i$-th smallest element of $P_j$, for any $i\in\set{1,\ldots,|P_j|}$. Then, \[ f(\ov{a}) \ \deff \ \big(\, v_{(\ov{a}_{P_1},\iota_{P_1})},\ldots,v_{(\ov{a}_{P_\ell},\iota_{P_\ell})}, \dummy, \ldots, \dummy \, \big), \] where the number of $\dummy$-components is $(k{-}\ell)$. It is straightforward to see that $f$ is injective. We let $\tau_1$ be the signature consisting of a unary relation symbol $C_\bot$, and a unary relation symbol $C_\iota$ for each injective mapping $\iota:\set{1,\ldots,s}\to\set{1,\ldots,k}$ for $s\in\set{1,\ldots,k}$. In $\G$, the symbol $C_\bot$ is interpreted by the singleton set $\set{\dummy}$, and each $C_\iota$ is interpreted by the set of all nodes $v_{(\ov{b},\hat{\iota})}\in V$ with $\hat{\iota}=\iota$. We let $E$ be a binary relation symbol which is interpreted in $\G$ by the set of all tuples $(v_{(\ov{b},\iota)},v_{(\ov{c},\hat{\iota})})\in V^2$ such that there are elements $b'\in A$ in $\ov{b}$ and $c'\in A$ in $\ov{c}$ such that $\dist^\A(b',c')\leq 2r{+}1$. For each $P=(P_1,\ldots,P_\ell)\in\Part$, each $j\in\set{1,\ldots,\ell}$, and each $t\in T_P$ we let $C_{P,j,t}$ be a unary relation symbol which, in $\G$, is interpreted by the set of all nodes $v_{(\ov{b},\iota)}\in V$ such that $\iota=\iota_{P_j}$ and $\A\models\vartheta_{P,j,t}(\ov{b})$. We let $\tau_2$ be the signature consisting of all the unary relation symbols $C_{P,j,t}$. We let $\ov{y}=(y_1,\ldots,y_k)$ be a tuple of $k$ distinct variables, and we define $\psi_1(\ov{y})$ to be the $\FO(E)$-formula \[ \psi_{1}(\ov{y}) \ \ \deff \ \ \Und_{\substack{ 1\leq j,j'\leq k \\ \text{with }j\neq j'}}\!\!\!\!\!\nicht E(y_j,y_{j'}). \] For each $P=(P_1,\ldots,P_\ell)$ we let $\psi_P(\ov{y})$ be the $\FO(\tau_1\cup\tau_2)$-formula defined as follows: \begin{eqnarray*} \psi_{P}(\ov{y}) & \deff & \Big(\Und_{j=1}^\ell C_{\iota_{P_j}}(y_j) \Big) \ \, \und \ \, \Big(\Und_{j=\ell+1}^k C_\bot(y_j) \Big) \ \, \und \, \ \Oder_{t\in T_P}\Big( \Und_{j=1}^\ell C_{P,j,t}(y_j)\Big). \end{eqnarray*} It is straightforward to verify that the following is true: \begin{me} \item For every $\ov{a}\in A^k$ with $\A\models \psi'_P(\ov{a})$, we have \ $\G\models (\psi_1\und\psi_P)(f(\ov{a}))$. \item For every $\ov{v}\in G^k$ with $\G\models (\psi_1\und\psi_P)(\ov{v})$, there is a (unique) tuple $\ov{a}\in A^k$ with $\ov{v}=f(\ov{a})$, and for this tuple we have $\A\models\psi'_P(\ov{a})$. \end{me} Finally, we let \[ \psi(\ov{y}) \ \deff \ \big(\psi_1(\ov{y}) \und \psi_2(\ov{y})\big) \quad \text{with} \quad \psi_2(\ov{y}) \ \deff \ \Oder_{P\in\Part} \psi_P(\ov{y}). \] It is straightforward to see that $f$ is a bijection between $\varphi(\A)$ and $\psi(\G)$. In summary, we now know that items~\ref{item:psi-form:prop-quantifier-elim-detailed} and~\ref{item:psi-comput:prop-quantifier-elim-detailed}, as well as the non computational part of item~\ref{item:f:prop-quantifier-elim-detailed} of Proposition~\ref{prop-quantifier-elim-detailed} are true. Later on in \emph{Step~5} we will provide details on how to build a data structure that, upon input of any tuple $\ov{a}\in A^k$, returns the tuple $f(\ov{a})$ within the claimed time bounds. In order to be able to also compute $f^{-1}(\ov{v})$ upon input of any tuple $\ov{v}\in \psi(\G)$, we use additional binary relation symbols $F_1,\ldots,F_k$ which are interpreted in $\G$ as follows: Start by initializing all of them to the empty set. Then, for each $v=v_{(\ov{b},\iota)}\in V$ and each $j\in\set{1,\ldots,|\ov{b}|}$, add to $F_{\iota(j)}^\G$ the tuple $(v,a)$, where $a$ is $j$-th component of $\ov{b}$. This completes the definition of $\G$ and $\tau$, letting $\tau\deff\tau_1\cup\tau_2\cup\set{E,F_1,\ldots,F_k}$. Using the relations $F_1,\ldots,F_k$ of $\G$, in time $O(k)$ we can, upon input of $v=v_{(\ov{b},\iota)}\in V$ compute the tuple $\ov{b}$ and the mapping $\iota$ (for this, just check for all $i\in\set{1,\ldots,k}$ whether node $v$ has an outgoing $F_i$-edge). Using this, it is straightforward to see that upon input of $\ov{v}\in \psi(\G)$, the tuple $f^{-1}(\ov{v})\in A^k$ can be computed in time $O(k^2)$, \medskip \noindent \emph{Step~4: Computing \G within the time bounds of Item~\ref{item:G:prop-quantifier-elim-detailed}.} First of all, note that for each $v_{(\ov{b},\iota)}\in V$, the tuple $\ov{b}$ is of the form $(b_1,\ldots,b_s)\in A^s$ for some $s\leq k$, such that all components of the tuple belong to the $\hat{r}$-neighborhood $\N^{\A}_{\hat{r}}(b_1)$ of $b_1$ in $\A$, for $\hat{r}\deff k(2r{+}1)$. By Lemma~\ref{lemma-compute-neigh} we can compute in total time $O(|\varphi|\cdot n \cdot d^{h'(|\varphi|)})$ all the neigborhoods $\N^{\A}_{\hat{r}}(a)$ (for all $a\in\dom(\A)$), where $h'$ is some computable function (recall that $\hat r$ depends only on $\varphi$). Within the same time bound, we can also compute all the neighborhoods $\N^{\A}_{\tilde{r}}(a)$, $\N^{\A}_{r'}(a)$, and $\N^{\A}_{r'-r}(a)$, for $\tilde{r}\deff \hat{r}{+}r$ and $r'\deff r+(2k{+}1)(2r{+}1)$ (later on it will be convenient to have efficient access to all these neighborhoods). Thus, the set $V$, along with the relations $C_\bot$, $C_\iota$ and $F_1,\allowbreak\ldots,F_k$ of $\G$, can be computed as follows: Start by letting $V\deff \set{\dummy}$ and initializing all relations to the empty set. Let $C_{\bot}^{\G}\deff\set{\dummy}$. Then, for each $a\in A$, consider the $\hat{r}$-neighborhood $\N^{\A}_{\hat{r}}(a)$ of $a$ in $\A$, and compute (by a brute-force algorithm), for each $s\in\set{1,\ldots,k}$, the set of all $s$-tuples $\ov{b}$ of elements from this neighborhood, which satisfy the following: The first component of $\ov{b}$ is $a$, and $\N^{\A}_{\hat{r}}(a)\models\gamma_{P_j}(\ov{b})$ for $P_j=\set{1,\ldots,s}$. For each such tuple $\ov{b}$ do the following: For each injective mapping $\iota:\set{1,\ldots,s}\to\set{1,\ldots,k}$ add to $V$ a new element $v_{(\ov{b},\iota)}$, add this element to the relation $C_{\iota}^{\G}$, and for each $j\in\set{1,\ldots,s}$, add to $F_{\iota(j)}^{\G}$ the tuple $(v_{(\ov{b},\iota)},a)$, where $a$ is the $j$-th component of $\ov{b}$. This way, the domain $G=A\cup V$ of $\G$, along with the relations $C_\iota$ and $F_1,\ldots,F_k$ of $\G$, can be computed in time $O(h(|\varphi|){\cdot}n{\cdot}d^{h(|\varphi|)})$, for a computable function $h$. For computing the unary relations $C_{P,j,t}$ of $\G$, start by initializing all of them to the empty set. For each $v_{(\ov{b},\iota)}\in V$ do the following: Compute (by using the relations $F_1,\ldots,F_k$) the tuple $\ov{b}$ and the mapping $\iota$. Let $a$ be the first component of $\ov{b}$. Consider the $\tilde{r}$-neighborhood $\N^{\A}_{\tilde{r}}(a)$ of $a$ in $\A$, for $\tilde{r}\deff \hat{r}{+}r$. For each $P=(P_1,\ldots,P_\ell)\in\Part$, each $j\in\set{1,\ldots,\ell}$ such that $\iota_{P_j}=\iota$, and each $t\in T_P$, check whether $\N^{\A}_{\tilde{r}}(a)\models \theta_{P,t,j}(\ov{b})$. If so, add the element $v_{(\ov{b},\iota)}$ to the relation $C_{P,j,t}$ of $\G$. (This is correct, since the formula $\theta_{P,j,t}$ is $r$-local around its free variables, and the radius of the neighborhood is large enough.) This way, $\G$'s relations $C_{P,j,t}$ can be computed in time $O(h(|\varphi|){\cdot}n{\cdot}d^{h(|\varphi|)})$, for a computable function $h$. To compute the $E$-relation of $\G$, note that for all tuples $(v_{(\ov{b},\iota)},v_{(\ov{c},\hat{\iota})})\in E^{\G}$, we have $\dist^{\A}(a,c_j)\leq (2k{+}1)(2r{+}1)$, for all components $c_j$ of $\ov{c}$, where $a$ is the first component of $\ov{b}$. Thus, the $E$-relation of $\G$ can be computed as follows: Start by initializing this relation to the empty set. For each $v_{(\ov{b},\iota)}\in V$ do the following: Compute (by using the relations $F_1,\ldots,F_k$) the tuple $\ov{b}$. Let $a$ be the first component of $\ov{b}$. Consider the $r'$-neighborhood $\N^{\A}_{r'}(a)$ of $a$ in $\A$, for $r'\deff r+(2k{+}1)(2r{+}1)$. Use a brute-force algorithm to compute all tuples $\ov{c}$ of elements in $\N^{\A}_{r'-r}(a)$, such that $|\ov{c}|\leq k$ and $\N^{\A}_{r'}(a)\models\gamma_{P_j}(\ov{c})$ for $P_j=\set{1,\ldots,|\ov{c}|}$. Check if there are components $b'$ of $\ov{b}$ and $c'$ of $\ov{c}$ such that $\dist^{\N^{\A}_{r'}(a)}(b',c')\leq 2r{+}1$. If so, add to $E^{\G}$ the tuple $(v_{(\ov{b},\iota)},v_{(\ov{c},\hat{\iota})})$ for each injective mapping $\hat{\iota}:\set{1,\ldots,|\ov{c}|}\to\set{1,\ldots,k}$. This way, the $E$-relation of $\G$ can be computed in time $O(h(|\varphi|){\cdot}n{\cdot}d^{h(|\varphi|)})$, for a computable function $h$. In summary, we obtain that $\G$ is computable from $\A$ and $\varphi$ within the desired time bound. To finish the proof of item~\ref{item:G:prop-quantifier-elim-detailed}, we need to give an upper bound on the degree of $\G$. As noted above, $(v_{(\ov{b},\iota)},v_{(\ov{c},\hat{\iota})})\in E^{\G}$ implies that $\dist^{\A}(a,c_j)\leq r'$ for $r'\deff (2k{+}1)(2r{+}1)$, for all components $c_j$ of $\ov{c}$, where $a$ is the first component of $\ov{b}$. Thus, for each fixed $v_{(\ov{b},\iota)}\in V$, the number of elements $v_{(\ov{c},\hat{\iota})}$ such that $(v_{(\ov{b},\iota)},v_{(\ov{c},\hat{\iota})})\in E^\G$ is at most \[ k! \cdot \sum_{s=1}^k|\N^{\A}_{r'}(a)|^s \quad \leq \quad k!\cdot |\N^{\A}_{r'}(a)|^{k+1} \quad \leq \quad k!\cdot d^{(r'+1)(k+1)}. \] Thus, since $E^\G$ is symmetric, its degree is $\leq 2k! d^{(r'+1)(k+1)}$. Similarly, for each tuple $(v_{(\ov{b},\iota)},a)\in F_{i}^{\G}$ (with $i\in\set{1,\ldots,k}$) we know that $a$ is the $\iota^{-1}(i)$-th component of $\ov{b}$ and each component of $\ov{b}$ belongs to the $\hat{r}$-neighborhood of $a$ in $\A$, for $\hat{r}=k(2r{+}1)$. Thus, for each fixed $a\in A$, the number of elements $v_{(\ov{b},\iota)}\in V$ such that $(v_{(\ov{b},\iota)},a)\in F_i^{\G}$ is at most \ $ k!\cdot\sum_{s=1}^k|\N^{\A}_{\hat{r}}(a)|^s \allowbreak \ \leq \ k!\cdot d^{(\hat{r}+1)(k+1)}. $ In summary, we thus obtain that $\G$ is of degree at most $d^{h(|\varphi|)}$ for a computable function $h$. \medskip \noindent \emph{Step~5: Computing $f$ within the time bounds of Item~\ref{item:f:prop-quantifier-elim-detailed}.} Recall that for $\ov{a}\in A^k$ we have \[ f(\ov{a}) \ \deff \ \big(\, v_{(\ov{a}_{P_1},\iota_{P_1})},\ldots,v_{(\ov{a}_{P_\ell},\iota_{P_\ell})}, \dummy, \ldots, \dummy \, \big), \] for the unique partition $P=(P_1,\ldots,P_\ell)\in\Part$ such that $\A\models\rho_P(\ov{a})$. The number of $\dummy$-components in $f(\ov{a})$ is $(k{-}\ell)$. We first show how to compute $f(\bar a)$ from $\bar a$ in constant time. This is where we use $\e$. To compute the partition $P$ for a given tuple $\ov{a}=(a_1,\ldots,a_k)$, we can proceed as follows: Construct an undirected graph $H$ with vertex set $\set{1,\ldots,k}$, where there is an edge between $i\neq j$ iff $\dist^{\A}(a_i,a_j)\leq 2r{+}1$. This can be done as follows. Let $R$ be the binary relation over $\dom(\A)$ containing all pairs $(a,b)$ such that $\dist^{\A}(a_i,a_j)\leq 2r{+}1$. As $\A$ as degree at most $d$, the size of $R$ is bounded by $n {\cdot} d^{2r+2}$ and $R$ can be computed by a brute-force algorithm in time $O(n \cdot d^{2r+2})$. Hence by the Storing Theorem (Theorem~\ref{thm-storing-complete}), we can compute a data structure in time $O(n^{1+\e} \cdot d^{2r+2})$ such that afterwards we can test in time depending only on $\e$ whether a given pair is in $R$ or not. Once $H$ is computed, we can compute its connected components in time depending only on $k$. Let $\ell$ be the number of connected components of $H$. For each $j\in\set{1,\ldots,\ell}$ let $P_j$ be vertex set of the $j$-th connected component, such that $\min P_j < \min P_{j+1}$ for all $j\in\set{1,\ldots,\ell{-}1}$. After having constructed the partition $P=(P_1,\ldots,P_\ell)$, further $O(k^2)$ steps suffice to construct the tuples $\ov{a}_{P_1}$, \ldots, $\ov{a}_{P_\ell}$, the mappings $\iota_{P_1}$, \ldots, $\iota_{P_\ell}$, and the according tuple $f(\ov{a})$. % Let $\zeta_P$ be the function associating to each pair $(\ov{a}_{P_j},\iota_{P_j})$ the element $v_{(\bar a_{P_j},\iota_{P_j})}$. The domain of $\zeta_P$ is at most $n{\cdot} d^{k(2r+1)+1}$ and $\zeta_P$ can be computed in $O(n\cdot d^{k(2r+1)+1})$ by a brute-force algorithm. Hence, using Theorem~\ref{thm-storing-complete} we can compute in time $O(n^{1+\e}\cdot d^{k(2r+1)+1})$ a data structure such that afterwards we can obtain the result of the function $\zeta_P$ in time depending only on $\e$. Altogether, after the preprocessing, we can compute $f(\ov{a})$ in time $O(k^2)$. Recall that using the relation $F$, it is straightforward to compute $f^{-1}(\ov{v})$ upon input of $\ov{v} \in \dom(\G)$ in time $O(k^2)$. This concludes the proof of proof of Proposition~\ref{prop-quantifier-elim-detailed}. \end{proof} \section{Conclusion}\label{section-conclusion} For classes of databases of low degree, we presented an algorithm which enumerates the answers to first-order queries with constant delay after pseudo-linear preprocessing. An inspection of the proof shows that the constants involved are non-elementary in the query size {(this is already the case for Theorem~\ref{thm:grohe-low-degree} and we build upon this result, this is also a consequence of Gaifman Normal Form which derives a new formula of non-elementary size~\cite{DBLP:conf/icalp/DawarGKS07})}. In the bounded degree case the constants are triply exponential in the query size~\cite{KS11}. In the (unranked) tree case the constants are provably non-elementary~\cite{FrickG04} (modulo some complexity assumption). We do not know what is the situation for classes of low degree. If the database is updated, for instance if a tuple is deleted or inserted, it would be desirable to be able to update efficiently the data structure that is computed for deriving in constant time counting, testing, and enumeration. With the data structure given in this paper it is not clear how to do this without recomputing everything from scratch. However it has been shown recently that there is another data structure, providing the same constant time properties that furthermore can be updated in time $O(n^\e)$ upon insertion or deletion of a tuple~\cite{DBLP:journals/corr/abs-2010-02982}. It would also be interesting to know whether we can enumerate the answers to a query using the \emph{lexicographical} order (as it is the case over structures of bounded expansion~\cite{KazanaS13}). \bibliographystyle{alphaurl}
{'timestamp': '2022-05-10T02:32:21', 'yymm': '2010', 'arxiv_id': '2010.08382', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08382'}
arxiv
\section{Introduction}\label{intro} Neural architecture search (NAS), as an emerging field of machine learning, has become one of the main methods to realize automatic machine learning, and has increasingly received widespread attention from the academic.\cite{elsken2018neural} The main technology of NAS is to construct various search spaces, design algorithms to search iteratively, train continuously and evaluate continuously to discover the optimal network architecture. After Google\cite{zoph2016neural} and MIT\cite{he2016deep} released NAS based on reinforcement learning in 2016, through improvements in search space\cite{zoph2018learning}, search strategies\cite{pham2018efficient}, and evaluation methods\cite{tan2019efficientnet} in recent years, NAS algorithms have gradually reduced the demand for GPUs and become more "civilized", enabling more people to have opportunities to provide new idea which promote the development of automated machine learning. Especially, DARTS\cite{hanxiao2019darts}, as one of the algorithms that rapidly improve the computational efficiency of NAS method, uses a neural network structure composed of stacked cells as the search space, and relax the Categorical selection of a specific operation to a softmax of all possible operations to make the search space continuous. In addition to the huge computational burden DARTS has to bear, the generalization ability of the searched network architecture also has space for improvement. The prior work named Partially-Connected DARTS (PC-DARTS)\cite{xu2019pc} proposed to sample a small part of super-network to reduce redundancy when exploring the network space. PC-DARTS improved the performance of the searched network architecture with only one group of channels, which indicated group of channels has good value for architecture search. In addition, Squeeze-and-Excitation Network (SENet)\cite{hu2018squeeze} that appeared in 2017 obtained the weight of different channels by learning the relationship between each channel, then multiplied the weight by the original feature map to acquire the final feature. We referred to the method of observing the connection between channels of attention mechanism and proposed our own parameters to balance the relationship between channels. In this paper, we present a novel approach named Group-DARTS with attention (G-DARTS-A) to reduce the overfitting and improve the stability in searching process. There are two primary contributions of our method, namely, Channel Group Parallel Sampling for Searching and the attention for balance between each group. As the key technique in this work, Channel Group Parallel Sampling has not been researched in NAS for searching more stable architecture with better performance. This point proposes a new idea to design super network for NAS. This kind of super network we built, combining Channel Group Parallel Sampling and weights for attention, can ensure the stability of the search process and prevent the searched architecture from overfitting. We increase the accuracy on cifar10 and cifar100 of PC-DARTS and DARTS. Moreover, these two components are easily transplanted to other search algorithms to improve search accuracy and generalization, e.g., these can boost the accuracy and speed of all algorithms based on DARTS search space. We only use the attention module of this method on DARTS and achieve an error rate of 2.82\%/16.36\% on CIFAR10/100 with 0.2GPU-days for search process on CIFAR10. Apply our G-DARTS-A to DARTS/PC-DARTS, an error rate of 2.57\%/2.64\% on CIFAR10 with 0.5/0.4 GPU-days is achieved. \section{Related work}\label{rl} Due to the increase in the amount of data and the improvement of computer computing power, people began to pursue to build more complex artificial neural networks. The existing excellent neural network structures built manually are time-consuming and error prone\cite{elsken2018neural} \cite{zoph2016neural} \cite{cai2019proxylessnas}. In order to realize automatic machine learning, neural architecture search as a process of automated architecture functional engineering enables the computer to automatically obtain the optimal network structure framework in the process of iterative search, continuous training and continuous evaluation. In 2016, Google published a neural architecture search based on reinforcement learning, which became the first well-known NAS work\cite{zoph2016neural}. It used recurrent neural network (RNN) trained through reinforcement learning to generate description of neural network model. After that, NASnet\cite{zoph2018learning} simplified searching the optimal convolutional architecture into finding the best units of CNN. With further improvement, AmoebaNet\cite{real2019regularized} generated an architecture based on genetic algorithms, surpassing manual design for the first time. The above algorithms rely on powerful hardware and bring huge computational overhead. In order to solve the computational problem, Google proposed an efficient neural architecture search (ENAS, Efficient NAS)\cite{pham2018efficient}, which used a controller to search for the best subgraph in a large computational graph to display the neural network architecture, and the subgraphs share parameters with each other. Then, ProxylessNAS\cite{cai2019proxylessnas} directly searched on the target data set instead of convention migration search strategies for reducing hardware requirements. In 2017, Senet\cite{hu2018squeeze} won the championship of the ImageNet 2017 competition classification task. SENet\cite{hu2018squeeze} uses the attention mechanism to focus on the relationship between channels, hoping the model can automatically learn the significance of different channel features. It learns the relationship between each channel to obtain the weight of different channels and multiplies the weight by the original feature map to obtain the final feature. This attention mechanism allows the model to pay more attention to the channel features with the most information, while suppressing those unimportant channel features. This work based on differentiable architecture search method, such as DARTS\cite{hanxiao2019darts} and PC-DARTS\cite{xu2019pc} and refers to SENet's\cite{hu2018squeeze} method of observing channel relationships. DARTS used the neural network structure stacked by computing units as the search space and reduced the search neural architecture to search for suitable units, which promoted a rapid increase in the computational efficiency of NAS method. It used bilevel optimization method for optimizing network weight and architecture parameter simultaneously. PC-DARTS\cite{xu2019pc} proposed channel sampling technology and edge normalization method, which shorten the search process of NAS and reduced the computational burden. This method only operated on a small part of the channels, then the remaining channels are merged with the operated channels after skipping the operating part. Structural parameters are optimized by randomly sampled channels in the iterative process. \section{Revisiting Gradient based Architecture Search}\label{nas} \subsection{Preliminaries of DARTS: continuous relaxation search space}\label{darts} DARTS is mentioned for the first time as the baseline of this work. Its search network is composed of a neural network formed by stacking L cells. Each cell can be regarded as a directed acyclic graph (DAG) connected by N nodes, $\{x_0,x_1,x_2,...,x_{N-1}\}$. Each pair of nodes $(i,j)$ is connected by edge $\mathrm{E}_{(i, j)}$ which is associated with different candidate structural operations, such as convolutional layer and pooling layer. We denote operations by $\mathcal{O}$, and the fixed function as elements in each operation is denoted by $o(\cdot)$. The core goal of DARTS is to make the search space continuous by using the architecture hyper-parameter $\alpha_o^{(i,j)}$ to quantify operation $o(x_i)$, so that the connection between edges $i$ and$j$ can be formulated as: $f_{i, j}(x_i) = \sum_{o\in\mathcal{O}_{i, j}}{\frac{\mathrm{exp}(\alpha_o^{(i,j)})}{\sum_{o'\in\mathcal{O}}\mathrm{exp}(\alpha_{o'}^{(i,j)})}o(x_i)}$.In addition, each cell consists of two input nodes, four intermediate nodes and one output node. The two input nodes are subject to the output of the first two cells respectively, and the output of this unit cell obtained by cascading all intermediate nodes. \subsection{Preliminaries of PC-DARTS: partial channel connections} In order to reduce the burden of memory and computer, PC-DARTS proposed a partial sampling method. Different from selecting all channels for candidate operation in each feature map, only 1/K channels are randomly sampled, followed by operation selection, while other shielded channels have no operation selection is performed. Because only part of the channel is operated, the burden of computer storage will be reduced by nearly K times, which makes it possible to use a batch size of K times larger than before in the search process. Not only does it speed up the network search, it also stabilizes the search process, making it possible to directly search for large-scale dataset. \section{Method}\label{mt} \subsection{Channel Group Parallel Sampling for Searching} The drawback of DARTS is simply training architecture parameters $\alpha$ as normal network weights, which increases the risk for overfitting in the search process. In addition, PC-DARTS with partial channel group connection can achieve good accuracy, which shows that the channel group has great value for searching architecture. In this work, we recommend using multiple channel group to design a super network, which named Channel Group Parallel Sampling method depicted in figure 1. In each cell, we set M edges on each pair of nodes, and each edge on the same connection shares $\beta$ weight. the method divides the feature maps into M groups that are seeded to the corresponding edges. Finally, the number of channels on each edge and M can be adjusted flexibly to adapt to various application scenarios.\\ \begin{figure}[t] \centering \includegraphics[width=0.9\linewidth]{1.pdf} \caption{Illustration of Channel Group Parallel Sampling (best viewed in color), In the sprite of PC-DARTS, we show the propagation process of information between nodes. $\mathcal P_{0i}$ denote operations (denoted by O) on each edge (between node i and j).} \label{motivation} \end{figure} This brings twofold benefits: First, multiple groups can bring more and different information to search process, so that the super-network has different optimization directions in weight updating. Additionally, the searched architecture can adapt to different groups of channels, thus network structure obtained in this way has stronger stability and generalization ability, which can effectively avoid overfitting of structural parameters. Therefore, the architecture searched by our G-DARTS-A also perform well on other data sets that are not used in the search process. \subsection{Attention for Balance between Each Channel Group} When it comes to Channel Group Parallel Sampling, it has advantages and disadvantages. The positive side was mentioned in the previous section. On the downside, first, multi-channel group greatly reduce the number of parameters in super network, which causes the decline of the super network's fitting ability. Moreover, different group of channels have unequal importance for searching, which may lead to vicious competition between each group of channels.\\ \begin{figure}[t] \centering \includegraphics[width=0.9\linewidth]{2} \caption{Representation of our weights.$\mathcal \gamma_0 $ to $\mathcal \gamma_N $represent the weights for Attention multiplied on the groups of channels.} \label{motivation} \end{figure} This disadvantage implies that the network has not learned deeply about the relationship between channel group. Simultaneously, we are inspired by the previous work of SEnet \cite{hu2018squeeze}, to alleviate these problem, we set weights that can be gradient as the channel group weights on each edge$(i,j)$, denoted by $\gamma$ showed as figure 2. Specifically, the weights of each edge in different cell is independent, which gives a large space for optimizing weights in search process. The bigger space for searching imply stronger ability to fit. Moreover, the weights can give more important groups of channels bigger weights than other groups of channels, which can keep a balance between each group of channels for searching a stable architecture with better performance. The two main ideas we propose can be combined into Channel Group Parallel Sampling with Attention, which be expressed by Equation 1. \begin{align*} & {{f}_{i,j}}\left( {{x}_{ij}} \right)={{\gamma }_{1}}\sum\limits_{o\in O}{\frac{\exp \left\{ \alpha _{i,j}^{o} \right\}}{\sum\limits_{{{o}^{\prime }}\in O}{\exp }\left\{ \alpha _{i,j}^{{{o}^{\prime }}} \right\}}}o\left( {{x}_{i1}}\ \right)+{{\gamma }_{2}}\sum\limits_{o\in O}{\frac{\exp \left\{ \alpha _{i,j}^{o} \right\}}{\sum\limits_{{{o}^{\prime }}\in O}{\exp }\left\{ \alpha _{i,j}^{{{o}^{\prime }}} \right\}}}o\left( {{x}_{i2}}\ \right) \\ &+{{\gamma }_{3}}\sum\limits_{o\in O}{\frac{\exp \left\{ \alpha _{i,j}^{o} \right\}}{\sum\limits_{{{o}^{\prime }}\in O}{\exp }\left\{ \alpha _{i,j}^{{{o}^{\prime }}} \right\}}}o\left( {{x}_{i3}}\ \right)+{{\gamma }_{4}}\sum\limits_{o\in O}{\frac{\exp \left\{ \alpha _{i,j}^{o} \right\}}{\sum\limits_{{{o}^{\prime }}\in O}{\exp }\left\{ \alpha _{i,j}^{{{o}^{\prime }}} \right\}}}o\left( {{x}_{i4}}\ \right) \\ & +\ldots +{{\gamma }_{M}}\sum\limits_{o\in O}{\frac{\exp \left\{ \alpha _{i,j}^{o} \right\}}{\sum\limits_{{{o}^{\prime }}\in O}{\exp }\left\{ \alpha _{i,j}^{{{o}^{\prime }}} \right\}}}o\left( {{x}_{iM}}\ \right) \tag{Equation 1} \end{align*} For Equation 1, We show the operation of the channel group between nodes i and j.$\mathcal x_{i1-M} $represents different channel groups of the operating channel,$ \sum\limits_{o\in O}{\frac{\exp \left\{ \alpha _{i,j}^{o} \right\}}{\sum\limits_{{{o}^{\prime }}\in O}{\exp }\left\{ \alpha _{i,j}^{{{o}^{\prime }}} \right\}}}$ represents the operation to be performed by the channel group, which gives different weights $\mathcal \alpha_{i,j}^{o^\prime}$ to the operation (convolutional layer, pooling layer, etc.). The final channel group operation result between the two nodes (i to j) is expressed as $\mathcal f_{i,j}\left(x_{ij}\right)$. In addition, the Attention can be divided into different groups for weighting multiplication, shown on Equation 1 which contains the Attention and Channel Group Parallel Sampling with same grouping. A more detailed presentation is shown in Figure 3. \begin{figure*}[t] \centering \includegraphics[width=0.9\linewidth]{3} \caption{Illustration of Channel Group Parallel Sampling with Attention (best viewed in color) After M groups of parallel sampling, the feature map can be divided into N groups and multiplied by the attention weight $\mathcal \gamma_N $.} \label{motivation} \end{figure*} \subsection{Grouped convolution improves the speed} Due to the characteristics of GPU and Pytorch\cite{paszkeautomatic} calculations, multi-channel group parallelism will cause the search speed to slow down and grouped sampling of features mainly changes the characteristics of convolution operations. Inspired by this, we use the grouped convolution inside Pytorch for approximate replacement. Grouped convolution groups the input feature maps, then each group is convolved separately. Assuming that $c$ represents the number of channels of the input feature map, and it is set to be divided into g groups, the number of input feature maps in each group becomes $c/g$, and the size of the convolution kernel is correspondingly reduced to the original $c/g$ times. In this way, memory can be reduced while achieving a speed advantage, so that the algorithm achieves a similar effect with faster speed, thus we replaced all convolution operations in DARTS with grouped convolution. This improvement achieves the improvement of experimental accuracy without introducing any additional overhead. \section{Experiments}\label{ex} \subsection{Dataset} We conduct experiments on CIFAR10 and CIFAR100 datasets. Architecture search is performed on CIFAR10 and the searched architectures are evaluated on CIFAR10 and CIFAR100. CIFAR-10 contains $60$K RGB images which are equally divided into 10 categories. Each image has a spatial resolution of $32*32$. Among them, there are $50$K and $10$K images for training and testing. In other words, CIFAR10 has $5$ training batches and $1$ test batch, and each batch has $10$K images. In each training batch, the number of images of different types may not be the same but still accurately contains 5000 images of each class. The only difference between CIFAR100 and CIFAR10 is that CIFAR100 divides $60$K images into $100$ categories on average. \subsection{Architecture Search on CIFAR10}\label{archi-se} \subsubsection{Implementation Details} We implement the core methods of G-DARTS-A on DARTS and PC-DARTS. In search process, training set are equally distributed into two parts for respectively tuning network weights and architecture parameters. DARTS-with-Attention for balance between each group of channels, we followed its defined search space which contains $8$ operations, i.e., $3*3$ average-pooling, $3*3$ max-pooling, skip-connect, $3*3$ and $5*5$ separable convolution, $3*3$ and $5*5$ dilated separable convolution and zero. We divide the features on each edge into four groups of $1/8$, $1/8$, $1/4$, $1/2$ according to the channel, and multiply them by four gradient-optimized parameters with different initial values: $2.4$, $2.4$, $3.2$ and $3.0$ correspond to four groups of channels respectively. After that,on G-DARTS-A we changed all the convolution in the operation to grouped convolution with the number of groups being $4$.\\ We use DARTS (first order) to train a small network consisting of $8$ cells, which lasts $50$ epochs, the batch size is $32$, and the initial number of channels is $16$. We use momentum SGD\cite{polyak1992acceleration} to optimize the weight $w$, initial learning rate $\eta_w= 0.025$ (anneal it to zero according to the cosine schedule without restarting), momentum $0.9$ and weight decay $3\times 10^{-4}$, while we use Adam\cite{kingma2014adam} as the optimizer for $\alpha$ with initial learning rate$\eta_\alpha= 3\times 10^{-4}$, momentum $\beta = (0.5, 0.999) $and weight decay$ 0.001$, and cutout\cite{devries2017improved} status is True. \subsubsection{Search Results} The architecture found from G-PC-DARTS-A on CIFAR10 by this method tends to retain deeper connections than the architecture found in previous work, as shown in Figure4(a) and Figure4(b). The cells found from DARTS-with-Attention are shown in Figure4(c) and Figure4(d). Besides, Figure4(e) and Figure4(f) represent the deep network architecture obtained from G-DARTS-A that uses grouped convolution instead of channel groups for sampling and accompanied by attention. The more layers of the network, the higher the possibility of its classification accuracy. Besides, we use 1080TiGPU to search architecture, G-PC-DARTS-A spent 0.3GPU-days while DARTS-with-Attention used 0.4GPU-days in Pytorch. \begin{figure}[htbp] \centering \subfloat[ normal cells of G-PC-DARTS-A]{ \label{fig:improved_subfig_a} \includegraphics [width=0.33\textwidth]{45.pdf} \hspace{10 pt} } \subfloat[ reduce cells of G-PC-DARTS-A]{ \label{fig:improved_subfig_a} \includegraphics [width=0.66\textwidth]{41.pdf} \hspace{10 pt} } \newline \subfloat[normal cells of DARTS-with-Attention]{ \label{fig:improved_subfig_a} \includegraphics [width=0.5\textwidth]{42.pdf} \hspace{10 pt} } \subfloat[ reduce cells of DARTS-with-Attention]{ \label{fig:improved_subfig_a} \includegraphics [width=0.45\textwidth]{43.pdf} \hspace{10 pt} } \newline \subfloat[normal cells of G-DARTS-A]{ \label{fig:improved_subfig_a} \includegraphics [width=0.8\textwidth]{46.pdf} \hspace{10 pt} } \newline \subfloat[reduce cells of G-DARTS-A]{ \label{fig:improved_subfig_a} \includegraphics [width=0.9\textwidth]{44.pdf} \hspace{10 pt} } \caption{Cells of G-PC-DARTS-A and DARTS-with-Attention found on CIFAR10} \label{fig:subfig} \end{figure} \subsection{Architecture Evaluation on CIFAR10 and CIFAR100} For DARTS-with-Attention and G-PC-DARTS-A, we both train a large network of 20 cells for 600 epoch with batch size 96, and the initial number of channels is increased from 16 (search process) to 36. The remaining hyperparameters keep same as those used for searching architecture. Path dropout\cite{srivastava2014dropout} of probability 0.2 and auxiliary towers with weight 0.4. The size of searched architecture is 4.2M and 3.3M on DARTS-with-Attention and G-PC-DARTS-A respectively. Our searched architectures remain small size together with great performance. DARTS-with-Attention achieved 2.82\%/16.36\% rate of evaluation error on CIFAR10/CIFA100, and G-PC-DARTS-A provide 2.64\%/16.87\% error on CIFAR10/CIFAR100. The specific experimental data is shown in table1. \begin{table*}[t] \caption{Comparison with state-of-the-art architectures on CIFAR10 and CIFAR100.} \begin{center} \resizebox{\textwidth}{!}{ \begin{tabular}{lccccc} \hline\noalign{\smallskip} \textbf{\multirow{2}{*}{Architecture}} & \multicolumn{2}{c}{\textbf{Test Err. (\%})} & \textbf{Params} & \textbf{Search Cost} & \textbf{\multirow{2}{*}{Search Method}} \\ \cmidrule(lr){2-3} & \textbf{C10} & \textbf{C100} & \textbf{(M)} & \textbf{(GPU-days)} &\\ \noalign{\smallskip}\hline\noalign{\smallskip} DenseNet-BC~\cite{huang2017densely} & 3.46 & 17.18 & 25.6 & - & manual \\ \noalign{\smallskip}\hline\noalign{\smallskip} NASNet-A + cutout\cite{zoph2018learning} & 2.65 & - & 3.3 & 1\rm{,}800 & RL \\ AmoebaNet-B + cutout\cite{real2019regularized} & 2.55 & - & 2.8 & 3\rm{,}150 & evolution \\ Hireachical Evolution\cite{liu2017hierarchical} & 3.75 & - & 15.7 & 300 & evolution \\ PNAS\cite{liu2018progressive} & 3.41 & - & 3.2 & 225 & SMBO \\ ENAS + cutout\cite{pham2018efficient} & 2.89 & - & 4.6 & 0.5 & RL \\ NAONet-WS\cite{luo2018neural} & 3.53 & - & 3.1 & 0.4 & NAO \\ \noalign{\smallskip}\hline\noalign{\smallskip} DARTS (first order) + cutout\cite{hanxiao2019darts} & 3.00 & 17.76$^\dagger$ & 3.3 & 1.5$^\ddagger$ & gradient-based \\ DARTS (second order) + cutout\cite{hanxiao2019darts} & 2.76 & 17.54$^\dagger$ & 3.3 & 4.0$^\ddagger$ & gradient-based \\ SNAS + mild constraint + cutout\cite{xie2018snas} & 2.98 & - & 2.9 & 1.5 & gradient-based \\ SNAS + moderate \\ constraint + cutout\cite{xie2018snas} & 2.85 & - & 2.8 & 1.5 & gradient-based \\ BayesNAS + cutout\cite{zhou2019bayesnas} & 2.81±0.04 & - & 3.4 & 0.2 & gradient-based \\ ProxylessNAS + cutout\cite{cai2019proxylessnas} & 2.08 & - & 5.7 & 4.0 & gradient-based \\ P-DARTS + cutout\cite{chen2019progressive} & 2.50 & 17.20 & 3.4 & 0.3 & gradient-based \\ PC-DARTS + cutout\cite{xu2019pc} & 2.57 & - & 3.6 & 0.1 & gradient-based \\ \noalign{\smallskip}\hline\noalign{\smallskip} DARTS (first order) with \\ Attention CIFAR10 + cutout & 2.82 & 16.36 &4.2 & 0.4 & gradient-based \\ G-DARTS (first order)-A \\ CIFAR10+cutout & 2.57 & 16.51 & 4.2 & 0.5 & gradient-based \\ G-PC-DARTS with Attention \\ CIFAR10 + cutout & 2.61 & - & 2.8 & 0.3 & gradient-based \\ \noalign{\smallskip}\hline \end{tabular} } \end{center} \label{tab_ev_cifar} \end{table*} \section{Conclusion} In this article, we propose a Channel Group Parallel Sampling technique with attention. The main method is to sample the feature map in multi-channel group to improve the computational efficiency while ensuring the integrity of the feature information. Attention weights contribute to balancing the relationship between each channel group, and we use it alone on DARTS and get an error rate of 2.82\%/16.36\% on CIFAR10/CIFAR100. Applying our complete technology to PC-DARTS, we get an error rate of 2.64\%/16.87\% on CIFAR10/CIFAR100.\\ According to the experimental process and results of this work, the following four ideas are proposed. (i) The effective results of this work indicate that the value between architecture parameters and ordinary network weights is quite different, and a certain way is needed to distinguish them, especially by adding some parameters that are optimized only in the architecture search process to assist its optimization, such as our attention parameter and the edge normalization proposed by PC-DARTS. This work points out that different channel groups have independent and different values in the search process, which means we can take more flexible way to search for neural network structures. (iii) The results of this paper may imply excessive redundancy of model channel information. we can try to compress the model by reducing the number of channels together with adding an attention mechanism. (iv) These findings may exist in the generated training model. we can try to introduce multiple sets of parallelism and attention mechanisms to the final model. There is still various work worth exploring, and we will further supplement experiment to explore the value behind problem in more depth. \bibliographystyle{unsrt}
{'timestamp': '2020-10-19T02:16:24', 'yymm': '2010', 'arxiv_id': '2010.08360', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08360'}
arxiv
\subsubsection*{\bibname}} \usepackage{booktabs} \usepackage{enumitem} \usepackage{mdframed} \usepackage{bm} \usepackage{hyperref} \usepackage{amssymb,amsmath} \usepackage{mathtools} \mathtoolsset{showonlyrefs} \usepackage{amsthm} \usepackage{algorithm} \usepackage[noend]{algpseudocode} \algrenewcommand{\algorithmiccomment}[1]{$\vartriangleright$ #1} \algrenewcommand{\algorithmicreturn}{\textbf{Return: }} \algnewcommand\algorithmicinput{\textbf{Input: }} \algnewcommand\Input{\State \algorithmicinput} \usepackage{todonotes} \DeclareMathOperator*{\argmax}{argmax} \DeclareMathOperator*{\argmin}{argmin} \DeclareMathOperator*{\diag}{diag} \def\text{vec}{\text{vec}} \def\text{\normalfont{dtw}}{\textsc{dtw}} \def\textsc{OT}{\textsc{OT}} \def\text{\normalfont{sdtw}}{\textsc{sdtw}} \def\textsc{sdtw}_\gamma{\textsc{sdtw}_\gamma} \def\textsc{sharp}_\gamma{\textsc{sharp}_\gamma} \def\text{min}{\text{min}} \defD_\gamma^C{D_\gamma^C} \defS_\gamma^C{S_\gamma^C} \def\text{\textsc{mean\_cost}}{\text{\textsc{mean\_cost}}} \def\text{\normalfont{Delannoy}}{\text{\normalfont{Delannoy}}} \def\bm{p}{\bm{p}} \def\bm{A}{\bm{A}} \def\bm{B}{\bm{B}} \def{\bm{C}}{{\bm{C}}} \def\bm{E}{\bm{E}} \def\bm{H}{\bm{H}} \def\bm{K}{\bm{K}} \def\bm{M}{\bm{M}} \def\bm{P}{\bm{P}} \def\bm{Q}{\bm{Q}} \def\bm{T}{\bm{T}} \def{\bm{V}}{{\bm{V}}} \def{\bm{X}}{{\bm{X}}} \def{\bm{Y}}{{\bm{Y}}} \def{\bm{Z}}{{\bm{Z}}} \def\bm{\omega}{\bm{\omega}} \def\bm{\Delta}{\bm{\Delta}} \def{\bm{v}}{{\bm{v}}} \def{\bm{t}}{{\bm{t}}} \def{\bm{x}}{{\bm{x}}} \def{\bm{y}}{{\bm{y}}} \def{\bm{1}}{{\bm{1}}} \def{\bm{0}}{{\bm{0}}} \def\bm{\alpha}{\bm{\alpha}} \def\bm{\beta}{\bm{\beta}} \def\mathcal{A}{\mathcal{A}} \def\mathcal{S}{\mathcal{S}} \def\mathcal{U}{\mathcal{U}} \def\mathbb{N}{\mathbb{N}} \def\mathbb{R}{\mathbb{R}} \def\mathbb{E}{\mathbb{E}} \def\mathbb{P}{\mathbb{P}} \def\RR^{m \times n}{\mathbb{R}^{m \times n}} \def\RR^{m \times d}{\mathbb{R}^{m \times d}} \def\RR^{n \times d}{\mathbb{R}^{n \times d}} \def\RR^{m \times m}{\mathbb{R}^{m \times m}} \def\RR^{n \times n}{\mathbb{R}^{n \times n}} \newcommand{\partialfrac}[2]{\frac{\partial #1}{\partial #2}} \newmdtheoremenv{proposition}{Proposition} \newmdtheoremenv{lemma}{Lemma} \newmdtheoremenv{corollary}{Corollary} \usepackage{color} \usepackage{xcolor} \colorlet{darkblue}{blue!80!black} \colorlet{darkred}{red!80!black} \colorlet{darkgreen}{green!60!black} \colorlet{darkmagenta}{orange!80!black} \colorlet{darkyellow}{purple!80!black} \newcommand{\myred}[1]{\textcolor{darkred}{#1}} \newcommand{\myblue}[1]{\textcolor{darkblue}{#1}} \newcommand{\mygreen}[1]{\textcolor{darkgreen}{#1}} \newcommand{\mygray}[1]{\textcolor{gray}{#1}} \newcommand{\mymagenta}[1]{\textcolor{darkmagenta}{#1}} \newcommand{\myyellow}[1]{\textcolor{darkyellow}{#1}} \hypersetup{ colorlinks, linkcolor={black}, citecolor={blue!50!black}, urlcolor={blue!50!black} } \newcommand{\jpvert}[1]{\textcolor{cyan}{\texttt{jpvert@} #1}} \newcommand{\mblondel}[1]{\textcolor{magenta}{\texttt{mblondel@} #1}} \begin{document} \twocolumn[ \aistatstitle{Differentiable Divergences Between Time Series} \aistatsauthor{ Mathieu Blondel \And Arthur Mensch \And Jean-Philippe Vert} \aistatsaddress{ Google Research, Brain team \And \'{E}cole Normale Sup\'{e}rieure \And Google Research, Brain team } ] \begin{abstract} Computing the discrepancy between time series of variable sizes is notoriously challenging. While dynamic time warping (DTW) is popularly used for this purpose, it is not differentiable everywhere and is known to lead to bad local optima when used as a ``loss''. Soft-DTW addresses these issues, but it is not a positive definite divergence: due to the bias introduced by entropic regularization, it can be negative and it is not minimized when the time series are equal. We propose in this paper a new divergence, dubbed soft-DTW divergence, which aims to correct these issues. We study its properties; in particular, under conditions on the ground cost, we show that it is a valid divergence: it is non-negative and minimized if and only if the two time series are equal. We also propose a new ``sharp'' variant by further removing entropic bias. We showcase our divergences on time series averaging and demonstrate significant accuracy improvements compared to both DTW and soft-DTW on 84 time series classification datasets. \end{abstract} \section{Introduction} Designing a meaningful discrepancy or ``loss'' between two sequences of variable lengths and integrating it in an end-to-end differentiable pipeline is challenging. For sequences on finite alphabets, differentiable local alignment kernels \citep{saigo_2006} and edit distances \citep{mccallum_2012} have been proposed. For sequences on continuous domains, connectionist temporal classification (CTC) is popularly used in speech recognition \citep{graves_2006}. A related approach for time series motivated by geometry is dynamic time warping (DTW), which seeks a minimum-cost alignment between time series and can be computed by dynamic programming in quadratic time \citep{sakoe_1978}. However, DTW is not differentiable everywhere, is sensitive to noise and is known to lead to bad local optima when used as a loss. Soft-DTW \citep{soft_dtw} addresses these issues by replacing the minimum over alignments with a soft minimum, which has the effect of inducing a probability distribution over all alignments. Despite considering all alignments, it is shown that soft-DTW can still be computed by dynamic programming in the same complexity. Since then, soft-DTW has been successfully applied for audio to music score alignment \citep{diff_dp}, video segmentation \citep{d3tw}, spatial-temporal sequences \citep{janati_2020}, and end-to-end differentiable text-to-speech synthesis \citep{donahue_2020}, to name but a few examples. Soft-DTW is included in popular R and Python packages for time series analysis \citep{sarda_2017,tavenard_2020}. In this paper, we show that, despite recent successes, soft-DTW has some limitations which have been overlooked in the literature. First, it can be negative, which is a nuisance when used as a loss. Second, and more problematically, when used with a squared Euclidean cost, we show that it is never minimized when the two time series are equal. Put differently, given an input time series, the closest time series in the soft-DTW sense is never the input time series. This is due to the entropic bias introduced by replacing the minimum with a soft one. We propose in this paper a new divergence, dubbed soft-DTW divergence, which is based on soft-DTW but corrects for these issues. We study its properties; in particular, under condition on the ground cost, we show that it is a valid divergence: it is non-negative and it is minimized if and only if the two time series are equal. Our approach is related to Sinkhorn divergences \citep{ramdas_2017,genevay_2018,feydy_2019}, which use similar correction terms as we do for optimal transport distances, but our proof techniques are completely different. We also propose a new ``sharp'' variant by further removing entropic bias. We showcase our divergences on time series averaging and demonstrate significant accuracy improvements compared to both DTW and soft-DTW on 84 time series classification datasets. The rest of the paper is organized as follows. After reviewing some background in \S\ref{sec:background}, we introduce the soft-DTW divergence and its ``sharp'' variant in \S\ref{sec:proposed_div}. We study their properties and limit behavior. We study their empirical performance in \S\ref{sec:exp} with experiments on time series averaging, interpolation and classification. \section{Background} \label{sec:background} \subsection{Dynamic time warping} Let ${\bm{X}} \in \mathbb{R}^{m \times d}$ and ${\bm{Y}} \in \mathbb{R}^{n \times d}$ be two $d$-dimensional time series of lengths $m$ and $n$. We denote their elements by ${\bm{x}}_i \in \mathbb{R}^d$ and ${\bm{y}}_j \in \mathbb{R}^d$, for $i \in [m]$ and $j \in [n]$. We say that $\bm{A} \in \{0,1\}^{m \times n}$ is an alignment matrix between ${\bm{X}}$ and ${\bm{Y}}$ when $[\bm{A}]_{i,j} = 1$ if ${\bm{x}}_i$ is aligned with ${\bm{y}}_j$ and $0$ otherwise. We say that $\bm{A}$ is a monotonic alignment matrix if the ones in $\bm{A}$ form a path starting from the upper-left corner $(1,1)$ that connects the lower-right corner $(m,n)$ using only $\downarrow$, $\rightarrow$, $\searrow$ moves. We denote the set of all such monotonic alignment matrices by $\mathcal{A}(m,n) \subset \{0,1\}^{m \times n}$. The cardinality $|\mathcal{A}(m,n)|$ grows exponentially in $\min(m,n)$ and is equal to the Delannoy number, $\text{Delannoy}(m-1,n-1)$, named after French amateur mathematician Henri Delannoy \citep{sulanke_2003,banderier_2005}. Let $C \colon \mathbb{R}^{m \times d} \times \mathbb{R}^{n \times d} \to \mathbb{R}^{m \times n}$ be a function which maps ${\bm{X}} \in \mathbb{R}^{m \times d}$ and ${\bm{Y}} \in \mathbb{R}^{n \times d}$ to a distance or cost matrix ${\bm{C}} = C({\bm{X}}, {\bm{Y}}) \in \mathbb{R}^{m \times n}$. A popular choice is the squared Euclidean cost \begin{equation} [C({\bm{X}}, {\bm{Y}})]_{i,j} = \frac{1}{2} \|{\bm{x}}_i - {\bm{y}}_j\|^2_2 \quad i \in [m], j \in [n]. \label{eq:squared_euclidean} \end{equation} The Frobenius inner product $\langle \bm{A}, {\bm{C}} \rangle \coloneqq \text{Trace}({\bm{C}}^\top \bm{A})$ between ${\bm{C}}$ and $\bm{A}$ is the sum of the costs along the alignment (Figure \ref{fig:dag}). Dynamic time warping \citep{sakoe_1978} can then be naturally formulated as the minimum cost among all possible alignments, \begin{equation} \text{\normalfont{dtw}}({\bm{C}}) \coloneqq \min_{\bm{A} \in \mathcal{A}(m,n)} \langle \bm{A}, {\bm{C}} \rangle. \label{eq:dtw} \end{equation} The corresponding optimal alignment (not necessarily unique) is then \begin{equation} \bm{A}^\star({\bm{C}}) \in \argmin_{\bm{A} \in \mathcal{A}(m,n)} \langle \bm{A}, {\bm{C}} \rangle. \label{eq:optimal_alignment} \end{equation} Despite the exponential number of alignments, \eqref{eq:dtw} and \eqref{eq:optimal_alignment} can be computed in $O(mn)$ time using dynamic programming and backtracking, respectively. The quantity $\text{\normalfont{dtw}}(C({\bm{X}}, {\bm{Y}}))$ is popularly used as a discrepancy measure between time series in numerous applications. In the rest of the paper, we will make the following assumptions about the ground cost $C$: \begin{itemize}[topsep=0pt,itemsep=3pt,parsep=2pt,leftmargin=9pt] \item A.1. $C({\bm{X}}, {\bm{Y}}) \ge {\bm{0}}_{m \times n}$ (non-negativity), \item A.2. $[C({\bm{X}}, {\bm{X}})]_{i,i} = 0$ for all $i \in [m]$, \item A.3. $C({\bm{X}}, {\bm{Y}}) = C({\bm{Y}}, {\bm{X}})^\top$ (symmetry). \end{itemize} The properties of $\text{\normalfont{dtw}}$ under these assumptions are summarized in Table \ref{table:properties}. Note that $\text{\normalfont{dtw}}$ is minimized at ${\bm{X}} = {\bm{Y}}$ but this may not be the unique minimum. \begin{table*}[t] \caption{Properties of time-series losses under assumptions A.1-A.3 and differentiability of $C$. For the soft-DTW divergence, we prove non-negativity and ``minimized at ${\bm{X}}={\bm{Y}}$'' using the cost \eqref{eq:log_cost} and one-dimensional absolute value \eqref{eq:lap_cost} (cf.\ Proposition \ref{prop:non_negativity_log}). For the soft-DTW and sharp divergences with the squared Euclidean cost \eqref{eq:squared_euclidean}, we only prove that ${\bm{X}}={\bm{Y}}$ is a stationary point (cf.\ Proposition \ref{prop:stationary_point}) } \label{table:properties} \centering \begin{tabular}{lcccc} \toprule & Non-negativity & Minimized at ${\bm{X}}={\bm{Y}}$ & Symmetry & Differentiable everywhere \\ \midrule DTW & $\checkmark$ & $\checkmark$ & $\checkmark$ & $\times$ \\[0.3em] Soft-DTW & $\times$ & $\times$ & $\checkmark$ & $\checkmark$ \\[0.3em] Sharp soft-DTW & $\checkmark$ & $\times$ & $\checkmark$ & $\checkmark$ \\[0.3em] Soft-DTW divergence & $\checkmark$ & $\checkmark$ & $\checkmark$ & $\checkmark$ \\[0.3em] Sharp divergence & $\checkmark$ & $\checkmark$ & $\checkmark$ & $\checkmark$ \\[0.3em] Mean-cost divergence & $\checkmark$ & $\checkmark$ & $\checkmark$ & $\checkmark$ \\[0.3em] \hline \end{tabular} \end{table*} \begin{figure} \centering \includegraphics[width=0.48\textwidth]{tikz/dtw} \caption{An alignment between two time series ${\bm{X}} \in \RR^{m \times d}$ and ${\bm{Y}} \in \RR^{n \times d}$ corresponds to a path in a directed acyclic graph (DAG) and can be encoded as a binary matrix $\bm{A} \in \{0,1\}^{m \times n}$. The sum of the costs along the path is then $\langle \bm{A}, {\bm{C}} \rangle$. DTW seeks a minimum cost alignment, while soft-DTW seeks the soft minimum cost alignment. The latter induces a Gibbs distribution over all alignments.} \label{fig:dag} \end{figure} \subsection{Soft dynamic time warping} \label{sec:sdtw} \paragraph{Definitions.} In order to obtain a fully differentiable discrepancy measure between time series, \citet{soft_dtw} proposed to replace the min operator in \eqref{eq:dtw} by a smooth one, \begin{equation} \underset{x \in \mathcal{S}}{\text{min}_\gamma} ~ f(x) \coloneqq -\gamma \log \sum_{x \in \mathcal{S}} \exp(-f(x) / \gamma), \end{equation} where $\gamma > 0$ is a parameter which controls the trade-off between approximation and smoothness. For convenience, we define the extension $\text{min}_0 \coloneqq \min$. The resulting ``soft'' dynamic time warping formulation is \begin{align} \textsc{sdtw}_\gamma({\bm{C}}) &\coloneqq \underset{\bm{A} \in \mathcal{A}(m,n)}{\text{min}_\gamma} \langle \bm{A}, {\bm{C}} \rangle \\ &= -\gamma \log \sum_{\bm{A} \in \mathcal{A}(m,n)} \exp(-\langle \bm{A}, {\bm{C}} \rangle / \gamma). \label{eq:sdtw} \end{align} Instead of only considering the minimum-cost alignment as in \eqref{eq:dtw}, \eqref{eq:sdtw} induces a Gibbs distribution over alignments. The probability of $\bm{A}$ given ${\bm{C}} \in \mathbb{R}^{m \times n}$ is \begin{equation} \mathbb{P}_\gamma(\bm{A}; {\bm{C}}) \coloneqq \frac{\exp(-\langle \bm{A}, {\bm{C}} \rangle / \gamma)} {\sum_{\bm{A}' \in \mathcal{A}(m,n)} \langle -\langle \bm{A}', {\bm{C}} \rangle / \gamma)} \in (0,1]. \label{eq:proba} \end{equation} We can see \eqref{eq:sdtw} as the negative log-partition of \eqref{eq:proba}. For convenience, we also gather the probabilities of all possible alignments in a vector \begin{equation} \bm{p}_\gamma({\bm{C}}) \coloneqq (\mathbb{P}_\gamma(\bm{A}; {\bm{C}}))_{\bm{A} \in \mathcal{A}(m,n)} \in \triangle^{|A(m,n)|}, \end{equation} where $\triangle^k \coloneqq \{\bm{p} \in \mathbb{R}^k \colon \bm{p} \ge {\bm{0}}_k, \bm{p}^\top {\bm{1}}_k = 1\}$ is the probability simplex. Let $A$ be a random variable distributed according to \eqref{eq:proba}. The expected alignment matrix under the Gibbs distribution induced by ${\bm{C}}$ is \begin{equation} \bm{E}_\gamma({\bm{C}}) \coloneqq \mathbb{E}_\gamma[A; {\bm{C}}] = \sum_{\bm{A} \in \mathcal{A}(m,n)} \mathbb{P}_\gamma(\bm{A}; {\bm{C}}) \bm{A} \in (0,1]^{m \times n}. \label{eq:expectation} \end{equation} Note that because the matrices in $\mathcal{A}(m,n)$ are binary ones, $[\bm{E}_\gamma({\bm{C}})]_{i,j}$ is also equal to the marginal probability $\mathbb{P}_\gamma(A_{i,j}=1; {\bm{C}})$, i.e., the probability that any of the paths goes through the cell $(i,j)$. \paragraph{Computation.} Surprisingly, even though \eqref{eq:sdtw} contains a sum over all $\bm{A}$ in $\mathcal{A}(m,n)$, it can be computed in $O(mn)$ time by simply replacing the $\min$ operator with $\text{min}_\gamma$ in the original dynamic programming recursion \citep{soft_dtw}. See also Algorithm \ref{alg:sdtw_value} in Appendix \ref{appendix:algorithms}. The equivalence between \eqref{eq:sdtw} and this ``locally smoothed'' recursion was later formally proved using the associativity of the $\text{min}_\gamma$ operator \citep{diff_dp}. The expected alignment can also be computed in $O(mn)$ time by backpropagation through the dynamic programming recursion \citep{soft_dtw}. See also Algorithm \ref{alg:sdtw_gradient} in Appendix \ref{appendix:algorithms}. \paragraph{Properties.} The following proposition summarizes known properties of $\textsc{sdtw}_\gamma$ \citep{soft_dtw,diff_dp}. \begin{proposition}{Properties of $\textsc{sdtw}_\gamma$} The following properties hold for all ${\bm{C}} \in \mathbb{R}^{m \times n}$. \begin{enumerate}[topsep=0pt,itemsep=3pt,parsep=2pt,leftmargin=9pt] \item {\bf Gradient:} $\textsc{sdtw}_\gamma({\bm{C}})$ is differentiable everywhere and its gradient is the expected alignment, \begin{equation} \nabla_{\bm{C}} \text{\normalfont{sdtw}}_\gamma({\bm{C}}) = \bm{E}_\gamma({\bm{C}}) \in (0,1]^{m \times n}. \end{equation} \item {\bf Concavity:} $\textsc{sdtw}_\gamma({\bm{C}})$ is concave in ${\bm{C}}$. \item {\bf Variational form:} letting $H(\bm{p}) = -\langle \bm{p}, \log \bm{p} \rangle$, \begin{equation} \textsc{sdtw}_\gamma({\bm{C}}) = \min_{\bm{p} \in \triangle^{|\mathcal{A}(m,n)|}} \langle \bm{p}, \bm{s}({\bm{C}}) \rangle - \gamma H(\bm{p}) \label{eq:varitional_form} \end{equation} where $\bm{s}({\bm{C}}) \coloneqq (\langle \bm{A}, {\bm{C}} \rangle)_{\bm{A} \in \mathcal{A}(mmn)} \in \mathbb{R}^{|\mathcal{A}(m,n)|}$. \item {\bf Scaling:} $\textsc{sdtw}_\gamma({\bm{C}}) = \gamma \text{\normalfont{sdtw}}_1({\bm{C}} / \gamma)$, $\bm{E}_\gamma({\bm{C}}) = \bm{E}_1({\bm{C}} / \gamma)$ and $\bm{p}_\gamma({\bm{C}}) = \bm{p}_1({\bm{C}} / \gamma)$. \item {\bf Asymptotics:} $\text{\normalfont{dtw}}({\bm{C}}) \xleftarrow[0 \leftarrow \gamma]{} \textsc{sdtw}_\gamma({\bm{C}})$ and $\bm{A}^\star({\bm{C}}) \xleftarrow[0 \leftarrow \gamma]{} \bm{E}_\gamma({\bm{C}})$. \item {\bf Lower and upper bounds:} \begin{equation} \small \text{\normalfont{dtw}}({\bm{C}}) - \gamma \log |\mathcal{A}(m,n)| \le \text{\normalfont{sdtw}}_\gamma({\bm{C}}) \le \text{\normalfont{dtw}}({\bm{C}}). \end{equation} \end{enumerate} \label{prop:sdtw_properties} \end{proposition} Note that $\textsc{sdtw}_\gamma(C({\bm{X}}, {\bm{Y}}))$ is generally neither convex nor concave in ${\bm{X}}$ and ${\bm{Y}}$, as is the case when $C$ is the squared Euclidean cost \eqref{eq:squared_euclidean}. A notable exception is $C({\bm{X}}, {\bm{Y}}) = -{\bm{X}} {\bm{Y}}^\top$, for which $\textsc{sdtw}_\gamma(C({\bm{X}}, {\bm{Y}}))$ is concave in ${\bm{X}}$ and ${\bm{Y}}$ (separately). \paragraph{Use as a loss function.} The differentiability of $\textsc{sdtw}_\gamma$ makes it particularly suitable to use as a loss function between time series, of potentially variable lengths. An example of application is the computation of Fr\'{e}chet means (\citeyear{frechet_1948}) with respect to $\textsc{sdtw}_\gamma$. Specifically, given a set of $k$ time series ${\bm{Y}}_1 \in \mathbb{R}^{n_1 \times d}$, $\dots$, ${\bm{Y}}_k \in \mathbb{R}^{n_k \times d}$, we compute its average (barycenter) according to $\textsc{sdtw}_\gamma$ by solving \begin{equation} \argmin_{{\bm{X}} \in \mathbb{R}^{m \times d}} \sum_{i=1}^k w_i ~ \textsc{sdtw}_\gamma(C({\bm{X}}, {\bm{Y}}_i)), \label{eq:barycenter_obj} \end{equation} where $\bm{w} = (w_1, \dots, w_k) \in \mathbb{R}^k$ is a vector of pre-defined weights. When the time series ${\bm{Y}}_1,\dots,{\bm{Y}}_k$ have different lengths, a typical choice would be $w_i = 1/n_i$, to compensate for the fact that $\textsc{sdtw}_\gamma$ increases with the length of the time series. Although it is non-convex, objective \eqref{eq:barycenter_obj} can be solved approximately by gradient-based methods. Compared to DTW barycenter averaging (DBA) \citep{petitjean_2011}, it was shown that smoothing helps to avoid bad local optima. Using the chain rule and item 1 of Proposition \ref{prop:sdtw_properties}, the gradient of $\textsc{sdtw}_\gamma(C({\bm{X}}, {\bm{Y}}))$ w.r.t.\ ${\bm{X}}$ is \begin{equation} \nabla_{\bm{X}} \textsc{sdtw}_\gamma(C({\bm{X}}, {\bm{Y}})) = (J_{\bm{X}} C({\bm{X}}, {\bm{Y}}))^\top \bm{E}_\gamma({\bm{C}}({\bm{X}}, {\bm{Y}})). \label{eq:sdtw_grad_X} \end{equation} Here, we assume that $C$ is differentiable and $J_{\bm{X}}$ denotes the Jacobian matrix of ${\bm{C}}({\bm{X}}, {\bm{Y}})$ w.r.t.\ ${\bm{X}}$, a linear map from $\mathbb{R}^{m \times d}$ to $\mathbb{R}^{m \times n}$ (its transpose is a linear map from $\mathbb{R}^{m \times n}$ to $\mathbb{R}^{m \times d}$). \subsection{Global alignment kernel} Although it was introduced before soft dynamic time warping, the global alignment kernel \citep{cuturi_2007} can be naturally expressed using $\textsc{sdtw}_\gamma$ as \begin{equation} K_\gamma^C({\bm{X}}, {\bm{Y}}) \coloneqq \exp(-\text{\normalfont{sdtw}}_1(C({\bm{X}}, {\bm{Y}}) / \gamma)). \label{eq:ga_kernel} \end{equation} Using a constructive proof, it was shown that \eqref{eq:ga_kernel} is a positive definite (p.d.) kernel under certain cost functions and in particular with \begin{equation} [C({\bm{X}}, {\bm{Y}})]_{i,j} = \delta({\bm{x}}_i, {\bm{y}}_i) + \log(2 - \exp(-\delta({\bm{x}}_i, {\bm{y}}_i)), \label{eq:log_cost} \end{equation} where $\delta({\bm{x}}, {\bm{y}}) \coloneqq \frac{1}{2} \|{\bm{x}} - {\bm{y}}\|^2_2$. In the one-dimensional case ($d=1$), we show in Appendix \ref{app:laplacian} that \begin{equation} [C({\bm{X}}, {\bm{Y}})]_{i,j} = \|{\bm{x}}_i - {\bm{y}}_j\|_1, \label{eq:lap_cost} \end{equation} also has the property that the kernel \eqref{eq:ga_kernel} is p.d. Using these costs, \eqref{eq:ga_kernel} can be used in any kernel method, such as support vector machines. The positive definiteness of \eqref{eq:ga_kernel} using the squared Euclidean cost \eqref{eq:squared_euclidean} has to our knowledge not been proved or disproved yet. \begin{figure} \centering \includegraphics[scale=0.45]{figures/entropic_bias.pdf} \caption{{\bf Denoising effect of soft-DTW.} We show the result of $\argmin_{{\bm{X}}} \textsc{sdtw}_\gamma(C({\bm{X}}, {\bm{Y}}))$, solved by L-BFGS with ${\bm{X}}={\bm{Y}}$ as initialization, for two values of $\gamma$. As stated in Proposition \ref{prop:limitations}, $\textsc{sdtw}_\gamma$ with $\gamma > 0$ and squared Euclidean cost never achieves its minimum at ${\bm{X}}={\bm{Y}}$. While this denoising can be useful, this means that $\textsc{sdtw}_\gamma$ is not a valid divergence.} \label{fig:denoising} \end{figure} \section{New differentiable divergences} \label{sec:proposed_div} In this section, we begin by pointing out potential limitations of soft-DTW. We then introduce two new divergences, the soft-DTW divergence and its sharp variant, which aim to correct for these limitations. We study their properties and limit behavior. \paragraph{Limitations of soft-DTW.} Despite recent empirical successes, soft-DTW has some inherent limitations that were not discussed in previous works. The following proposition clarifies these limitations. \begin{proposition}{Limitations of $\textsc{sdtw}_\gamma$} The following holds. \begin{enumerate}[topsep=0pt,itemsep=3pt,parsep=2pt,leftmargin=9pt] \item For all ${\bm{C}} \in \mathbb{R}^{m \times n}$, $\gamma \mapsto \textsc{sdtw}_\gamma({\bm{C}})$ is non-increasing, concave, and diverges to $-\infty$ when $\gamma\rightarrow +\infty$. In particular, there exists $\gamma_0 \in [0, \infty)$ such that $\textsc{sdtw}_\gamma({\bm{C}}) \le 0$ for all $\gamma \ge \gamma_0$. \item For all cost functions $C$ satisfying A.2, ${\bm{X}}\in\mathbb{R}^{m\times d}$ and $\gamma \in [0, \infty)$, $\textsc{sdtw}_\gamma(C({\bm{X}}, {\bm{X}})) \le 0$. \item For the squared Euclidean cost \eqref{eq:squared_euclidean} and any $\gamma \in (0, \infty)$, the minimum of $\textsc{sdtw}_\gamma(C({\bm{X}}, {\bm{Y}}))$ is not achieved at ${\bm{X}} = {\bm{Y}}$. \end{enumerate} \label{prop:limitations} \end{proposition} A proof is given in Appendix \ref{appendix:proof_limitations}. Proposition \ref{prop:limitations} shows that that there exists values of $\gamma$ or ${\bm{C}}$ for which $\textsc{sdtw}_\gamma({\bm{C}})$ is negative. Non-negativity is a useful property of divergences and the fact that $\textsc{sdtw}_\gamma$ does not satisfy it can be a nuisance. More problematic is the fact that $\textsc{sdtw}_\gamma(C({\bm{X}}, {\bm{Y}}))$ is not minimized at ${\bm{X}} = {\bm{Y}}$. This is illustrated in Figure \ref{fig:denoising}. While the denoising effect of soft-DTW can be useful, we would expect a proper differentiable divergence to be zero when the two time series are equal. \paragraph{Soft-DTW divergences.} To address these issues, we propose to use for all ${\bm{X}} \in \RR^{m \times d}$ and ${\bm{Y}} \in \RR^{n \times d}$ \begin{align} D_\gamma^C({\bm{X}}, {\bm{Y}}) \coloneqq ~ &\textsc{sdtw}_\gamma(C({\bm{X}}, {\bm{Y}})) \\ -\frac{1}{2} &\textsc{sdtw}_\gamma(C({\bm{X}}, {\bm{X}})) \\ -\frac{1}{2} &\textsc{sdtw}_\gamma(C({\bm{Y}}, {\bm{Y}})). \end{align} Since it is based on soft-DTW, we call it the soft-DTW divergence. Sinkhorn divergences \citep{ramdas_2017,genevay_2018,feydy_2019}, which are divergences between probability measures based on entropy-regularized optimal transport, use similar correction terms. \paragraph{Sharp divergences.} The variational form of $\textsc{sdtw}_\gamma$ (Proposition \ref{prop:sdtw_properties}) implies that it can be decomposed as the sum of a cost term and an entropy term, \begin{equation} \textsc{sdtw}_\gamma({\bm{C}}) = \langle \bm{E}_\gamma({\bm{C}}), {\bm{C}} \rangle - \gamma H(\bm{p}_\gamma({\bm{C}})). \label{eq:decomposition} \end{equation} On the other hand, we have \begin{equation} \text{\normalfont{dtw}}({\bm{C}}) = \langle \bm{A}^\star({\bm{C}}), {\bm{C}} \rangle. \end{equation} Since $\bm{E}_\gamma({\bm{C}}) \to \bm{A}^\star({\bm{C}})$ when $\gamma \to 0$, this suggests a new discrepancy measure, \begin{equation} \textsc{sharp}_\gamma({\bm{C}}) \coloneqq \langle \bm{E}_\gamma({\bm{C}}), {\bm{C}} \rangle. \label{eq:sharp} \end{equation} It is the directional derivative of $\textsc{sdtw}_\gamma({\bm{C}})$ in the direction of ${\bm{C}}$, since $\bm{E}_\gamma({\bm{C}}) = \nabla_{\bm{C}} \textsc{sdtw}_\gamma({\bm{C}})$. Inspired by \citet{luise_2018}, who studied a similar idea in an optimal transport context,we call it sharp soft-DTW, since it removes the entropic regularization term $-\gamma H(\bm{p}_\gamma({\bm{C}}))$ from \eqref{eq:decomposition}. Its gradient is equal to \begin{equation} \nabla_{\bm{C}} \textsc{sharp}_\gamma({\bm{C}}) = \bm{E}_\gamma({\bm{C}}) + \frac{1}{\gamma} \nabla^2_{\bm{C}} \textsc{sdtw}_\gamma({\bm{C}}) {\bm{C}} \in \RR^{m \times n}, \label{eq:sharp_gradient} \end{equation} where $\nabla^2_{\bm{C}} \textsc{sdtw}_\gamma({\bm{C}}) {\bm{C}}$ is a Hessian-vector product (that can be computed efficiently, as we detail below). The gradient w.r.t.\ ${\bm{X}}$ is obtained by the chain rule, similarly to \eqref{eq:sdtw_grad_X}. Although $\textsc{sharp}_\gamma$ is trivially non-negative, it suffers from the same issue as $\textsc{sdtw}_\gamma$, namely, $\textsc{sharp}_\gamma(C({\bm{X}}, {\bm{Y}}))$ is not minimized at ${\bm{X}} = {\bm{Y}}$. We therefore propose to use instead \begin{align} S_\gamma^C({\bm{X}}, {\bm{Y}}) \coloneqq ~ &\textsc{sharp}_\gamma(C({\bm{X}}, {\bm{Y}})) \\ -\frac{1}{2} &\textsc{sharp}_\gamma(C({\bm{X}}, {\bm{X}})) \\ -\frac{1}{2} &\textsc{sharp}_\gamma(C({\bm{Y}}, {\bm{Y}})). \end{align} We call it the sharp soft-DTW divergence. \paragraph{Validity.} We remind the reader that in mathematics, a \emph{divergence} $D$ is a function that is non-negative ($D({\bm{X}},{\bm{Y}})\geq 0$ for any ${\bm{X}},{\bm{Y}}$) and that satisfies the identify of indiscernibles ($D({\bm{X}},{\bm{Y}})= 0$ if and only if ${\bm{X}}={\bm{Y}}$). By construction, we have $D_\gamma^C({\bm{X}}, {\bm{X}}) = 0$ and $S_\gamma^C({\bm{X}},{\bm{X}})=0$ for all ${\bm{X}} \in \RR^{m \times d}$. Moreover, the following result shows that $D_\gamma^C$ is a valid divergence, under some assumptions on the cost $C$. \begin{proposition}{Valid divergence.} \label{prop:non_negativity_log} Let $\gamma > 0$. If $C$ is the cost defined in \eqref{eq:log_cost} with $d \in \mathbb{N}$, or, if $C$ is the absolute value \eqref{eq:lap_cost} with $d=1$, then $D_\gamma^C({\bm{X}}, {\bm{Y}}) \ge 0$ for all ${\bm{X}} \in \RR^{m \times d}$ and ${\bm{Y}} \in \RR^{n \times d}$, and $D_\gamma^C({\bm{X}}, {\bm{Y}}) = 0$ if and only if ${\bm{X}}={\bm{Y}}$. Therefore, $D_\gamma^C$ is a valid divergence. \end{proposition} A proof is given in Appendix \ref{appendix:proof_nn_log_cost}. This implies that, for the costs \eqref{eq:log_cost} and \eqref{eq:lap_cost}, $D_\gamma^C({\bm{X}}, {\bm{Y}})$ is uniquely minimized at ${\bm{X}} = {\bm{Y}}$. The proof relies on the fact that the global alignment kernel \eqref{eq:ga_kernel} is positive definite under these costs. Unfortunately, since the positive definiteness of \eqref{eq:ga_kernel} under the squared Euclidean cost \eqref{eq:squared_euclidean} has not been proved or disproved, the same proof technique does not apply. Nevertheless, we can prove the following. \begin{proposition}{Stationary point under cost \eqref{eq:squared_euclidean}} If $C$ is the squared Euclidean cost \eqref{eq:squared_euclidean}, then ${\bm{X}} = {\bm{Y}}$ is a stationary point of $D_\gamma^C({\bm{X}}, {\bm{Y}})$ and $S_\gamma^C({\bm{X}},{\bm{Y}})$ w.r.t.\ ${\bm{X}} \in \RR^{n \times d}$ for all ${\bm{Y}} \in \RR^{n \times d}$. \label{prop:stationary_point} \end{proposition} A proof is given in Appendix \ref{appendix:proof_stationary_point}. Based on Proposition \ref{prop:stationary_point} and ample numerical evidence (cf. Appendix \ref{appendix:numerical_validation}), we conjecture that $D_\gamma^C({\bm{X}},{\bm{Y}})$ and $S_\gamma^C({\bm{X}}, {\bm{Y}})$ are also non-negative under the squared Euclidean cost. \vspace{-0.5em} \paragraph{Asymptotic behavior.} We now study the behavior of our divergences in the zero and infinite temperature limits, i.e., when $\gamma \to 0$ and $\gamma \to \infty$. As we saw, $\bm{E}_\gamma({\bm{C}})$ is the expected alignment matrix under the Gibbs distribution $\mathbb{P}_\gamma(\bm{A}; {\bm{C}})$. Let $A$ be a random alignment matrix \textit{uniformly} distributed over $\mathcal{A}(m,n)$, i.e., independent of the cost matrix ${\bm{C}}$. Replacing $\bm{E}_\gamma({\bm{C}})$ with $\mathbb{E}[A]$ in \eqref{eq:sharp}, we obtain the mean cost, the average of the cost along all possible paths, \begin{align} \text{\textsc{mean\_cost}}({\bm{C}}) &\coloneqq \langle \mathbb{E}[A], {\bm{C}} \rangle \\ &= \frac{1}{|\mathcal{A}(m,n)|} \sum_{\bm{A} \in \mathcal{A}(m,n)} \langle \bm{A}, {\bm{C}} \rangle. \label{eq:mean_cost} \end{align} We also define the mean-cost divergence, \begin{align} M^C({\bm{X}}, {\bm{Y}}) &\coloneqq \text{\textsc{mean\_cost}}(C({\bm{X}}, {\bm{Y}})) \\ &- \frac{1}{2} \text{\textsc{mean\_cost}}(C({\bm{X}}, {\bm{X}})) \\ &- \frac{1}{2} \text{\textsc{mean\_cost}}(C({\bm{Y}}, {\bm{Y}})). \end{align} It bears some similarity with energy distances \citep{baringhaus_2004,szekely_2004}, with the key difference that the probability distribution is over the alignments, not over the time series. We now show that our proposed divergences are all intimately related through their asymptotic behavior, and that $D_\gamma^C$ and $S_\gamma^C$ share the same limits to the right when $m=n$ but not when $m \neq n$. \begin{proposition}{Limits w.r.t.\ $\gamma$} For all ${\bm{C}} = C({\bm{X}}, {\bm{Y}}) \in \RR^{m \times n}$, $m=n$: \begin{equation} \text{\normalfont{dtw}}({\bm{C}}) \xleftarrow[0 \leftarrow \gamma]{} D_\gamma^C({\bm{X}}, {\bm{Y}}) \xrightarrow[\gamma \to \infty]{} M^C({\bm{X}}, {\bm{Y}}). \end{equation} For all ${\bm{C}} = C({\bm{X}}, {\bm{Y}}) \in \RR^{m \times n}$, $m \neq n$: \begin{equation} \text{\normalfont{dtw}}({\bm{C}}) \xleftarrow[0 \leftarrow \gamma]{} D_\gamma^C({\bm{X}}, {\bm{Y}}) \xrightarrow[\gamma \to \infty]{} \infty. \end{equation} For all ${\bm{C}} = C({\bm{X}}, {\bm{Y}}) \in \RR^{m \times n}$: \begin{equation} \text{\normalfont{dtw}}({\bm{C}}) \xleftarrow[0 \leftarrow \gamma]{} S_\gamma^C({\bm{X}}, {\bm{Y}}) \xrightarrow[\gamma \to \infty]{} M^C({\bm{X}}, {\bm{Y}}). \end{equation} \label{prop:limits} \end{proposition} Note that the mean-cost divergence was obtained mostly as a side product of our limit case analysis. As we show in our experiments, it performs worse than the (sharp) soft-DTW divergence in practice. Therefore we do not recommend it in practice. \begin{figure*}[t] \centering \includegraphics[width=0.98 \textwidth]{figures/barycenter_uWaveGestureLibrary_Y.pdf} \caption{Average of $10$ time series ${\bm{Y}}_1,\dots,{\bm{Y}}_{10}$, on the {\bf uWaveGestureLibrary\_Y} dataset.} \label{fig:barycenter_main} \end{figure*} \paragraph{Computation.} The value, gradient, directional derivative and Hessian product of $\textsc{sdtw}_\gamma({\bm{C}})$ for ${\bm{C}} \in \RR^{m \times n}$ can all be computed in $O(mn)$ time \citep{soft_dtw,diff_dp}. Therefore, both $D_\gamma^C({\bm{X}}, {\bm{Y}})$ and $S_\gamma^C({\bm{X}}, {\bm{Y}})$ take $O(\max\{m,n\}^2)$ time to compute. Sharp divergences take roughly twice more time to compute, as computing a Hessian-vector product requires one more pass through the dynamic programming recursion. The mean alignment and mean cost can also both be computed in $O(mn)$ time. We detail all algorithms in Appendix \ref{appendix:algorithms}. \paragraph{Comparison with Sinkhorn divergences.} Since our proposed divergences use similar correction terms as Sinkhorn divergences, we briefly review them and discuss their differences. Given two input probability measures $\bm{\alpha} \in \triangle^m$ and $\bm{\beta} \in \triangle^n$, entropy-regularized optimal transport is now commonly defined as \begin{equation} \textsc{OT}_\gamma(\bm{\alpha}, \bm{\beta}) \coloneqq \min_{\bm{T} \in \mathcal{U}(\bm{\alpha}, \bm{\beta})} \langle \bm{T}, {\bm{C}} \rangle + \gamma \text{KL}(\bm{T} || \bm{\alpha} \otimes \bm{\beta}), \label{eq:ot_kl} \end{equation} where $\text{KL}$ is the Kullback-Leibler divergence and $\mathcal{U}(\bm{\alpha}, \bm{\beta})$ is the so-called transportation polytope \citep{peyre_2019}. To address the entropic bias of $\textsc{OT}_\gamma$, Sinkhorn divergences include correction terms, i.e., they are defined as $(\bm{\alpha}, \bm{\beta}) \mapsto \textsc{OT}_\gamma(\bm{\alpha}, \bm{\beta}) - \frac{1}{2} \textsc{OT}_\gamma(\bm{\alpha}, \bm{\alpha}) - \frac{1}{2} \textsc{OT}_\gamma(\bm{\beta}, \bm{\beta})$. There are however two important differences between $\textsc{OT}_\gamma$ and $\textsc{sdtw}_\gamma(C(\cdot, \cdot))$. First, the former is convex in its inputs (separately) while the latter is not. This means that the proof technique for non-negativity of Sinkhorn divergences \citep{feydy_2019} does not apply to the soft-DTW divergence. Indeed our proof technique for Proposition \ref{prop:non_negativity_log} is completely different than for Sinkhorn divergences. Second, the entropic regularization in $\textsc{sdtw}_\gamma$ is on the probability distribution (Proposition \ref{table:properties}), not on the soft alignment, as is the case for the transportation map $\bm{T}$ in \eqref{eq:ot_kl}. Contrary to Sinkhorn divergences, the soft-DTW and sharp divergences are non-convex in their inputs. For time-series averaging, an initialization scheme that works well in practice is to use the $\textsc{sdtw}_\gamma$ solution as initialization, itself initialized from the Euclidean mean. \section{Experimental results} \label{sec:exp} Throughout this section, we use the UCR (University of California, Riverside) time series classification archive \citep{UCRArchive}. We use a subset containing 84 datasets encompassing a wide variety of fields (astronomy, geology, medical imaging) and lengths. Datasets include class information (up to 60 classes) for each time series and are split into train and test sets. Due to the large number of datasets in the UCR archive, we choose to report only a summary of our results in the main manuscript. Detailed results are included in the appendix for interested readers. In all experiments, we use the squared Euclidean cost~\eqref{eq:squared_euclidean}. Our Python source code is available on \href{https://github.com/google-research/soft-dtw-divergences}{github}. \subsection{Time series averaging} \paragraph{Experimental setup.} To investigate the effect of our divergences on time series averaging, we replace $\textsc{sdtw}_\gamma$ in objective \eqref{eq:barycenter_obj} with our divergences. For this task, we focus on a visual comparison and refrain from reporting quantitative results, since the choice of evaluation metric necessarily favors one divergence over others. For each dataset, we pick $10$ time series ${\bm{Y}}_1,\dots,{\bm{Y}}_{10}$ randomly. Since the time series all have the same length, we use uniform weights $w_1 = \dots = w_k = 1$. To approximately minimize the objective function, we use $200$ iterations of L-BFGS \citep{lbfgs}. Because the objective is non-convex in ${\bm{X}}$, initialization is important. For $\text{\normalfont{dtw}}$, $\textsc{sdtw}_\gamma$, $\textsc{sharp}_\gamma$ and $\text{\textsc{mean\_cost}}$, we use the Euclidean mean as initialization and set $\gamma=1$. For $D_\gamma^C$, $S_\gamma^C$ and $M^C$, we use as initialization the solution of their ``biased couterpart'', i.e., $\textsc{sdtw}_\gamma$, $\textsc{sharp}_\gamma$, $\text{\textsc{mean\_cost}}$, respectively, and we set $\gamma=10$. \begin{figure*}[t] \centering \includegraphics[width=0.98 \textwidth]{figures/interpolation_ArrowHead.pdf} \caption{Interpolation between two time series ${\bm{Y}}_1$ (red) and ${\bm{Y}}_2$ (dark green), from the {\bf ArrowHead} dataset.} \label{fig:interpolation_main} \end{figure*} \paragraph{Results.} We show the time series averages obtained on the \textit{uWaveGestureLibrary\_Y} dataset in Figure \ref{fig:barycenter_main}. With DTW, the obtained average does not match well the time series, confirming the conclusion of \citet{soft_dtw}. This is because the objective is both highly non-convex and non-smooth, rendering optimization difficult, despite the use of Euclidean mean as initialization. On the other hand, the averages obtained by other divergences appear to match the time series much better, thanks to the smoothness of their objective function. We observe that $D_\gamma^C$ (soft-DTW divergence), $S_\gamma^C$ (sharp divergence) and $M^C$ (mean-cost divergence) produce different results from their biased counterpart, $\textsc{sdtw}_\gamma$ (soft-DTW), $\textsc{sharp}_\gamma$ (sharp soft-DTW) and $\text{\textsc{mean\_cost}}$ (mean cost), respectively. This is to be expected, since the variable ${\bm{X}}$ with respect to which we minimize is involved in the correcting term using $C({\bm{X}}, {\bm{X}})$. The averages obtained with $\textsc{sharp}_\gamma$ and $S_\gamma^C$ tend to include sharper peaks, a trend confirmed on other datasets as well. More average examples are included in the appendix. \subsection{Time series interpolation} \paragraph{Experimental setup.} As a simple variation of time series averaging, we now consider time series interpolation. We pick two times series ${\bm{Y}}_1$ and ${\bm{Y}}_2$ and set the weights in objective \eqref{eq:barycenter_obj} to $w_1 = \pi$ and $w_2 = 1 - \pi$, for $\pi \in \{0.25, 0.5, 0.75\}$, i.e., we seek an interpolation of the two time series. We again minimize the objective approximately using L-BFGS, with the same initialization scheme and the same $\gamma$ as before. \paragraph{Results.} Results on the \textit{ArrowHead} dataset are shown in Figure \ref{fig:interpolation_main}. We observe similar trends as for time series averaging. The interpolations obtained by DTW include artifacts that do not represent well the data. Our divergences obtain slightly more visually pleasing results than their biased counterparts. More examples are included in the appendix. The interpolation obtained by the sharp soft-DTW includes a peak (light green) which is slightly off, but this is not the case of the sharp divergence. \subsection{Time series classification} \paragraph{Experimental setup.} To quantitatively compare our proposed divergences, we now consider time series classification tasks. To better isolate the effect of the divergence itself, we choose two simple classifiers: nearest neighbor and nearest centroid. To predict the class of a time series, the well-known nearest neighbor classifier assigns the class of the nearest time series in the training set, according to the chosen divergence. Note that this does not require differentiability of the divergence. The lesser known nearest centroid classifier \citep{ESLII} first computes the centroid (average) of each class in the training set. We compute the centroid by minimizing \eqref{eq:barycenter_obj} for each class, according to the chosen divergence. To predict the class of a time series, we then assign the class of the nearest centroid, according to the same divergence. Although very simple, this method is known to be competitive with the nearest neighbor classifier, while requiring much lower computational cost at prediction time \citep{petitjean_icdm}. For all datasets in the UCR archive, we use the pre-defined test set. For divergences including a $\gamma$ parameter, we select $\gamma$ by cross-validation. More precisely, we train on $2/3$ of the training set and evaluate the goodness of a $\gamma$ value on the held-out $1/3$. We repeat this procedure $5$ times, each with a different random split, in order to get a better estimate of the goodness of $\gamma$. We do so for $\gamma \in \{10^{-4}, 10^{-3}, \dots, 10^{4}\}$ and select the best one. Finally, we retrain on the entire training set using that $\gamma$ value. \paragraph{Results.} Due to the large number of datasets in the UCR archive, we only show a summary of the results in Table \ref{table:summary_1nn} and Table \ref{table:summary_nearest_centroid}. Detailed results are in Appendix \ref{appendix:exp}. We observe consistent trends for both the nearest neighbor and the nearest centroid classifiers. The mean-cost divergence appears to perform poorly, even worse than the squared Euclidean distance and DTW. This shows that considering all possible alignments uniformly does not lead to a good divergence measure. On the other hand, our proposed divergences, the soft-DTW divergence and the sharp divergence, outperform on the majority of the datasets the Euclidean distance, DTW, soft-DTW, and sharp soft-DTW. Furthermore, each proposed divergence (i.e., with correction term) clearly outperforms its biased counterpart (i.e., without correction term). This shows that proper divergences, which are minimized when the two time series are equal, indeed translate to higher classification accuracy in practice. Overall, the soft-DTW divergence works better than the sharp divergence. \begin{table*}[t] \caption{{\bf Nearest neighbor results.} Each number indicates the percentage of datasets in the UCR archive for which using $A$ in the nearest neighbor classifier is within $99\%$ or better than using $B$ .} \centering \vspace{0.3em} \begin{tabular}{lcccccccc} \toprule $A$ ($\downarrow$) vs. $B$ ($\rightarrow$) & Euc. & DTW & SDTW & SDTW div & Sharp & Sharp div & Mean cost & Mean-cost div \\[0.3em] \midrule Euclidean & - & 41.67 & 34.62 & 22.37 & 29.49 & 27.63 & 95.29 & 71.43 \\[0.3em] DTW & 71.43 & - & 42.31 & 39.47 & 50.00 & 39.47 & 89.29 & 79.76 \\[0.3em] SDTW & 75.64 & 82.05 & - & 52.63 & 73.08 & 55.26 & 97.44 & 80.77 \\[0.3em] SDTW div & 93.42 & 93.42 & 86.84 & - & 84.21 & 82.67 & 97.37 & 96.05 \\[0.3em] Sharp & 83.33 & 84.62 & 76.92 & 53.95 & - & 52.63 & 98.72 & 87.18 \\[0.3em] Sharp div & 94.74 & 86.84 & 77.63 & 66.67 & 81.58 & - & 98.68 & 96.05 \\[0.3em] Mean cost & 9.41 & 13.10 & 8.97 & 5.26 & 5.13 & 6.58 & - & 44.05 \\[0.3em] Mean-cost div & 42.86 & 32.14 & 25.64 & 19.74 & 21.79 & 18.42 & 98.81 & - \\[0.3em] \hline \end{tabular} \label{table:summary_1nn} \end{table*} \begin{table*}[t] \caption{{\bf Nearest centroid results.} Each number indicates the percentage of datasets in the UCR archive for which using $A$ in the nearest neighbor classifier is within $99\%$ or better than using $B$ .} \centering \vspace{0.3em} \begin{tabular}{lcccccccc} \toprule $A$ ($\downarrow$) vs. $B$ ($\rightarrow$) & Euc. & DTW & SDTW & SDTW div & Sharp & Sharp div & Mean cost & Mean-cost div \\[0.3em] \midrule Euclidean & - & 44.71 & 27.06 & 28.57 & 30.95 & 32.50 & 77.65 & 78.82 \\[0.3em] DTW & 63.53 & - & 36.47 & 36.90 & 41.67 & 37.50 & 83.53 & 80.00 \\[0.3em] SDTW & 82.35 & 85.88 & - & 55.95 & 77.38 & 62.50 & 94.12 & 94.12 \\[0.3em] SDTW div & 82.14 & 83.33 & 82.14 & - & 78.57 & 70.00 & 91.67 & 94.05 \\[0.3em] Sharp & 79.76 & 78.57 & 54.76 & 48.81 & - & 55.00 & 91.67 & 91.67 \\[0.3em] Sharp div & 82.50 & 82.50 & 70.00 & 63.75 & 78.75 & - & 92.50 & 93.75 \\[0.3em] Mean cost & 37.65 & 22.35 & 11.76 & 11.90 & 15.48 & 11.25 & - & 77.65 \\[0.3em] Mean-cost div & 41.18 & 23.53 & 14.12 & 14.29 & 17.86 & 15.00 & 90.59 & - \\[0.3em] \hline \end{tabular} \label{table:summary_nearest_centroid} \end{table*} \section{Conclusion} Due to entropic bias, soft-DTW can be negative and is not minimized when the two time series are equal. To address these issues, we proposed the soft-DTW divergence and its sharp variant. We proved that the former is a valid divergence under the cost \eqref{eq:log_cost} for $d \in \mathbb{N}$ and under the absolute cost \eqref{eq:lap_cost} for $d=1$. We conjecture that this is also true under the squared Euclidean cost \eqref{eq:squared_euclidean}, but leave a proof to future work. By studying the limit behavior of our divergences when the regularization parameter $\gamma$ goes to infinity, we also obtained a new mean-cost divergence, which is of independent interest. Experiments on $84$ time series classification datasets established that the soft-DTW divergence performs the best among all discrepancies and divergences considered. \input{paper.bbl} \onecolumn
{'timestamp': '2021-03-01T02:05:15', 'yymm': '2010', 'arxiv_id': '2010.08354', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08354'}
arxiv
\section{Introduction and background} \label{section_introduction} Word embeddings, continuous vectorial representations of words, have become a fundamental initial step in many natural language processing (NLP) tasks for many languages. In recent years, their cross-lingual counterpart, cross-lingual word embeddings (CLWE) ---maps of matching words across languages--- have been shown to be useful in many important cross-lingual transfer and modeling tasks such as machine translation, cross-lingual document classification and zero-shot dependency parsing \cite{klementiev2012inducingcrosslingual, zou2013bilingualword, guo2015crosslingualdependency, conneau2018wordtranslation, glavas2019howto, mozhi2020whyoverfitting}. In these representations, matching words across different languages are represented by similar vectors. Following the observation of \citet{mikolov2013efficientestimation} that the geometric positions of similar words in two embedding spaces of different languages appear to be related by a linear relation, the most common method aims to map between two pretrained monolingual embedding spaces by learning a single linear transformation matrix. Due to its simple structure design and competitive performance, this approach has become the mainstream of learning CLWE \cite{glavas2019howto, vulic2019dowe, ruder2019asurvey}. Initially, the linear mapping was learned by minimizing the distances between the source and target words in a seed dictionary. Early work from \citet{mikolov2013efficientestimation} uses a seed dictionary of five-thousand word pairs. Since then, the size of the seed dictionary has been gradually reduced, from several-thousand to fifty word pairs \cite{smith2017offlinebilingual}, reaching a minimal version of only sharing numerals \cite{artetxe2017learningbilingual}. More recent works on unsupervised learning have shown that mappings across embedding spaces can also be learned without any bilingual evidence \cite{barone2016towardscrosslingual, zhang2017adversarialtraining, conneau2018wordtranslation, hoshen2018aniterative, alvarezmelis2018gromovwassersteinalignment, artetxe2018arobust}. More concretely, these fully unsupervised methods usually consist of two main steps \cite{hartmann2019comparingunsupervised}: an unsupervised step which aims to induce the seed dictionary by matching the source and target distributions, and then a pseudo-supervised refinement step based on this seed dictionary. The system proposed by \citet{conneau2018wordtranslation} can be considered the first successful unsupervised system for learning CLWE. They first use generative adversarial networks (GANs) to learn a single linear mapping to induce the seed dictionary, followed by the Procrustes Analysis \cite{Schoneman1966ageneralized} to refine the linear mapping based on the induced seed dictionary. While this GAN-based model has competitive or even better performance compared to supervised methods on typologically-similar language pairs, it often exhibits poor performance on typologically-distant language pairs, pairs of languages that differ drastically in word forms, morphology, word order and other properties that determine how similar the lexicon of a language is. More specifically, their initial linear mapping often fails to induce the seed dictionary for distant language pairs \cite{vulic2019dowe}. Later work from \citet{artetxe2018arobust} has proposed an unsupervised self-learning framework to make the unsupervised CLWE learning more robust. Their system uses similarity distribution matching to induce the seed dictionary and stochastic dictionary induction to refine the mapping iteratively. The final CLWE learned by their system performs better than the GAN-based system. However, their advantage appears to come from the iterative refinement with stochastic dictionary induction, according to \citet{hartmann2019comparingunsupervised}. If we only consider the performance of a model induced only with distribution matching, GAN-based models perform much better. This brings us to our first conclusions, that a GAN-based model is preferable for seed dictionary induction. Fully unsupervised mapping-based methods to learn CLWE rely on the strong assumption that monolingual word embedding spaces are isomorphic or near-isomorphic, but this assumption is not fulfilled in practice, especially for distant language pairs \cite{sogaard2018onthe}. Experiments by \citet{vulic2020areall} also demonstrate that the lack of isomorphism does not arise only because of the typological distance among languages, but it also depends on the quality of the monolingual embedding space. If we replace the seed dictionary learned by an unsupervised distribution matching method with a pretrained dictionary, keeping constant the refinement technique, the final system becomes more robust \cite{vulic2019dowe}. All these previous results indicate that learning a better seed dictionary is a crucial step to improve unsupervised cross-lingual word embedding induction and reduce the gap between unsupervised methods and supervised methods, and that GAN-based methods hold the most promise to achieve this goal. The results also indicate that a solution that can handle the full complexity of induction of cross-lingual word embeddings will show improvements in both close and distant languages. In this paper, we focus on improving the initial step of distribution matching, using GANs \cite{hartmann2019comparingunsupervised}. Because the isomorphism assumption is not observed in reality, we argue that a successful GAN-based model must not learn only one single linear mapping for the entire distribution, but must be able to identify mapping subspaces and learn multiple mappings. We propose a multi-adversarial learning method which learns different linear maps for different subspaces of word embeddings. \section{Limitations of single-linear mappings} \begin{figure} \centering \includegraphics[scale=0.26]{figure_translation_accuracy_per_cluster.png} \caption{Translation accuracy from English to Chinese and to French for different English subspaces. We only include the top fifty-thousand most frequent English words in the pretrained fastText embeddings. The gold translations comes from Google Translate.} \label{figure_translation_accuracy_per_cluster} \end{figure} If the assumption by \citet{mikolov2013efficientestimation} that similar words across source and target languages are related by a single linear relation holds exactly or even approximately , the distance between source and target embedding spaces should be (nearly) evenly minimized during the training of the initial mapping. More specifically, each source subspace should be mapped (nearly) equally well to its corresponding target space, so that the translation ability of the single linear mapping should be similar across different source subspaces. To verify this expectation, we use the GAN-based system MUSE\footnote{https://github.com/facebookresearch/MUSE} to train two linear mappings (without refinement) \citep{conneau2018wordtranslation}. One mapping relates two typologically distant languages, English and Chinese, and the other maps the English space to the space of French - a typologically similar language. We use pretrained FastText embeddings.\footnote{https://fasttext.cc/docs/en/pretrained-vectors.html} We split the English space into ten subspaces by running $k$-means clustering. We evaluate the trained linear mappings by calculating the translation accuracy with precision at one (P@1) ---how often the highest ranked translation is the correct one--- for each subspace, using the translations from Google Translate as the gold dataset. To reduce the influence of infrequent words, we only consider the first fifty-thousand most frequent source words. As we can see in Figure \ref{figure_translation_accuracy_per_cluster}, the distribution of accuracies of different subspaces is not uniform or even nearly so. This is true for both language pairs, but particularly for the distant languages, where the general mapping does not work at all in some subspaces. Similar phenomena were also discovered by \citet{nadapa2018normaneighborhood} where source words are grouped into different categories. This lack of uniformity in results corroborates the appropriateness of designing a model that learns different linear mappings for different subspaces instead of only learning a single linear mapping for the entire source space. \section{Multi-adversarial CLWE learning} \label{section_learning_multi-linear_mapping_through_distribution_matching} To learn different mappings for different source subspaces, we propose a method for training one GAN for each source subspace. These multi-discriminator GANs encourage the distribution of mapped word embeddings from a specific source subspace to match the distribution of word embeddings from the corresponding target subspace. The first step of our proposed method is to train a single linear mapping, as in previous approaches. This is used to find aligned subspaces. Our proposed multi-discriminator GAN model then learns the multi-linear mapping. This section starts with the two GAN models, followed by the subspace alignment method, and then describes methods used to improve the GAN training. \subsection{Unsupervised CLWE learning} \label{section_unsupervised_clwe_learning} We first define the task of learning CLWEs and the role of GANs in the previous work of \citet{conneau2018wordtranslation}. Let two monolingual word embeddings $V_s^j=\{v_{s_{_1}}, ..., v_{s_{_j}}\}$ and $V_t^k=\{v_{t_{_1}}, ..., v_{t_{_k}}\}$ be given. In previous work, mapping $V_s^j$ to $V_t^k$ means seeking a linear transformation matrix $W$, so that the projected vector $Wv_i$ of a source word is close to the vector of its translation in the target language. The basic idea underlying supervised methods is using a seed dictionary of $n$ word pairs $\{(w_{s_{_1}}, w_{t_{_1}}), ..., (w_{s_{_n}}, w_{t_{_n}})\}$ to learn the matrix $W$ by minimizing the distance in (\ref{equation_mapping_mikolov}), where $v_{s_{_i}}$ and $v_{t_{_i}}$ represent the embeddings of $w_{s_{_i}}$ and $w_{t_{_i}}$. The trained matrix $W$ can then be used to map the source word embeddings to the target space. \begin{equation} \label{equation_mapping_mikolov} \min_{W}\sum_{i=1}^{n}\| Wv_{s_{_i}} - v_{t_{_i}} \|^{2} \end{equation} In an unsupervised setting, the seed dictionary is not provided. \citet{conneau2018wordtranslation} propose a two-step system where the seed dictionary is learned in an unsupervised fashion. In a first step, they use GANs to learn an initial linear transformation matrix $W$ and use this to induce a seed dictionary by finding the translations of the first ten-thousand most frequent source words. In a second step, the seed dictionary is used to refine the initial matrix $W$. In this work we focus on the GAN component of this model. \subsection{GAN learning of a single linear mapping} \label{section_single_linear_mapping} Previous GAN-based systems learn a single linear mapping from the source embedding space to the target embedding space. In such models, a source word is trained against a target word sampled from the whole target distribution, and the resulting single linear mapping is applied to all the source words. We first introduce the basic GAN architecture for CLWE of \citet{conneau2018wordtranslation}. We use this model as our comparative baseline and as the initial stage of our proposed method. A standard GAN model plays a min-max game between a generator $G$ and a discriminator $D$ \citep{goodfellow2014generativeadversarial}. The generator learns from the distribution of source data and tries to fool the discriminator by generating new samples which are similar to the target data. When we adapt the basic GAN model to learning CLWE, the goal of the generator is to learn the linear mapping matrix $W$. The discriminator $D$ detects whether the input is from the distribution of target embeddings $p_{v_t}$. \citet{conneau2018wordtranslation} use the loss functions in (\ref{equation_discriminator_loss}) and (\ref{equation_generator_loss}) to update the discriminator and the generator, respectively. $G(v_s) = Wv_s$, and $D(v)$ denotes the probability that the input vector $v$ came from the target distribution $p_{v_{t}}$ rather than the generator applied to samples from the source distribution $p_{v_{s}}$. \begin{align} \label{equation_discriminator_loss} l_D &= -\log D(v_t) - \log (1 - D(G(v_s))) \\ \label{equation_generator_loss} l_G &= -\log D(G(v_s)) - \log(1 - D(v_t)) \end{align} The parameters of both generator and discriminator are updated alternatively by using stochastic gradient descent. However, a number of additional methods are needed for robust reliable training of such GANs, which are discussed in Section~\ref{section_training}. \begin{figure} \centering \includegraphics[width=\columnwidth]{multi_discriminator_mapping.png} \caption{Architecture of our multi-discriminator model. The generator $G^i$ for each source subspace $V^i_s$ is trained against the discriminator $D^i_s$ for the aligned subspace $V^i_t$ and a whole-language discriminator $D^i_l$. } \label{figure_multi_discriminator_mapping} \end{figure} \subsection{GAN learning of a multi-linear mapping} \label{section_multi_linear_mapping} Unlike previous work, we propose learning different linear mappings for different source subspaces. We propose a multi-discriminator GAN where a source word from one subspace is trained against a target word sampled from the aligned target subspace. For each subspace of source embeddings, we propose a multi-discriminator adversarial model to train the specific mapping for vectors that belong to this subspace. As the architecture in Figure~\ref{figure_multi_discriminator_mapping} illustrates, the generator of the given source subspace $i$ takes the vector sampled from the sub-distribution as input and maps it to the target language. Differently from standard GANs, the mapped vector $G^i(v^i_s){=}W^iv^i_s$ will be fed into two discriminators. First, a subspace-specific discriminator $D^i_s$ judges whether the vector has come from the correspondent target subspace $i$. Thus, we use the vectors sampled from both source and target subspaces to train $D^i_s$. Second, a normal language discriminator $D^i_l$ judges whether the vector has come from the whole target distribution. This language discriminator helps avoid local optima for the specific subspace. Both discriminators are two-layer perceptron classifiers. Except for the different sampling ranges, their loss function is similar to equations \eqref{equation_discriminator_loss} and \eqref{equation_generator_loss}: \begin{align} \label{equation_language_discriminator_loss} l_{D^i_l} &= -\log D(v'_t) - \log (1 - D(G(v'_s))) \\ \label{equation_subspace_discriminator_loss} l_{D^i_s} &= -\log D(v^i_t) - \log (1 - D(G(v^i_s))) \end{align} where $v'_s$ and $v'_t$ are sampled from the 75-thousand most frequent source and target words,\footnote{We use different language discriminator models $D^i_l$ for each subspace $i$, even though their training samples all come from the same distributions. This leads to more stable training, presumably because initially these language discriminators are randomly different.} and $v^i_s$ and $v^i_t$ are sampled from the specific source subspace $V^i_s$ and its corresponding target subspace $V^i_t$. Since the outputs of both discriminators are used for training the generator, the loss function of the subspace-specific generator $G^i$ can be written as: \begin{equation} \label{equation_subspace_specific_generator_loss} \begin{split} &l_{G^i} = -\lambda (\log D^i_l(G^i(v^i_s)) + \log(1 - D^i_l(v'_t)))\\ &- (1-\lambda)(\log D^i_s(G^i(v^i_s)) + \log(1 - D^i_s(v^i_t))) \end{split} \end{equation} where $\lambda$ is a coefficient that we call global confidence, which balances the contributions of the two discriminators in updating the generator. In practice, we find that setting $\lambda$ to 0.5 for each subspace works well for the final result. Additionally, as the similarities between the entire distribution and the distribution of different subspaces are different, it is justified to use different lambdas for different subspaces instead of using a single one. We therefore propose a metric to set $\lambda$ dynamically, based on the proportion of the eigenvalue divergence between the two subspaces and the eigenvalue divergence between the whole source and target distributions, as shown in (\ref{equation_lambda}). In this paper, we only report results with dynamic $\lambda$. \begin{equation} \label{equation_lambda} \begin{split} \lambda = \frac{EV\!D(V^i_s, V^i_t)}{EV\!D(V_s, V_t)} \end{split} \end{equation} The eigenvalue divergence between two embedding distributions $V_1$ and $V_2$ can be computed as shown in (\ref{equation_evd}), where $e^{V_1}_k$ and $e^{V_2}_k$ represent the eigenvalues of $V_1$ and $V_2$. \begin{equation} \label{equation_evd} \begin{split} EV\!D(V_1, V_2) = \sum_{k=1}^{d}(\log e^{V_1}_k - \log e^{V_2}_k)^2 \end{split} \end{equation} All subspace-specific generators are initialized with the single linear mapping discussed in Section~\ref{section_single_linear_mapping}. \subsection{Subspace alignment} The above multi-discriminator GAN assumes that we have an alignment between source subspaces and target subspaces. We first present the method we use to produce aligned subspaces in both source and target distributions, and then the clustering method we use to find coherent subspaces, which are both important for the model's improved performance. If we want to encourage words from a specific source subspace to be trained against words from a matching target subspace, we need to align the two cross-language subspaces. The second problem we need to solve for our multi-adversarial method to work is how to discover this alignment. Although metrics such as Gromov-Hausdorff distance (GH) \cite{patra2019bilinguallexicon} and Eigenvalue Divergence (EVD) \cite{dubossarsky2020lostin} can be used to measure the similarity between two distributions and find the most similar target subspace for a given source subspace, matching between two sub-distributions may amplify any bias generated during the clustering. To avoid this problem, we only run the clustering on the source side. For a given source embedding space $V_s$, we denote its subspaces after clustering as $\left \{ V^1_s, V^2_s, ..., V^i_s, ..., V^n_s \right \},$ where $n$ represent the number of subspaces. To align target words to their matching source subspace, we propose to first learn a single linear mapping from source to target space using the GAN-based method (without refinement) described previously, and then use the transpose of this linear mapping to retrieve the translation of each target word in the source language (using cross-domain similarity local scaling, defined below in Section~\ref{section_training}). The subspace index of the target word is then set to the subspace index of this translation. In this way, the target embedding space $V_t$ is partitioned into as many subspaces as the source embedding space, denoted as $\left \{ V^1_t, V^2_t, ..., V^i_t, ..., V^n_t \right \}$. This gives us aligned subspace pairs $(V^i_s, V^i_t)$. Although the single linear mapping from source language to target language is not good enough to get accurate translations, our experiments indicate that it is a good method to produce a subspace alignment. A possible reason for this result is that the clustering on the source language has already grouped similar words. Therefore, even if a translation turns out to be incorrect, it usually has the same subspace index as the best translation. \paragraph{Parameter-free hierarchical clustering} A major issue in clustering an embedding space is how to find a clustering that adapts to the space, without fixed parameters. To avoid having to identify the number of subspaces in advance, we use hierarchical clustering. Recent work proposes a parameter-free method called First Integer Neighbor Clustering Hierarchy (FINCH) \cite{sarfraz2019efficientparameterfree}, which we use in this paper. Traditionally, clustering methods split a given space of vectors into different clusters by calculating the distances between the centroid and the other vectors. FINCH is developed based on the observation that the first neighbour of each vector is a sufficient statistic to find links in the space, so that computing the distance matrix between all the vectors is not needed \cite{sarfraz2019efficientparameterfree}. For a given vector space, one first computes an adjacency link matrix using the equation in (\ref{equation_clustering}). \begin{equation} \label{equation_clustering} A(i, j) = \left\{\begin{matrix} 1 & i\!f~ j=\kappa^1_i ~or~ \kappa^1_j = i ~or~ \kappa^1_i=\kappa^1_j \\ 0 & otherwise \end{matrix}\right. \end{equation} where $i, j$ denote the indices of vectors and $\kappa^1_i$ represents the index of the first neighbour of the vector with index $i$. The connected components can then be detected from the adjacency matrix $A$ by building a directed or undirected graph on $A$. No parameter needs to be set. When the clustering on the original first level (original data) is completed, the centroid of each cluster can then be considered as a data vector for the next level and a new level of clustering is computed using the same procedure. In theory, all the vectors will eventually be gathered into a single cluster. In practice, we find that using the clusters of the last level or the second-to-last level works well for our system.\footnote{In the code of \citet{sarfraz2019efficientparameterfree}, the last level means the level before grouping all the data vectors into a single cluster.} \subsection{Training the GANs} \label{section_training} Training the GANs described in Sections~\ref{section_single_linear_mapping} and~\ref{section_multi_linear_mapping} can be challenging. Based on previous work and our experience, we employ the following techniques during training. \paragraph{Orthogonalization} Previous work shows that enforcing the mapping matrix $W$ to be orthogonal during the training can improve the performance \cite{smith2017offlinebilingual}. In the system of \citet{conneau2018wordtranslation}, they follow the work of \citet{cisse2017parsevalnetworks} and approximate setting $W$ to an orthogonal matrix with $W\leftarrow (1+\beta)W -\beta( WW^\top)W$. This orthogonalization usually performs well when setting $\beta$ to 0.001 \cite{conneau2018wordtranslation, wang2019weaklysupervised}. \paragraph{Cross-Domain Similarity Local Scaling} The trained mapping matrix $W$ can be used for retrieving the translation for a given source word $w_s$ by searching a target word $w_t$ whose embedding vector $v_t$ is close to $Wv_s$. But \citet{conneau2018wordtranslation} showed that using cross-domain similarity local scaling (CSLS) to retrieve translations is more accurate than standard nearest neighbor techniques and can reduce the impact of the hubs problem \cite{radovanovic2010hubsin, dinu2015Improvingzeroshot}. Instead of just considering the distance between $Wv_s$ and $v_t$, CSLS also takes into account the neighbours of $v_t$ in the source language by minimising $( 2\cos(Wv_s, v_t)-r_t(Wv_s)-r_s(v_t) )$, where $r_t(Wv_s)$ denotes the mean similarity between a $Wv_s$ and its neighbours in the target language, while $r_s(v_t)$ represents the mean similarity between $v_t$ and its neighbours in the source language. \paragraph{Model selection criterion} The cosine-based model selection criterion is another important component of adversarial training for selecting the best mapping matrix $W$. More specifically, at the end of each training epoch, the current mapping is used to translate the ten-thousand most frequent source words into target words and calculate the average cosine similarity between the source vectors and the target vectors. This cosine-based criterion has been shown to correlate well with the quality of $W$ \cite{conneau2018wordtranslation, hartmann2019comparingunsupervised}. \paragraph{Random restarts} Previous work \cite{vulic2019dowe,glavas2019howto} shows that using GANs to train the mapping matrix $W$ is not stable. \citet{hartmann2019comparingunsupervised} propose to solve this problem with the random restart technique. More specifically, before going to the step of refinement, they randomly train ten mapping matrices, choosing only the best model among them for the next step. The best model is selected with the unsupervised model selection criterion. Their experiments show that this model selection method has the best performance on bilingual lexicon induction. We follow \cite{vulic2019dowe,glavas2019howto} and apply the same random restart technique to train the single linear mapping and use it to initialize each subspace-specific generator. \section{CLWE mapping refinement } \label{section_refinement} As in previous work, after GANs have been used to find a mapping from source to target word embeddings, a refinement step can be used to improve this mapping. Refinement involves first inducing a seed dictionary of word translations, and then refining the mapping using this seed dictionary. \paragraph{Bidirectional seed dictionary induction} Using the mapping learned with adversarial training, the translations $(w_{t_{1}}, w_{t_{2}},..., w_{t_{10000}})$ for the top ten-thousand source words $(w_{s_{1}}, w_{s_{2}},..., w_{s_{10000}})$ are retrieved and then back-translated into the source language $(w'_{s_{1}}, w'_{s_{2}},..., w'_{s_{10000}})$. The mutual translation pairs $(w_{s_{i}}, w_{t_{i}}) $ such that $w_{s_{i}} = w'_{s_{i}}$ constitute the seed dictionary. This guarantees that the induced seed dictionary will be bidirectional. \paragraph{Mapping refinement} The refinement step is based on the Procrustes Analysis \cite{Schoneman1966ageneralized}. With the seed dictionary, the mapping can be updated using the objective in equation~\eqref{equation_mapping_mikolov}, and forced to be orthogonal using singular value decomposition (SVD) \cite{xing2015normalizedword}. Later work combines the Procrustes Analysis with stochastic dictionary induction \cite{artetxe2018arobust} and greatly improves the performance of the standard refinement \cite{hartmann2019comparingunsupervised}. More specifically, in order to prevent local optima, after each iteration some elements of the similarity matrix are randomly dropped, so that the similarity distributions of words change randomly and the new seed dictionary for the next iteration varies. \paragraph{Global and local refinement} Refinement can be applied to our multi-linear mapping in two different ways. First, after the training of all the subspace alignments, we can refine a linear relationship between the transformed source embeddings and the target embeddings, like previous unsupervised methods. This we call \textit{global refinement}. It is noteworthy that the combination of the multi-linear mapping trained by our multi-discriminator model and the refined single linear mapping is still multi-linear. Second, we can also refine the mapping of each subspace separately. More concretely, for a given subspace $(V^i_s,V^i_t)$, we build a local seed dictionary and use the local seed dictionary to update the mapping $G^i(v^i_s)$. We call this \textit{local refinement}. We evaluate both global and local refinement in the next section. \section{Experiments} \label{section_experiments} Bilingual lexicon induction (BLI) has become a standard task for evaluating CLWE models. However, according to \citet{glavas2019howto} and \citet{mozhi2020whyoverfitting}, BLI performance of a given CLWE model doesn't always correlate with performance in other cross-lingual downstream tasks. In this section, we evaluate our proposal on both the task of BLI and the task of cross-lingual document classification (CLDC). We evaluate our system both with and without refinement. Since GAN-based methods of learning CLWE are often criticized for their instability at inducing the seed dictionary, we report the average over 10 runs for the BLI without-refinement setting. We include the random restart technique for other tasks and report the result of the best model selected by the unsupervised model selection criterion. We evaluate our model both with global refinement (G-Ref) and local refinement (L-Ref). \vspace{-0.1cm} \paragraph{BLI setting} We use the dataset provided by \citet{conneau2018wordtranslation} for the task of BLI. This dataset contains high quality dictionaries for more than 150 language pairs. For each language pair, it provides a training dictionary of 5000 words and a test dictionary of 1500 words. This dataset allows us to have a better understanding of the performance of our proposal on many different language pairs. For each language pair, we retrieve the best translations of source words in the test dictionary using CSLS, and we report the accuracy with precision at one (P@1). \vspace{-0.1cm} \paragraph{CLDC setting} We use the multilingual classification benchmark (MLDoc) provided by \citet{schwenk2018acorpus} for the task of CLDC. MLDoc contains training and test documents with balanced class priors for eight languages: German (de), English (en), Spanish (es), French (fr), Italian (it), Japanese (ja), Russian (ru) and Chinese (zh). We follow previous works \cite{glavas2019howto, mozhi2020whyoverfitting} and train a CNN classifier on English using 10,000 documents and test the classifier on the other seven languages.\footnote{https://github.com/zhangmozhi/retrofit\_clwe} Each language contains 4000 test documents. The input of the classifier comes from the CLWE models. We report the average accuracy over ten runs. \vspace{-0.1cm} \paragraph{Language pairs} In this paper, we focus on projecting foreign language embeddings into the English space. We choose the eight languages included in MLDoc for both the BLI and CLDC tasks. Within the seven non-English languages, Japanese, Russian and Chinese are languages distant from English and the others are languages similar to English. For the task of BLI, we also investigate Turkish, another language distant from English. \vspace{-0.1cm} \paragraph{Monolingual word embeddings} We use the pretrained FastText embedding models \cite{bojanowski2017enrichingword} for our experiments. These embeddings of 300 dimensions are pretrained on Wikipedia dumps and publicly available.\footnote{https://fasttext.cc/docs/en/pretrained-vectors.html} Following previous works, we use the first 200,000 most frequent words for each monolingual embedding model.\footnote{The original pretrained Latvian fastText model only consists of 171,000 words.} We apply iterative normalization \cite{mozhi2019aregirls} on each embedding model before training. \vspace{-0.2cm} \begin{table} \setul{0.3ex}{0.7pt} \addtolength{\tabcolsep}{-0.6ex} \small \begin{tabular}{@{}lrrrrrrrr} \toprule \multicolumn{9}{c}{BLI Task - with refinement} \\ \midrule & \multicolumn{1}{c}{de} & \multicolumn{1}{c}{es} & \multicolumn{1}{c}{fr} & \multicolumn{1}{c}{it} & \multicolumn{1}{c}{ja} & \multicolumn{1}{c}{ru} & \multicolumn{1}{c}{tr} & \multicolumn{1}{c}{zh} \\ \midrule PROC & 73.1 & 83.6 & 82.2 & 77.5 & 37.9 & 64.3 & \ul{63.1} & 40.0 \\ RCSLS & 73.1 & 83.1 & \ul{83.1} & \ul{78.9} & \ul{39.3} & \ul{64.6} & 63.1 & \ul{43.0} \\ \midrule \midrule MUSE & 73.7 & 83.0 & 82.2 & 78.5 & 29.3 & 62.7 & 60.5 & 38.1 \\ VecMap & 73.6 & \textbf{\ul{83.7}} & \textbf{82.9} & 78.5 & \textbf{34.7} & 63.1 & \textbf{61.3} & 36.4 \\ \midrule Ours GRef & \textbf{\ul{74.1}} & \textbf{\ul{83.7}} & 82.4 & \textbf{78.6} & 34.1 & \textbf{64.0} & 61.2 & \textbf{38.2} \\ Ours LRef & 66.6 & 79.3 & 77.8 & 70.3 & 23.7 & 46.5 & 39.7 & 29.7 \\ \bottomrule \end{tabular}\caption{BLI task results with refinement. Bold shows the best score within unsupervised systems and underline shows the best score over all the systems.} \label{table_bli_results_with_refinement} \vspace{-0.3cm} \end{table} \begin{table} \addtolength{\tabcolsep}{-0.5ex} \centering \small \begin{tabular}{@{}lrrrrrrrr} \toprule \multicolumn{9}{c}{BLI Task - without refinement} \\ & \multicolumn{1}{c}{de} & \multicolumn{1}{c}{es} & \multicolumn{1}{c}{fr} & \multicolumn{1}{c}{it} & \multicolumn{1}{c}{ja} & \multicolumn{1}{c}{ru} & \multicolumn{1}{c}{tr} & \multicolumn{1}{c}{zh}\\\midrule & \multicolumn{8}{c}{Successful runs averages}\\ MUSE & 53.9 & 68.9 & 66.9 & \textbf{60.7}& 14.7 & \textbf{38.1} & 22.3 & 16.2 \\ VecMap & 0.0 & 0.0 & 0.0 & 0.0 & 0.0 & 0.0 & 0.0 & 0.0 \\ \midrule Ours & \textbf{55.5} & \textbf{69.3} & \textbf{67.3} & 59.3 & \textbf{18.3} & \textbf{38.1} & \textbf{28.4} & \textbf{19.1} \\ \midrule & \multicolumn{8}{c}{Failures} \\ MUSE & 3 & 1 & 0 & 1 & 5 & 5 & 4 & 9 \\ VecMap & 10 & 10 & 10& 10 & 10 & 10 & 10& 10\\ \midrule Ours & 1 & 1 & 0 & 0 & 5& 4& 4 & 8\\ \bottomrule \end{tabular} \caption{BLI task results for unsupervised models without refinement. We consider accuracy below 2\% as failure and report the average accuracy with P@1 over the successful runs. Bold represents the best score.} \label{table_bli_results_without_refinement} \vspace{-0.5cm} \end{table} \paragraph{Baselines} The objective of our proposal is to improve the mapping ability of GANs by learning a multi-linear mapping instead of only a single-linear mapping. Therefore, we use the GAN-based system MUSE \citep{conneau2018wordtranslation}\footnote{https://github.com/facebookresearch/MUSE} as our main unsupervised baseline. Since the unsupervised method proposed by \citet{artetxe2018arobust}\footnote{ https://github.com/artetxem/vecmap} is considered a robust CLWE system, we also use it as our second unsupervised baseline (VecMap in the tables). In the setting with refinement, we use the iterative refinement with stochastic dictionary induction for all the unsupervised systems.\footnote{We disabled the re-weighting technique since it's not applicable for L-Ref. However, adding re-weighting to VecMap, MUSE and G-Ref doesn't change the gaps between them.} We also include two supervised systems, Procrustes (PROC) \cite{conneau2018wordtranslation} and Relaxed CSLS (RCSLS) \cite{armand2018lossin}, to better understand our method. Both PROC and RCSLS are robust supervised systems for learning CLWE and have been widely used previously \cite{glavas2019howto, mozhi2020whyoverfitting}. We also wanted to include the supervised system proposed by \citet{nadapa2018normaneighborhood}, which learns multiple local mappings between embedding spaces, but their code is not publicly available. \subsection{Performance on BLI} We report the results of BLI both with and without refinement in Tables \ref{table_bli_results_with_refinement} and \ref{table_bli_results_without_refinement}, respectively. The results in Table \ref{table_bli_results_without_refinement} show a clear improvement from our multi-linear mapping, compared with single-linear GANs. We perform better than MUSE for both average accuracy and number of failures in almost every language pair. The advantages are more striking on distant language pairs. VecMap is considered the most robust unsupervised model for learning CLWE. However, according to \citet{hartmann2019comparingunsupervised}, the advantage of VecMap mostly comes from its refinement technique. From the results in Table \ref{table_bli_results_with_refinement}, we can see that when using the same refinement technique, our best model selected from ten random restarts using the unsupervised metric performs as well as VecMap or even better. Our model achieves higher scores on four language pairs and comes close for the other language pairs. The results shown in Table \ref{table_bli_results_with_refinement} demonstrate that our model is comparable with supervised systems when using iterative refinement with stochastic dictionary induction and random restarts. We even perform better than PROC and RCSLS on similar language paris such as German and Spanish to English (de-en and es-en). From the results in Table \ref{table_bli_results_with_refinement}, we can easily see that the global refinement outperforms local refinement. Using local refinement we even perform much worse than our GAN-based baseline. This phenomenon does not surprise us since local refinement can easily lead to overfitting on a given subspace, and we leave the investigation of alternative refinement methods to future work. \subsection{Performance on CLDC} We report the results on the task of CLDC without and with refinement in Tables \ref{table_cldc_results_without_refinement} and \ref{table_cldc_results_with_refinement}, respectively. From the results shown in Table \ref{table_cldc_results_without_refinement}, we can see that our multi-linear model continues to maintain its advantage over the single-linear GAN, MUSE, in the setting without refinement. When refinement is added, MUSE becomes a little better than our model on German and Spanish. However, we still perform better on all those languages that are distant from English. Differently from the task of BLI, there is no obvious advantage in the supervised baselines over our multi-linear model both with and without refinement. Conversely, as the results in Table \ref{table_cldc_results_without_refinement} indicate, our model without refinement performs comparably or better than either our supervised baselines or VecMap in the setting with refinement. For example, our model achieves 69.5 of accuracy on Chinese test data, while the best supervised model, PROC, only has 32.0 accuracy. While CLWE refinement is a necessary step for the BLI task, for the CLDC task our model does not seem to need refinement. As the performance gap illustrated in Figure \ref{figure_cldc_gap} shows, our model performs worse when adding refinement for languages such as French, Japanese, Russian and Chinese, which includes all the languages distant from English. Furthermore, even for languages where we benefit from refinement, the improvement is limited. \begin{table} \addtolength{\tabcolsep}{-0.6ex} \centering \begin{tabular}{@{}lrrrrrrrr} \toprule \multicolumn{8}{c}{~CLDC Task - without refinement} \\ \midrule & \multicolumn{1}{c}{de} & \multicolumn{1}{c}{es} & \multicolumn{1}{c}{fr} & \multicolumn{1}{c}{it} & \multicolumn{1}{c}{ja} & \multicolumn{1}{c}{ru} & \multicolumn{1}{c}{zh} \\ \midrule MUSE & 79.2 & \textbf{69.7} & 71.5 & 56.4 & 27.6 & 56.3 & 60.8 \\ VecMap & 21.4 & 24.6 & 23.1 & 23.7 & 21.2 & 23.6 & 22.3 \\ \hline Ours & \textbf{80.1} & 67.4 & \textbf{73.2} & \textbf{62.3} & \textbf{30.3} & \textbf{61.5} & \textbf{69.5} \\ \bottomrule \end{tabular} \caption{CLDC results on MLDoc dataset \cite{schwenk2018acorpus} without refinement. Bold represents the best score.} \label{table_cldc_results_without_refinement} \vspace{-0.3cm} \end{table} \begin{table} \setul{0.3ex}{0.7pt} \addtolength{\tabcolsep}{-0.75ex} \centering \begin{tabular}{@{}lrrrrrrrr} \toprule \multicolumn{8}{c}{CLDC Task - with refinement} \\ \midrule & \multicolumn{1}{c}{de} & \multicolumn{1}{c}{es} & \multicolumn{1}{c}{fr} & \multicolumn{1}{c}{it} & \multicolumn{1}{c}{ja} & \multicolumn{1}{c}{ru} & \multicolumn{1}{c}{zh} \\ \midrule PROC & 81.4 & 69.6 & 70.7 & 62.9 & 30.0 & \ul{64.9} & 32.0 \\ RCSLS & 81.6 & \ul{70.5} & \ul{71.1} & 62.4 & 29.7 & 64.3 & 31.8 \\ \midrule \midrule MUSE & 80.9 & 69.4 & 70.6 & 59.9 & 28.9 & 61.1 & 45.6 \\ VecMap & \textbf{\ul{81.8}} & 69.8 & \textbf{71.0} & \textbf{\ul{64.0}} & 28.4 & 63.2 & 35.4 \\ \midrule Ours G-Ref & 80.7 & 69.2 & 70.9 & 62.6 & \textbf{\ul{30.2}} & 61.3 & 55.9 \\ Ours L-Ref & 79.5 & 69.1 & 69.9 & 62.6 & 30.1 & 62.9 & \textbf{\ul{59.9}} \\ \bottomrule \end{tabular} \caption{CLDC results on MLDoc dataset \cite{schwenk2018acorpus} with refinement. Bold shows the best score within unsupervised systems and underline shows the best score over all the systems.} \label{table_cldc_results_with_refinement} \vspace{-0.3cm} \end{table} \begin{figure} \centering \includegraphics[scale=0.62]{cldc_gap.png} \caption{Performance gap on the CLDC task. The left panel represents the gap between our multi-linear model with refinement and without refinement. The right panel represents the performance gap between our model without refinement and the best baseline (best results selected from our supervised and unsupervised baselines). Blue bars indicate the cases where the model without refinement performs better than its competitors. Yellow bars represent the opposite cases.} \label{figure_cldc_gap} \end{figure} \section{Conclusion} In this paper, we propose a multi-adversarial learning method for cross-lingual word embeddings. Our system learns different linear mappings for different source subspaces instead of just learning a single one for the whole source space. The results of our experiments on bilingual lexicon induction and cross-lingual document classification on both close languages and distant languages prove that learning cross-lingual word embeddings with a multi-linear mapping improves performance over a single-linear mapping. Future work will focus on learning multi-linear mappings for contextualized embeddings.
{'timestamp': '2021-08-27T02:05:03', 'yymm': '2010', 'arxiv_id': '2010.08432', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08432'}
arxiv
\section{Online Stochastic Policy Gradient}\label{sec_algorithm} In order to compute a stochastic approximation of $\nabla_h U_{s_0}(h)$ we need to sample from $\rho_{s_0}(s,a)$ given in \eqref{eqn_discounted_distribution}. The intuition behind $\rho_{s_0}(s,a)$ is that it weights the probability of the system being at a specific state-action pair $(s,a)$ at time $t$ by a factor of $(1-\gamma)\gamma^t$. Notice that this factor is equal to the probability of a geometric distribution of parameter $\gamma$ to take the value $t$. Thus, for the $k$-th policy update, one can interpret the distribution $\rho_{s_0}(s,a)$ as the probability of running the system for $T$ steps, with $T$ randomly drawn from a geometric distribution of parameter $\gamma$. This supports steps 2-7 in Algorithm \ref{alg_stochastic_grad} which describes how to obtain a sample $(s_T,a_T)\sim\rho_{s_0}(s,a)$. Latter, in Proposition \ref{prop_unbiased_grad} it is claimed that an unbiased estimate of $\nabla_h U_{s_0}(h)$ is obtained by substituting the sample $(s_T,a_T)$ in the stochastic gradient \begin{equation}\label{eqn_first_stochastic_gradient} \hat{\nabla}_h U_{s_0}(h,\cdot) = \frac{1}{1-\gamma}\hat{Q}(s_T,a_T;h)\kappa(s_T,\cdot)\Sigma^{-1}(a_T-h(s_T)), \end{equation} with $\hat Q(s_T,a_T;h)$ being an unbiased estimate of $Q(s_T,a_T;h)$. The previous expression reveals a second challenge in computing of the stochastic gradient, namely the need of computing the function $Q$ -- or an estimate-- at the state-action pair $(s_T,a_T)$. In \red{cite offline} an unbiased estimate of $Q(s_T,a_T;h)$ that can be computed in a finite number of steps is proposed. In Section \ref{sec_q_estimate} we explain the main idea of such estimator and formalize its main property. With such estimate at hand, one could compute \eqref{eqn_first_stochastic_gradient} to update the policy iteratively following the rule \begin{equation}\label{eqn_stochastic_update} h_{k+1} = h_k + \eta_k \hat{\nabla}_h U_{s_0}(h_k,\cdot), \end{equation} where $\eta_k>0$ is the step size of the algorithm. Under proper conditions stochastic gradient ascent methods can be shown to converge with probability one to the local maxima \cite{pemantle1990nonconvergence}. This approach has been widely used to solve parametric optimization problems where the decision variables are vectors in $R^n$ and in \red{cite offline} these results are extended to non-parametric problems in RKHSs. Observe however, that the estimate of the gradient \eqref{eqn_first_stochastic_gradient} requires that the system runs for, at least, $T$ steps. Denote by $s_{k+1}$ the state of the system at this point. Thus, when the policy is updated to $h_{k+1}$, the initial position for the system is different than $s_0$, hence if we repeat the previous process the estimate obtained will be the estimate of the gradient of the function $U_{s_{k+1}}(h_{k+1})$. The latter could be avoided by taking the system to the initial state $s_0$ after each update. However, such policy prevents a fully online implementation of the algorithm. In this work we overcome this limitation by exploiting the fact that the gradient $\nabla_h U_{s}(h_k,\cdot)$ are similar for all $s\in\ccalS$. (Proposition \red{SOME PROPOSITION}). We start by describing the algorithm to obtain the unbiased estimate $\hat Q(s_k,a_k;h)$ in a finite number of steps, which is instrumental for our overall non-parametric stochastic approximation strategy. \subsection{Unbiased Estimate of Q}\label{sec_q_estimate} A theoretically conceivable but unrealizable form of estimating the value of $Q(s,a;h)$ is to run a trajectory for infinite steps stating from $(s_0,a_0)=(s,a)$ and then compute the following infinite sum $\hat{q}_h = \sum_{t=0}^\infty \gamma^{t} r(s_t,a_t).$ Despite being an unbiased estimate, a major drawback of this approach is the need to consider an infinite number of steps. In contrast, we present the subroutine Algorithm \ref{alg_q_estimate} that allows to compute an unbiased estimate of $Q(s,a;h)$ by considering a representative future reward obtained after a finite number of steps. As with $U(h)$, a parameter $\gamma$ closer to zero assigns similar weights to present and future rewards, and $\gamma$ close to zero prioritizes the present. In that sense, when $\gamma$ is very small, we do not need to let the system evolve for long time to get a representative reward. Likewise, for $\gamma$ close to one we need to look far away into the future. Again, the geometric distribution allows us to represent this idea. Specifically, let $T_Q$ be a geometric random variable with parameter $\gamma$, i.e., $P(T_Q=t) =(1-\gamma)\gamma^t$, which is finite with probability one. Then define the estimate of $Q(s,a;h)$ as the sum of rewards collected from step $t=0$ until $t=T_Q$ \begin{align} \hat{Q}(s,a;h) &:= (1-\gamma)\sum_{t=0}^{T_Q}r(s_t,a_t) \label{eqn_q_estimate} \end{align} Algorithm \ref{alg_q_estimate} summarizes how to obtain $\hat{Q}(s,a;h)$ as in \eqref{eqn_q_estimate}, and Proposition 1 states that it is unbiased. \begin{algorithm} \caption{estimateQ} \label{alg_q_estimate} \begin{algorithmic}[1] \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \Require $s,a,h$ \State \textit{Initialize}: $\hat{Q} = 0$, $s_0 = s$, $a_0 =a$ \State Draw an integer $T_Q$ form a geometric distribution with parameter $\gamma$, $P(T_Q = t) = (1-\gamma)\gamma^t$ \For {$t = 0,1,\ldots T_Q-1$} \State Collect reward and add to estimate $\hat{Q} = \hat{Q} + r(s_t,a_t)$ \State Let system advance $s_{t+1} \sim P_{s_t\to s_{t+1}}^{a_t}$ \State Select action $a_{t+1} \sim \pi_h(a|_{s_{t+1}})$ \EndFor \State Collect last reward $\hat{Q} = \hat{Q} + r(s_{m^\prime},a_{m^\prime})$ \State Scale $\hat{Q} = (1-\gamma)\hat{Q}$\\ \Return $\hat{Q}$, $s_{T_Q}$ \end{algorithmic} \end{algorithm} \begin{proposition}\label{prop_unbiased_q} The output $\hat{Q}(s,a;h)$ of Algorithm \ref{alg_q_estimate} is an unbiased estimate of $Q(s,a;h)$. \end{proposition} \begin{proof} See Proposition 1 \red{CITE OFFLINE PAPER}. \end{proof} \blue{Not clear that we want to it this way} \red{ \subsection{Unbiased Estimate of the Stochastic Gradient}\label{sec_nabla_U} In this section we present a subroutine that uses the estimate $\hat Q(s,a;h)$ produced by Algorithm \ref{alg_q_estimate} to obtain an unbiased estimate of $\nabla_hU(h)$. As discussed before, a sample from $\rho(s,a)$ can be obtained by sampling a time $T$ from a geometric distribution of parameter $\gamma$ and running the system $T$ times. Although the resulting estimate in \eqref{eqn_first_stochastic_gradient} can be shown to be unbiased, which would be enough for the purpose of stochastic approximation, we chose to introduce symmetry with respect to $h(s)$ as it is justified in Remark \ref{remark_approximation}. Instead of computing the approximation only at the state-action pair $(s_T,a_T)$ we average said value with $\hat Q(s_T,\bar{a}_T)$, where $\bar{a}_T=h(s_T)-(a_T-h(s_T)$ is the action that is symmetric to $a_T$ with respect to $h(s_T)$ (steps 8--11 in Algorithm \ref{alg_stochastic_grad}). Hence, the proposed estimate is \begin{align}\nonumber \hat{\nabla}_hU(h,\cdot) &=\frac{1}{2(1-\gamma)}\left(\hat{Q}(s_T,a_T;h)-\hat{Q}(s_T,\bar{a}_T;h)\right)\\&\times \kappa(s_T,\cdot)\Sigma^{-1}(a_T-h(s_T))\label{eqn_stochastic_grad}. \end{align} The subroutine presented in Algorithm \ref{alg_stochastic_grad} summarizes the algorithm to compute our stochastic approximation in \eqref{eqn_stochastic_grad}. We claim that it is unbiased in the following proposition. \begin{algorithm} \caption{StochasticGradient}\label{alg_stochastic_grad} \begin{algorithmic}[1] \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \Require $h$, $s$ \State \textit{Initialize}: $s_0=s$ \State Draw an integer $T$ form a geometric distribution with parameter $\gamma$, $P(T = t) = (1-\gamma)\gamma^t$ \State Select action $a_{0} \sim \pi_h(a|_{s})$ \For {$t = 0,1,\ldots T-1 $} \State Advance system $s_{t+1} \sim P_{s_t\to s_{t+1}}^{a_t}$ \State Select action $a_{t+1} \sim \pi_h(a|_{s_{t+1}})$ \EndFor \State \label{stepQ} Get estimate of $Q(s_T,a_T;h)$ as in Algorithm \ref{alg_q_estimate}: $$\hat{Q}(s_T,a_T;h) = \textrm{estimateQ}(s_T,a_T;h)$$ \vspace{-3mm} \State Given $a_T$, find symmetric $\bar{a}_T=h(s_T)-(a_T-h(s_T))$ \State Get estimate of $Q(s_T,\bar{a}_T;h)$ as in Algorithm \ref{alg_q_estimate}: $$\hat{Q}(s_T,\bar{a}_T;h)= \textrm{estimateQ}(s_T,\bar{a}_T;h)$$ \label{stepQ2}\vspace{-4mm} \State Compute the stochastic gradient $\hat{\nabla}_hU(h,\cdot)$ as in \eqref{eqn_stochastic_grad} \Return $\hat{\nabla}_hU(h,\cdot)$ \end{algorithmic}\label{alg_stochastic_gradient} \end{algorithm} \begin{proposition}\label{prop_unbiased_grad} The output $\hat{\nabla}_h U(h,\cdot)$ of Algorithm \ref{alg_stochastic_gradient} is an unbiased estimate of $\nabla_h U(h,\cdot)$ in \eqref{eqn_nabla_U}. \end{proposition} \begin{proof} To show that the estimate is unbiased we compute the expectation of $\hat{\nabla}_hU(h,\cdot)$ conditioned to $h$, which in turn can be written as % \begin{equation} \begin{split} \mathbb{E}\left[\hat{\nabla}_hU(h,\cdot)\Big| h\right] &= \mathbb{E}\left[\left[\hat{\nabla}_hU(h,\cdot)\Big|s_T,a_T\right]\Big| h\right] \end{split} \end{equation} % Using the linearity of the expectation and the fact that $\kappa(s_T,\cdot)\Sigma^{-1}(a_T-h(s_T))$ is measurable with respect of the sigma algebra generated by $s_0 \ldots s_T$ and $a_0\ldots a_T$ we have that \begin{equation} \begin{split} \mathbb{E}\left[\hat{\nabla}_hU(h,\cdot)\Big| h\right] &= \mathbb{E}\left[\mathbb{E}\left[\hat{Q}(s_T,a_T;h)-\hat{Q}(s_T,\bar{a}_T;h)\Big|s_T,a_T\right]\right.\\ &\left.\frac{1}{2(1-\gamma)}\kappa(s_T,\cdot)\Sigma^{-1}(a_T-h(s_T))\Big| h\right] \end{split} \end{equation} Using the result of Proposition \ref{prop_unbiased_q} the previous expression reduces to \begin{equation} \begin{split} \mathbb{E}\left[\hat{\nabla}_hU(h,\cdot)\Big| h\right] &= \mathbb{E}\left[\left({Q}(s_T,a_T;h)-{Q}(s_T,\bar{a}_T;h)\right)\right.\\ &\left.\frac{1}{2(1-\gamma)}\kappa(s_T,\cdot)\Sigma^{-1}(a_T-h(s_T))\Big| h\right] \end{split} \end{equation} Since $a_T$ is normally distributed with mean $h(s_T)$ we have that $a_T-h(s_T)$ and $h(s_T)-a_T$ are both normally distributed with zero mean. Moreover, $\bar{a}_T$ has the same distribution as $a_T$. Hence the two expectations on the right hand side of the previous equality are the same. Adding them yields \begin{equation} \begin{split} \mathbb{E}\left[\hat{\nabla}_hU(h,\cdot)\Big| h\right]&= \mathbb{E}\left[\frac{Q(s_T,a_T;h)}{1-\gamma} \right.\\ &\left.\kappa(s_T,\cdot)\Sigma^{-1}(a_T-h(s_T))\Big|h\right]. \end{split} \end{equation} The previous expression is equivalent to \begin{equation}\label{eqn_before_swaping_sum_expectation} \begin{split} \mathbb{E}\left[\hat{\nabla}_hU(h,\cdot)\Big| h\right]= \frac{1}{1-\gamma}\mathbb{E}\left[\sum_{t=0}^\infty \mathbbm{1}(T=t)Q(s_t,a_t;h)\right.\\ \left.\phantom{\sum_{t=0}^\infty}\kappa(s_t,\cdot)\Sigma^{-1}(a_t-h(s_t))|h\right]. \end{split} \end{equation} Next, we argue that it is possible to exchange the infinity sum and the expectation in the previous expression. Observe that only one of terms inside the sum can be different than zero. Denote by $t^*$ the index corresponding to that term and upper bound the norm of $\hat{\nabla}_h U(h)$ by \begin{equation} \begin{split} (1-\gamma)\left\|\hat{\nabla}_h U(h)\right\|\leq \left|Q(s_{t^*},a_{t^*};h)\right|\left\| \kappa(s_{t^*},\cdot)\right\|\\ \left\|\Sigma^{-1}(a_{t^*}-h(s_{t^*}))\right\|. \end{split} \end{equation} Using that $\left\|\kappa(s_t,\cdot)\right\| =1$ (cf., Definition \ref{def_rkhs}) and $\left|Q(s,a;h) \right| \leq B_r/(1-\gamma)$ (cf., Lemma \ref{lemma_bounded}), we can upper bound the previous expression by \begin{equation}\label{eqn_bound_kappa_Q} \begin{split} \left\|\hat{\nabla}_h U(h)\right\|&\leq \frac{B_r}{\left(1-\gamma\right)^2}\left\|\Sigma^{-1}(a_{t^*}-h(s_{t^*}))\right\| \\ &\leq \frac{B_r}{\left(1-\gamma\right)^2\lambda_{\min}(\Sigma^{-1/2})}\left\|\Sigma^{-1/2}(a_{t^*}-h(s_{t^*}))\right\|, \end{split} \end{equation} Notice that $\Sigma^{-1/2}\left(a_t-h(s_t)\right)$ are identically distributed mutlivariate normal distributions, and thus the expectation of its norm is bounded. The Dominated Convergence Theorem can be hence used to exchange the sum and the expectation in \eqref{eqn_before_swaping_sum_expectation}. In addition, the draw of the random variable $T$ is independent of the evolution of the system until infinity. Hence \eqref{eqn_before_swaping_sum_expectation} yields \begin{align}\label{eqn_after_swaping_sum_expectation} & \mathbb{E}\left[\hat{\nabla}_hU(h,\cdot)\Big| h\right]=\\ & \sum_{t=0}^\infty \frac{P\left(t=T\right)}{1-\gamma}\mathbb{E}\left[Q(s_t,a_t;h)\kappa(s_t,\cdot)\Sigma^{-1}(a_t-h(s_t))|h\right] =\nonumber\\ & \sum_{t=0}^\infty \gamma^t\mathbb{E}\left[Q(s_t,a_t;h)\kappa(s_t,\cdot)\Sigma^{-1}(a_t-h(s_t))|h\right]=\nabla_hU(h,\cdot).\nonumber \end{align} where the last equality coincides with that in \eqref{eqn_nabla_U}. To be able to write the last equality we need to justify that it is possible to exchange the sum with the expectation. We do so next in order to complete proof that the stochastic gradient estimated by Algorithm \ref{alg_stochastic_gradient} is unbiased. Let us define the following sequence of random variables \begin{equation} S_k = \sum_{t=0}^k\gamma^t Q(s_t,a_t;h)\kappa(s_t,\cdot)\Sigma^{-1}(a_t-h(s_t)). \end{equation} Use the triangle inequality along with the bounds on $Q(s_t,a_t;h)$ and $\kappa(s_t,\cdot)$ from \eqref{eqn_bound_kappa_Q} to bound the norm of $S_k$ by \begin{equation} \left\|S_k\right\| \leq \frac{B_r}{1-\gamma}\sum_{t=0}^k\gamma^t\left\|\Sigma^{-1}(a_t-h(s_t))\right\|. \end{equation} Observe that the sum in the right is an increasing random variable because all terms in the sumands are positive. Hence, by virtue of the Monotone Convergence Theorem (see e.g., \cite[Theorem 1.6.6]{durrett2010probability}) we have that \begin{equation} \mathbb{E}\hspace{-.1cm}\left[\sum_{t=0}^\infty\hspace{-.1cm}\gamma^t\left\|\Sigma^{-1}(a_t-h(s_t))\right\|\right]=\sum_{t=0}^\infty\hspace{-.1cm}\gamma^t\mathbb{E}\hspace{-.1cm}\left[\left\|\Sigma^{-1}(a_t-h(s_t))\right\|\right]. \end{equation} Because $\Sigma^{-1/2}(\left(a_t-h(s_t)\right)$ is normally dsitributed, its norm has bounded expectation. Use in addition the fact that the geometric series converges to ensure that the right hand side of the previous expression is bounded. $S_k$ is therefore dominated by a random variable with finite expectation. Thus, the Dominated Convergence Theorem allows us to write that \begin{equation} \lim_{k\to \infty} \mathbb{E}[S_k] = \mathbb{E}[\lim_{k\to\infty}S_k]. \end{equation} The latter corresponds to exchanging the sum and the expectation in \eqref{eqn_after_swaping_sum_expectation}. \end{proof} Now we are in conditions of presenting the complete algorithm for policy gradient in RKHSs. Each iteration consists of the estimation of $\hat{\nabla}_h U(h_k,\cdot)$ as described in Algorithm \ref{alg_stochastic_gradient} -- which uses Algorithm \ref{alg_q_estimate} as a subroutine to get unbiased estimates of $Q(s,a;h)$ -- and of the updated \begin{equation}\label{eqn_gradient_ascent} {h}_{k+1} = h_k +\eta_k\hat{\nabla}_h U(h_k,\cdot), \end{equation} where $\eta_k$ is non-summable and square summable, i.e. \begin{equation}\label{eqn_stepsize} \sum_{k=0}^\infty \eta_k = \infty \quad \mbox{and} \quad \sum_{k=0}^\infty \eta_k^2 <\infty. \end{equation} \begin{algorithm} \caption{Stochastic Policy Gradient Ascent} \begin{algorithmic}[1] \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \Require step size $\eta_0$ \State \textit{Initialize}: $h_0=0$ \For{$k=0 \ldots$} \State Draw an initial state $s_0$ for Algorithm \ref{alg_stochastic_gradient} \State Compute the stochastic gradient: $$\hat{\nabla}_h U(h_k,\cdot) = \textrm{StochasticGradient}(h_k,s_0)$$ \State Gradient ascent step ${h}_{k+1} = h_k +\eta_k \hat{\nabla}_h U(h_k,\cdot) $ \EndFor \end{algorithmic}\label{alg_policy_gradient} \end{algorithm} \begin{theorem}\label{thm_convergence_unbiased} Let $\left\{h_k,k\geq 0\right\}$ be the sequence of functions given by \eqref{eqn_gradient_ascent}, where $\eta_k$ is as step size satisfying \eqref{eqn_stepsize} and $\hat{\nabla}_hU(h_k,\cdot)$ is an unbiased estimator of the gradient of the functional. With probability one we have that $\lim_{k\to \infty} h_k = H^*$, % where $H^*$ is a random variable taking values in the set of critical points of the functional $U(h)$ defined in \eqref{eqn_problem_statement}. \end{theorem} \begin{proof} The proof of this result is the matter of Section \ref{sec_convergence}. \end{proof} The previous result establishes that $h_k$ converges with probability one to a critical point of the functional $U(h)$. A major drawback of Algorithm 3 is that at each iteration the stochastic gradient ascent iteration will add a new element to the kernel dictionary. Indeed, for each iteration $\hat{\nabla}_hU(h_k,\cdot)$ introduces an extra kernel centered at a new $s_{T}$ (cf., \eqref{eqn_stochastic_grad}). Hence for any $k>0$ in order to represent $h_k$ we require $k$ dictionary elements. This translates into memory explosion and thus Algorithm 3, while theoretically interesting, is not practical. \red{To overcome this limitation, we introduce in the next section a projection on a smaller Hilbert space so that we can control the model order. Before that, we make a pertinent remark regarding the random policy. } \begin{comment} \end{comment} \begin{remark}\label{remark_approximation} % Our reason to use a randomized Gaussian policy is two-fold: it yields a tractable approximation of the gradient of the q-function that would result from a deterministic policy, and it effects numerical derivatives when the gradients are handled via stochastic approximation (see also \cite{nesterov2017random}). Building on these hints, we will propose alternative estimates for faster convergence. In this direction, we consider the Gaussian bell $\pi_h(a|_{s})$ with covariance $\Sigma=\sigma^2 I$ as an approximation to the Dirac's impulse \cite{schwartz1998distributions}, and its gradient $\nabla_a \pi_h(a|_{s})= \Sigma^{-1} (a-h(s))\pi_h(a|_{s})$ as an approximation of the impulse's gradient. Then, the next proposition follows \begin{proposition} Consider a family of Gaussian policies with $\Sigma=\sigma^2 I$ such that $\sigma\in \mathbb R$, and let $U_\sigma(s;h)$ and $Q_\sigma(s,a;h)$ be the cumulative rewards and q-functions that results from such policies, respectively. Correspondingly, let $Q_0(s,a;h):=\mathbb{E}\left[\sum_{t=0}^\infty \gamma^t r(s_t,a_t)\Big| h, s_0=s, a_0=a\right]$ be the q-function that results from a deterministic policy $a_t=h(s_t)$. Then \begin{align} \lim_{\sigma\to 0}\int Q_\sigma(s,a;h) \Sigma^{-1} (a-h(s))\pi_h(a|_{s}) da=\nabla_a Q_0(s,a;h)\label{pi_is_gradient} \end{align} and \begin{align*} \nabla_h & U_\sigma(h,\cdot) = &\xrightarrow[\sigma \to 0]{} \frac{1}{1-\gamma} \int \nabla_a Q_0(s,a;h)\rho(s) \kappa(s,\cdot) ds\end{align*} where $\rho(s)$ is defined such that $\rho(s,a)=\rho(s)\pi_h(a|_{s}).$ \end{proposition}% This interpretation of the integral in \eqref{pi_is_gradient} as the gradient of $Q(s,a;h)$ can be seen from the perspective of stochastic approximation. For notational brevity we define $I_\pi:=\int Q(s,a;h) \nabla_a \pi_h(a|_{s}) da$, and express it in terms of expectations \begin{align}I_\pi&=\mathbb E_{a\sim\pi_{h}}[Q(s,a;h) \Sigma^{-1} (a-h(s))]\label{IpiQ} \end{align} Then, an unbiased stochastic approximation can be obtained by sampling two (or more) instances $a$ and $a'$ from $\pi_h(a|_{s})$ and averaging as in $\hat I_\pi= \frac{1}{2} Q(s,a;h) \Sigma^{-1} (a-h(s))+ \frac{1}{2} Q(s,a';h) \Sigma^{-1} (a'-h(s))$. Furthermore, if $a'$ is the symmetric action of $a$ with respect to the mean $h(s)$, then the estimator is still unbiased. Define the zero-mean Gaussian variable $\eta = a-h(s)$ to be the deviation of $a$ from $h(s)$. Thus by symmetry, $a'-h(s)=-\eta$, and we can rewrite the symmetric estimate as the finite difference \begin{align}\hspace{-.1cm} \hat I_\pi&=\frac{\Sigma^{-1}\eta}{2}(Q(s,h(s)+\eta;h)-Q(s,h(s)-\eta;h)), \label{numerical_derivative}\end{align} revealing the gradient structure hidden in \eqref{IpiQ}. The interpretation of \eqref{numerical_derivative} as a derivative is relevant to our policy method because it reveals the underlying reinforcement mechanisms, in the sense that the policy update favors directions that improve the reward. Fig.\ref{fig_gradient} (left) represents the field $Q(s,a;h)$ as a function of $a\in\mathbb R^2$, and the gradient estimate $\hat I_\pi$ in \eqref{numerical_derivative} that is obtained by weighting two opposite directions with the corresponding rewards. Since the reward in the direction $\eta$ is relatively higher $\hat I_\pi(Q)$ points in this direction. Fig. \ref{fig_gradient} (right) shows that the direction of $\nabla_a Q(s,a;h)$ can be approximated more accurately at the expense of sampling the reward at $2d$ points in quadrature. \begin{figure} \centering \includegraphics[width=0.49 \linewidth]{./figures/gradientIQ2red.eps} \includegraphics[width=0.49\linewidth]{./figures/gradientIQ4red.eps} \caption{Numerical gradient via stochastic approximation; (left) two-sample approximation, (right) full-dimension. Red levels represents higher values of $Q(s,a;h)$.} \label{fig_gradient} \end{figure} \end{remark} } \subsection{Kernel Orthogonal Matching Pursuit}\label{sec_komp} In this section we present the details of Kernel Orthogonal Matching Pursuit. Starting with the policy $h_0 \equiv 0$, each stochastic gradient ascent iteration defines a new policy \begin{equation}\label{eqn_partial_grad_ascent} \tilde{h}_{k+1} = h_k +\eta\hat{\nabla}_h U_{s_k}(h_k,\cdot), \end{equation} where $\hat{\nabla}_h U_{s_k}(h_k,\cdot)$ is that in \eqref{eqn_stochastic_gradient}. The difference between the updates \eqref{eqn_partial_grad_ascent} and \eqref{eqn_stochastic_update} is that in \eqref{eqn_partial_grad_ascent} $h_k=\sum_{j=1}^{M_k} \kappa(s_{T^j}^{(k)},\cdot)w_j^{(k)}$ is represented by a reduced $M_k\leq k$ number of states $s_{T^j}^{(k)}$ and weights $w_j^{(k)}\in\mathbb{R}^p$, as it results from the pruning procedure below, (cf., $M_k=k$ for $h_{k+1}$ in \eqref{eqn_stochastic_update}). Let $(s_{T^k},a_{T^k})$ be the state-action pair $(s_T, a_T) $ in step 7 Algorithm \ref{alg_stochastic_grad} at its $k$--th call by Algorithm \ref{alg_online_policy_gradient}. Then define \begin{equation}\label{eqn_weights} \tilde{w}_k :=\eta \frac{\hat{Q}(s_{T^k},a_{T^k};h_k)}{1-\gamma}\Sigma^{-1}(a_{T^k}-h_k(s_{T^k})), \end{equation} and rewrite $\eta\hat{\nabla}_h U_{s_k}(h_k,\cdot)$ using the expression \eqref{eqn_stochastic_gradient} and \eqref{eqn_weights} as $\eta\hat{\nabla}_h U_{s_k}(h_k,\cdot) = \kappa(s_{T_k},\cdot)\tilde{w}_k$. Thus, we can write $\tilde{h}_{k+1}$ \begin{equation} \tilde{h}_{k+1} = \sum_{j=1}^{M_{k}} \kappa(s_{T^j}^{(k)},\cdot)w_j^{(k)}+\kappa(S_{T^k},\cdot)\tilde{w}_k. \end{equation} Hence, $h_k$ is represented by dictionary $D_k=[s_{T^k}^{(k)},\ldots, s_{T^{M_k}}^{(k)}]$ and associated weights $\bbw_k=\left[\left(w_1^{(k)}\right)^\top,\ldots,\left(w_{M_k}^{(k)}\right)^\top\right]^\top,$ and $\tilde{h}_{k+1}$ is represented by the updated $\tilde{D}_{k+1} = [D_k, s_{T_k}]$ and $\tilde{\bbw}_{k+1} = [\bbw_k^\top, \tilde{w}_{k}^\top]^\top$, which has model order $\tilde{M}_{k+1} = M_k+1$. Then, to avoid memory explosion, we prune the dictionary as long as the induced error stays below a prescribed bound $\epsilon>0$. We start by storing copies of the previous dictionary, i.e., define ${D}_{k+1} = \tilde{D}_{k+1}$ and ${\bbw}_{k+1} = \tilde{\bbw}_{k+1}$. Let $\ccalH_{{D}^j_{k+1}}$ be the space spanned by all the elements of ${D}_{k+1}$ except for the $j$-th one. For each $j=1 \ldots {M}_{k+1}$ we identify the less informative dictionary element by solving \begin{align}\label{eqn_pruning_optimization} e_j &= \min_{{h}\in\ccalH_{{D}^j_{k+1}}}\left\| {h}-\tilde{h}_{k+1}\right\|_\ccalH^2 =\tilde{\bbw}_{k+1}^\top \bbK_{\tilde{D}_{k+1},\tilde{D}_{k+1}}\tilde{\bbw}_{k+1}\\ & +\hspace{-0.1cm} \min_{\bbw \in \mathbb{R}^{p M_{k+1}-1}}\hspace{-0.1cm} \bbw^\top \bbK_{{D}^j_{k+1},{D}^j_{k+1}} \bbw -2 \bbw^\top \bbK_{{D}^j_{k+1},\tilde{D}_{k+1}}\tilde{\bbw}_{k+1}, \nonumber \end{align} which results from expanding the square after substituting $h$ and $\tilde{h}_{k+1}$ by their representations as weighted sums of kernel elements, and upon defining the block matrices $\bbK_{\tilde{D}_{k+1},\tilde{D}_{k+1}}$, $\bbK_{{D}^j_{k+1},{D}^j_{k+1}}$ and $\bbK_{{D}^j_{k+1},\tilde{D}_{k+1}}$ as block matrices whose $(l,m)$-th blocks of size $p\times p$ are $\kappa\left(\tilde{s}_{T^l}^{(k)},\tilde{s}_{T^m}^{(k)}\right)$, $\kappa\left(s_{T^l}^{(k)},s_{T^m}^{(k)}\right)$ and $\kappa\left(s_{T^l}^{(k)},\tilde{s}_{T^m}^{(k)}\right)$, where $s_{T^i}^{(k)}$ and $\tilde{s}_{T^i}^{(k)}$ correspond to the $i$-th element of $D_{k+1}^j$ and of $\tilde{D}_{k+1}$ respectively. \begin{algorithm} \caption{Kernel Orthogonal Matching Pursuit (KOMP)} \begin{algorithmic}[1] \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \Require function ${\tilde{h}_k}$ defined by Dictionary $\tilde{D}_k\in\mathbb{R}^{n\times \tilde{M}_k}$ weights $\tilde{\bbw}_k\in\mathbb{R}^{p \times \tilde{M}_k}$ and compression budget $\epsilon>0$ \State \textit{Initialize}: ${D}_k = \tilde{D}_k$, $\bbw_k=\tilde{\bbw}_k$, $M_k=\tilde{M}_k$, $e^\star=0$ \While{$e^\star<\epsilon$ and $M_k>0$} \For{$j=1\ldots {M}_k$} \State Find minimal error $e_j$ by solving \eqref{eqn_pruning_optimization} \EndFor \State Less informative element $j^\star = \argmin_{j} e_j$ \State Save error $e^\star = e_{j^\star}$ \If{Error smaller than compression budget $e^\star <\epsilon$} \State Prune Dict., ${D}_{k} \leftarrow {D}_{k}^{j^\star} $, ${M}_k \leftarrow {M}_k-1$ \State Update Weights as in \eqref{eqn_least_square_solution} $$ {\bbw}_k = \bbK_{{D}_{k},{D}_{k}}^\dagger \bbK_{{D}_{k},\tilde{D}_{k}}\tilde{\bbw}_{k} $$ \EndIf \EndWhile\\ \Return ${D}_k,{\bbw}_k$ \end{algorithmic}\label{algorithm_komp} \end{algorithm} Problem \eqref{eqn_pruning_optimization} is a least-squares problem with the following closed-form solution \begin{equation}\label{eqn_least_square_solution} \bbw^\star_j = \bbK_{{D}^j_{k+1},{D}^j_{k+1}}^\dagger \bbK_{{D}^j_{k+1},\tilde{D}_{k+1}}\tilde{\bbw}_{k+1}, \end{equation} where, $\left(\cdot\right)^\dagger$ denotes the Moore-Penrose pseudo-inverse. After computing all compression errors $e_j$ we chose the dictionary element that yields the smallest error $j^\star = \argmin_{j=1 \ldots M_{k+1}} e_j$, we remove the $j^\star$-th column from the dictionary ${D}_{k+1}$, i.e., we redefine ${D}_{k+1} = {D}_{k+1}^{j^\star}$ and the model order $M_{k+1} =M_{k+1}-1$ and update the corresponding weights as ${\bbw}_{k+1} = \bbw^\star_{j^\star}$. We repeat the process as long as the minimum compression error remains below the compression budget, i.e., $\min_{j=1 \ldots M_{k+1}} e_j<\epsilon$. The output of the pruning process is a function $h_{k+1}$ that is represent by at most the same number of elements than $\tilde{h}_{k+1}$ and such that the error introduced in this approximation is, by construction, smaller than the compression budget $\epsilon$. This output can be interpreted as a projection over a RKHS of smaller dimension. Let $D_{k+1}$ be the dictionary that Algorithm \ref{algorithm_komp} outputs. Then, the resulting policy can be expressed as \begin{equation}\label{eqn_proj_stochastic_ascent} \hspace{-.1cm}h_{k+1}\hspace{-.1cm} =\hspace{-.1cm} \ccalP_{\ccalH_{D_{k+1}}}\hspace{-.1cm}\left[ \tilde{h}_{k+1}\right]\hspace{-.1cm} =\hspace{-.1cm} \ccalP_{\ccalH_{D_{k+1}}}\hspace{-.1cm}\left[h_{k}+\eta \hat{\nabla}_h U_{s_k}(h_k,\cdot)\right], \end{equation} where the operation $\ccalP_{\ccalH_{D_{k+1}}}\left[ \cdot \right]$ refers to the projection onto the RKHS spanned by the dictionary $D_{k+1}$. \subsection{Proof of Lemma \ref{lemma_distribution}}\label{appendix_lemma_distribution} \begin{proof} % Since $s\in\ccalS_0$ there exists some time $t\geq 0$ such that $p(s_t=s|s_0)> 0$. Therefore we have that % \begin{equation} \begin{split} \rho_{s_0}(s) &= (1-\gamma)\sum_{u=0}^\infty \gamma^u p(s_u=s|s_0) \\ &\geq (1-\gamma)\gamma^{t}p(s_t=s|s_0), \end{split} \end{equation} % where the last inequality follows from the fact that $\gamma>0$ and $p(s_u=s|s_0) \geq 0$ for all $u\geq 0$. Hence, by assumption it follows that $\rho_{s_0}(s) >0$. To prove the second claim, start by writting $\rho_{s^\prime}(s^{\prime\prime})$ as % \begin{equation} \begin{split} \rho_{s^\prime}(s^{\prime\prime}) &= (1-\gamma)\sum_{t=0}^\infty \gamma^t p(s_t=s^{\prime\prime}| s_0=s^\prime) \\ &= (1-\gamma)\gamma^{-T}\sum_{u=T}^\infty \gamma^u p(s_u=s^{\prime\prime}| s_T=s^\prime) , \end{split} \end{equation} % where the last equality holds for any $T\geq 0$. Using the Markov property for any $u$ we have that % \begin{equation} p(s_u=s^{\prime\prime}| s_T=s^\prime) = p(s_u=s^{\prime\prime}| s_T=s^\prime,s_0). \end{equation} % % Since $s^\prime \in S_0$, there exists $T\geq 0$ such that $p(S_T=s^\prime |s_0)>0$. For that specific $T$, we have that % \begin{equation} p(s_u=s^{\prime\prime}| s_T=s^\prime,s_0) = \frac{p(s_u=s^{\prime\prime}, s_T=s^\prime|s_0)}{p(s_T=s^\prime|s_0)}. \end{equation} % Notice next that since $s^{\prime\prime} \in \ccalS\setminus \ccalS_0$ we have that $p(s_u=s^{\prime\prime}|s_0)=0$ for all $u\geq 0$. Hence, we also have that $p(s_u=s^{\prime\prime},S_T=s^\prime|s_0)=0$ for all $u\geq 0$ which completes the proof of the proposition. \end{proof} \subsection{Proof of Lemma \ref{lemma_lipshitz}}\label{appendix_lipshitz} % Without loss of generality, we prove the result for $D(s)\rho_{s_0}(s)$. We start by showing that the cumulative weighted distribution $\rho_{s_0}(s)$ is Lipschitz with constant $L_p$. \begin{lemma} Under Assumption \ref{assumption_prob_dist}, the distribution $\rho_{s_0}(s)$ is Lipschitz with constant $L_p$, where $L_p$ is the Lipschitz constant defined in Assumption \ref{assumption_prob_dist}. \end{lemma} \begin{proof} Let us start by writing $p(s_t=s|s_0)$ by marginalizing it % \begin{equation} \begin{split} & p(s_t=s|s_0) =\int p(s_t=s,a_{t-1},s_{t-1}|s_0)\, ds_{t-1} da_{t-1}. \end{split} \end{equation} % Using Bayes' rule and the Markov property of the transition probability it follows that \begin{equation} \begin{split} & p(s_t=s|s_0) =\\ &\int p(s_t=s|a_{t-1},s_{t-1})\pi_h(a_{t-1}|s_{t-1})p(s_{t-1}|s_0)\, ds_{t-1} da_{t-1}. \end{split} \end{equation} Using the Lipschitz property of the transition probability (cf., Assumption \ref{assumption_prob_dist}) we can upper bound $\left| p(s_t=s|s_0) - p(s_t=s^\prime|s_0)\right|$ by \begin{equation} \begin{split} \left| p(s_t=s|s_0) - p(s_t=s^\prime|s_0)\right| \leq L_p\left\|s-s^\prime \right\| \\ \int \pi_h(a_{t-1}|s_{t-1}) p(s_{t-1}|s_0) \, ds_{t-1}da_{t-1} \\ \end{split} \end{equation} Since both $\pi_h(a_{t-1}|s_{t-1})$and $p(s_{t-1}|s_0)$ are probability distributions they integrate one. Thus we have that \begin{equation}\label{eqn_lipschitz_p} \begin{split} \left| p(s_t=s|s_0) - p(s_t=s^\prime|s_0)\right| \leq L_p\left\|s-s^\prime \right\|. \end{split} \end{equation} Use the definition of $\rho_{s_0}(s)$ (cf., \eqref{eqn_discounted_distribution}) to write the difference $\left|\rho_{s_0}(s)-\rho_{s_0}(s^\prime)\right|$ as \begin{equation} \begin{split} \left|\rho_{s_0}(s)-\rho_{s_0}(s^\prime)\right|=\\ (1-\gamma)\left|\sum_{t=0}^\infty\gamma^t \left(p(s_t=s|s_0)-p(s_t=s^\prime|s_0)\right)\right|. \end{split} \end{equation} Use the triangle inequality to upper bound the previous expression by \begin{equation} \begin{split} \left|\rho_{s_0}(s)-\rho_{s_0}(s^\prime)\right|&\\ \leq (1-\gamma)&\sum_{t=0}^\infty\gamma^t\left|p(s_t=s|s_0)-p(s_t=s^\prime|s_0)\right|. \end{split} \end{equation} By virtue of \eqref{eqn_lipschitz_p}, each term can be upper bounded by $\gamma^tL_p\left\|s-s^\prime\right\|$. Thus \begin{equation} \begin{split} \left|\rho_{s_0}(s)-\rho_{s_0}(s^\prime)\right| \leq (1-\gamma)\sum_{t=0}^\infty\gamma^tL_p\left\|s-s^\prime\right\|=L_p\left\|s-s^\prime\right\|. \end{split} \end{equation} This completes the proof of the lemma. \end{proof} \begin{lemma} Under the Assumptions of Lemma \ref{lemma_lipshitz} $D(s)$ is bounded by $B_D$ (cf., \eqref{eqn_bound_D}) and it is Lipschitz, i.e., % \begin{equation} \left\|D(s)-D(s^\prime)\right\| \leq L_D\left\|s-s^\prime\right\|, \end{equation} were $L_D$ is the constant defined in Lemma \ref{lemma_lipshitz}. \end{lemma} \begin{proof} Let us start by introducing the change of variables $\zeta=\Sigma^{-1/2}(a-h(s))$ to compute $D(s)$. Hence we have that % \begin{equation} D(s) =\int Q(s,h(s)+\Sigma^{1/2}\zeta) \frac{\zeta}{\sqrt{2\pi}^p} e^{-\left\|\zeta\right\|^2/2} \,d\zeta. \end{equation} % Notice that we can define $\phi(\zeta) = e^{-\left\|\zeta\right\|^2/2}/\sqrt{2\pi}^p$ and then, the previous expression reduces to % \begin{equation}\label{eqn_D_change_variable} D(s) =-\int Q(s,h(s)+\Sigma^{1/2}\zeta) \nabla\phi(\zeta) \,d\zeta. \end{equation} Thus, integrating each component of $D(s)$ by parts we have for each $i=1,\ldots, n$ that \begin{equation}\label{eqn_parts_integration} \begin{split} D(s)_i = \int Q(s,h(s)+\Sigma^{1/2}\zeta) \phi(\zeta) \Big|_{\zeta_i-\infty}^{\zeta_i=\infty} d\bar{\zeta}_i\\ +\int \frac{\partial Q(s,h(s)+\Sigma^{1/2}\zeta)}{\partial \zeta_i} \phi(\zeta)\, d\zeta, \end{split} \end{equation} % where $\bar{\zeta}_i$ denotes the integral with respect to all variables in $\zeta$ except for the $i$-th component. Since $Q(s,a)\leq B_r/(1-\gamma)$ \cite[Lemma 3]{paternain2018stochastic} and $\phi(\zeta)$ is a Multivariate Gaussian density the first term in the above sum is zero. Next we compute the derivative of the $Q$-function with respect to $\zeta$. By the chain rule we have that % \begin{equation} \frac{\partial Q(s,h(s)+\Sigma^{1/2}\zeta)}{\partial \zeta} = \Sigma^{1/2}\frac{\partial Q(s,a)}{\partial a}\Big|_{a=h(s)+\Sigma^{1/2}\zeta}. \end{equation} % Thus, \eqref{eqn_parts_integration} reduces to % \begin{equation} \begin{split} D(s) =\int \frac{\partial Q(s,a)}{\partial a}\Big|_{a=h(s)+\Sigma^{1/2}\zeta} \phi(\zeta)\, d\zeta. \end{split} \end{equation} % We claim that the first term in the above integral % \begin{equation}\label{eqn_q_prime_def} Q^\prime(s):= \frac{\partial Q(s,a)}{\partial a}\Big|_{a=h(s)+\Sigma^{1/2}\zeta} \end{equation} % is Lipschitz with constant $L_{D}$. That being the case, one has that % \begin{equation} \begin{split} \left\| D(s)-D(s^\prime)\right\| &\leq \int\left\| Q^\prime(s) -Q^\prime(s^\prime)\right\|\phi(\zeta)\,d\zeta \\ &\leq L_{D}\left\| s -s^\prime\right\| \int\phi(\zeta) \, d\zeta = L_{D}\left\| s -s^\prime\right\|. \end{split} \end{equation} % Thus, to show that $D(s)$ is Lipschitz with constant $L_D$ it remains to be showed that $Q^\prime(s)$ is Lipschitz with the same constant. To do so, write the $Q$ function as % \begin{equation} Q(s,a) = r(s,a) + \sum_{t=1}^\infty \gamma^t \int r(s_t,a_t)p(s_t|a,s)\pi_h(a_t|s_t) \, ds_tda_t, \end{equation} % and compute its derivative with respect to $a$ % \begin{equation}\label{eqn_aux_q_prime} \begin{split} Q^\prime(s,a)=\frac{\partial Q(s,a)}{\partial a} = \frac{\partial r(s,a)}{\partial a} \\+ \sum_{t=1}^\infty \gamma^t \int r(s_t,a_t)\frac{\partial p(s_t|a,s)}{\partial a}\pi_h(a_t|s_t) \, ds_tda_t. \end{split} \end{equation} % Since $\partial r(s,a)/\partial a$ is Lipschitz in both arguments (cf., Assumption \ref{assumption_reward_function}), to show that the derivative of $Q$ is Lipschitz, it suffices to show that $\partial p(s_t|a,s)/\partial a$ is Lipschitz as well. To that end, write $p(s_t|s,a)$ as % \begin{equation} \begin{split} p(s_t|s,a)= \\\int p(s_1|s,a)\prod_{u=1}^{t-1}\pi_h(a_u|s_u)p(s_{u+1}|s_u,a_u) \, d\bbs_{t-1} d\bba_{t-1}, \end{split} \end{equation} % where $d \bbs_{t-1} = (ds_1, \cdots, ds_{t-1})$ and $d\bba_{t-1}=(da_1,\cdots, da_{t-1})$. Let us define % \begin{equation} \begin{split} \Delta p_t(s^\prime,s^{\prime\prime},a^\prime,a^{\prime\prime}):= \frac{ \partial p(s_t|s^\prime,a)}{\partial a}\big|_{a=a^\prime} -\frac{ \partial p(s_t|s^{\prime\prime},a)}{\partial a}\big|_{a=a^{\prime\prime}} . \end{split} \end{equation} % Using the fact that $\partial p(s_1|s,a)/\partial a$ is Lipschitz with respect to $s$ and $a$ with constants $L_{ps}$ and $L_{pa}$ (cf., Assumption \ref{assumption_prob_dist}) we have that % \begin{equation}\label{eqn_deltap} \begin{split} \left\|\Delta p_t(s,s^{\prime},a,a^{\prime})\right\| \leq \int \left(L_{ps}\left\|s^\prime-s^{\prime\prime}\right\|+L_{pa}\left\|a^\prime-a^{\prime\prime}\right\|\right)\\ \prod_{u=1}^{t-1}\pi_h(a_u|s_u)p(s_{u+1}|s_u,a_u) \, d\bbs_{t-1} d\bba_{t-1}. \end{split} \end{equation} % % % % Using the previous bound and \eqref{eqn_aux_q_prime}, we can upper bound the norm of the difference $Q^\prime(s,a) - Q^\prime(s^\prime,a^\prime)$ as % \begin{equation}\label{eqn_aux_dif_Q} \begin{split} \left\| Q^\prime(s,a) - Q^\prime(s^\prime,a^\prime)\right\| \leq L_{r s}\left\|s-s^\prime \right\|+L_{r a}\left\|a-a^\prime \right\|\\ +\sum_{t=1}^\infty \gamma^t\int B_r\left\|\Delta p(s,s^\prime,a,a^\prime)\right\|\pi_h(a_t|s_t) \,d \bba_t d\bbs_t\\ \end{split} \end{equation} % Because $p(s_{u+1}|s_u,a_u)$ and $\pi_h(a_u|s_u)$ in \eqref{eqn_deltap} are density functions they integrate to one. Hence, the integral in the previous expression can be upper bounded by % \begin{equation} \begin{split} \int \left\|\Delta p_t(s,s^\prime,a,a^\prime)\right\|\pi_h(a_t|s_t) \,d \bba_t d\bbs_t \\\leq \int L_{ps}\left\|s-s^{\prime}\right\|+L_{pa}\left\|a-a^{\prime}\right\| ds_1\\ \leq |\ccalS| \left(L_{ps}\left\|s-s^{\prime}\right\|+L_{pa}\left\|a-a^{\prime}\right\|\right), \end{split} \end{equation} % where $| \ccalS|$ is the measure of the set $\ccalS$. Then, one can further upper bound \eqref{eqn_aux_dif_Q} by % \begin{equation} \begin{split} \left\| Q^\prime(s,a) - Q^\prime(s^\prime,a^\prime)\right\| \leq L_{r s}\left\|s-s^\prime \right\|+L_{r a}\left\|a-a^\prime \right\|\\ +\sum_{t=1}^\infty \gamma^t B_r|\ccalS| \left(L_{ps}\left\|s-s^{\prime}\right\|+L_{pa}\left\|a-a^{\prime}\right\|\right). \end{split} \end{equation} % Because the sum of the geometric yields $\gamma/(1-\gamma)$, it follows that $Q^\prime(s,a)$ satisfies % \begin{equation}\label{eqn_q_prime_lipschitz} \left\| Q^\prime(s,a) - Q^\prime(s^\prime,a^\prime)\right\| \leq L_{Qs}\left\|s-s^\prime \right\|+L_{Qa}\left\|a-a^\prime \right\|, \end{equation} % with $L_{Qs}=L_{rs}+\frac{\gamma B_r}{1-\gamma}L_{ps} |\ccalS|$ and $L_{Qa}=L_{ra}+\frac{\gamma B_r}{1-\gamma}L_{pa} |\ccalS|$. We next show that $h$ is Lipschitz. Using the reproducing property of the kernel, we can write the difference between $h(s)$ and $h(s^\prime)$ as \begin{equation} h(s)-h(s^\prime) = \left\langle h, \kappa(s,\cdot)-\kappa(s^\prime,\cdot)\right\rangle. \end{equation} % Using the Cauchy-Schwartz inequality we can upper bound the previous inner product by % \begin{equation} \left\|h(s)-h(s^\prime)\right\| \leq \left\|h\right\| \sqrt{\kappa(s,s)+\kappa(s^\prime,s^\prime)-2\kappa(s,s^\prime)} \end{equation} % Let us define $f(s,s^\prime) = \sqrt{\kappa(s,s)+\kappa(s^\prime,s^\prime)-2\kappa(s,s^\prime)}$ and show that it is Lipschitz. To do so, use the following change of variables {$u=\Sigma_\ccalH^{-1/2}\left(s-s^\prime\right)$} and write $f(u)$ as follows % \begin{equation} f(u) = \sqrt{2} \sqrt{1-e^{-\left\|u\right\|^2/2}}. \end{equation} Then, the gradient of $f(u)$ yields % \begin{equation}\label{eqn_gradient_aux_f} \nabla f(u) = \frac{1}{\sqrt{2}}\frac{e^{-\left\|u\right\|^2/2}u}{\sqrt{1-e^{-\left\|u\right\|^2/2}}}. \end{equation} % Notice that the only point where the function might not be bounded is when $u=0$, since the limit of the denominator is zero. To show that this is not the case, observe that a second order Taylor approximation of that term yields % \begin{equation} 1-e^{-\left\|u\right\|^2/2} = \frac{1}{2}\left\|u\right\|^2 +o(\left\|u\right\|^2), \end{equation} % where $o(\left\|u\right\|^2)$ is a function such that $\lim_{\left\|u\right\| \to 0} o(\left\|u\right\|^2)/\left\|u\right\|^2=0$. Thus we have that % \begin{equation} \begin{split} \lim_{\left\|u\right\| \to 0} \left\|\nabla f(u)\right\| &= \lim_{\left\|u\right\|\to 0} \frac{e^{-\left\|u\right\|^2/2}\left\|u\right\|}{\left\|u\right\|}=1 \end{split} \end{equation} % It can be shown that the gradient of $\left\|\nabla f(u)\right\|$ is always differentiable except at $u=0$ and it never attains the value zero except for at the limit when $\left\|u\right\|\to \infty$. This means, that there are no critical points of $\left\|\nabla f(u)\right\|$ except at infinity. On the other hand it follows from \eqref{eqn_gradient_aux_f} that $\lim_{\left\|u\right\| \to \infty} \left\|\nabla f(u)\right\| =0$, so, the critical point at infinity is a minimum. Thus, the maximum norm of $\nabla f(u)$ is attained at $u=0$ and it takes the value $1$. Thus $f(u)$ is Lipschitz with constant $1$. Use the fact that $f(0)=0$ to bound % \begin{equation} \begin{split} \left|f(u) \right| &\leq \left\|u\right\| = \left\|\Sigma_{\ccalH}^{-1/2}(s-s^\prime)\right\| \\ & \leq \lambda_{\min}(\Sigma_\ccalH)^{-1/2}\left\|s-s^\prime\right\|. \end{split} \end{equation} % The latter shows that $h(s)$ is Lipschitz with constant $L_h:=\left\|h\right\|\lambda_{\min}(\Sigma_\ccalH)^{-1/2}$. We next use this result to complete the proof that $Q^\prime(s)$ is Lipschitz. From its definition (cf., \eqref{eqn_q_prime_def}) and the fact that its Lipschitz (cf., \eqref{eqn_q_prime_lipschitz}) we have that % \begin{equation} \begin{split} \left\| Q^\prime(s)-Q^\prime(s^\prime)\right\| \leq L_{Q_s}\left\|s-s^\prime\right\| + L_{Q_a}\left\|h(s)-h(s^\prime)\right\|. \end{split} \end{equation} % Because $h(s)$ is Lipschitz it follows that \begin{equation} \begin{split} \left\| Q^\prime(s)-Q^\prime(s^\prime)\right\| \leq (L_{Q_s}+L_{Q_a}L_h)\left\|s-s^\prime\right\|. \end{split} \end{equation} This completes the proof of the first claim of the proposition. To show that $D(s)$ is bounded consider its norm. Using its expression in \eqref{eqn_D_change_variable} it is possible to uper bound it as % \begin{equation} \left\|D(s)\right\| \leq \mathbb{E}\left\| Q\left(s,h(s)+\Sigma^{1/2}\zeta\right)\zeta\right\|. \end{equation} % Since $|Q(s,a)|<B_r/(1-\gamma)$ (cf., Lemma 3 \cite{paternain2018stochastic}) it follows that % \begin{equation} \begin{split} \left\|D(s)\right\| &\leq \frac{B_r}{1-\gamma}\mathbb{E} \left\|\zeta\right\| = \frac{\sqrt{2}B_r}{1-\gamma}\frac{\Gamma\left(\frac{p+1}{2}\right)}{\Gamma\left(\frac{p}{2}\right)}, \end{split} \end{equation} % where $\Gamma$ is the Gamma function. \end{proof} To complete the proof of Lemma \ref{lemma_lipshitz} observe that we can write the difference \begin{equation} \begin{split} \left\|D(s)\rho_{s_0}(s) - D(s^\prime)\rho_{s_0}(s^\prime)\right\| \leq \left\|D(s)\rho_{s_0}(s)-D(s)\rho_{s_0}(s^\prime)\right\|\\ +\left\|D(s)\rho_{s_0}(s^\prime)-D(s^\prime)\rho_{s_0}(s^\prime)\right\|. \end{split} \end{equation} Using the Lipschitz continuity and the boundedness of both $D(s)$ and $\rho_{s_0}(s)$ it follows that\begin{equation} \begin{split} \left\|D(s)\rho_{s_0}(s) - D(s^\prime)\rho_{s_0}(s^\prime)\right\| \leq B_DL_p\left\|s-s^\prime\right\|\\ +B_{\rho}L_D\left\|s^\prime-s\right\|. \end{split} \end{equation} This completes the proof of the lemma. \section{Conclusion} We have considered the problem of learning a policy that belongs to a RKHS in order to maximize the functional defined by the expected discounted cumulative reward that an agent receives. In particular, we presented a fully online algorithm that accumulates at the critical points of the value function and keeps the model order of the representation of the function bounded for all iterations. The algorithm uses unbiased estimates of the gradient of the functionals conditioned at the current state that can be achieved in finite time. We establish that these gradients are also ascent directions for the initial value function for Gaussian kernels with small enough bandwidth. Therefore, by updating the policy following such gradients the value of the initial value function is increased in expectation at each iteration, when the step size and compression budget are small enough. { We tested this algorithm in a navigation and surveillance problem whose cyclic nature highlights the ability to operate in a non stationary setup. The surveillance task is carried out while by training in a fully online fashion, without the need of episodic restarts. With this experiment we also corroborated our claim in Theorem \ref{theo_convergence} regarding the ascent directions of the stochastic gradients.} \section{Convergence Analysis of Online Policy Gradient}\label{sec_convergence} Let $\left(\Omega,\ccalF,P\right)$ be a probability space and define the following sequence of increasing sigma-algebras $\left\{\emptyset, \Omega \right\} = \ccalF_0 \subset\ccalF_1 \subset \ldots \subset \ccalF_k \subset \ldots \subset \ccalF_{\infty}\subset \ccalF$, where for each $k$ we have that $\ccalF_k$ is the sigma algebra generated by the random variables $h_0,\ldots,h_k$. For the purpose of constructing a submartingale that will be used in the proof of convergence, we provide a lower bound on the expectation of random variables $U_{s_0}(h_{k+1})$ conditioned to the sigma field $\ccalF_k$ in the next Lemma \begin{lemma}\label{lemma_supermartingale_pars} % Choosing the compression budget $\epsilon_{K} = K\eta$ with $K>0$, the sequence of random variables $U(h_k)$ satisfies the following inequality \begin{equation}\label{eqn_supermartingale_equation_pars} \begin{split} \mathbb{E}\left[{U_{s_0}(h_{k+1})|\ccalF_k}\right] \geq U_{s_0}(h_k)- {\frac{\eta^2}{Z}} C_1-{\frac{\eta^3}{Z^{3/2}}}C_2\\ -\left\|\nabla_h U_{s_0}(h_k)\right\|_\ccalH K\eta +\eta\left<\nabla_h U_{s_0}(h_k),\nabla_h U_{s_k}(h_k)\right>_\ccalH, \end{split} \end{equation} where $C_1$ and $C_2$ are the following positive constants \begin{equation}\label{eqn_bound_for_radius_convergence_1} C_1 = L_1\left(\sigma^2+2K\sigma +K^2\right) \end{equation} and \begin{equation}\label{eqn_bound_for_radius_convergence_2} C_2 =L_2\left(\sigma^2+2K\sigma +K^2\right)^{3/2}, \end{equation} where $L_1$ and $L_2$ are given by \begin{equation}\label{eqn_grad_lipschitz} L_1 = B_r\frac{(1-\gamma+p(1+\gamma))}{\lambda_{\min}{\Sigma}(1-\gamma)^2}, L_2 = B_r\frac{(1+p)\sqrt{p}}{\lambda_{\min}(\Sigma)^{3/2}(1-\gamma)^3}, \end{equation} and \begin{equation}\label{eqn_sigma_moment} \sigma = \frac{(3\gamma)^{1/3}}{\lambda_{\min}(\Sigma^{1/2})(1-\gamma)^2}\left(4\frac{\Gamma(2+p/2)}{\Gamma(p/2)}\right)^{1/4}. \end{equation} \end{lemma} \begin{proof} Start by writing the Taylor expansion of $U_{s_0}(h_{k+1})$ around $h_k$ % \begin{equation} \begin{split} U_{s_0}(h_{k+1})= U_{s_0}(h_k)+\left<\nabla_h U_{s_0}(f_k,\cdot),h_{k+1}-h_k\right>_{\ccalH}. \end{split} \end{equation} % where $f_k = \lambda h_k +(1-\lambda)h_{k+1}$ with $\lambda\in[0,1]$. From \cite[Lemma 5]{paternain2018stochastic} we have that % \begin{equation}\label{eqn_lipschitz_nabla_U} \left\| \nabla_h U_{s_0}(g)-\nabla_hU_{s_0}(h)\right\|_{\ccalH} \leq L_1\left\|g-h\right\|_{\ccalH}+L_2\left\|g-h\right\|_{\ccalH}^2, \end{equation} % with $L_1$ and $L_2$ being the constants in \eqref{eqn_grad_lipschitz}. Adding and subtracting $\left<\nabla_h U_{s_0}(h_k,\cdot),h_{k+1}-h_k\right>_{\ccalH}$ to the previous expression, using the Cauchy-Schwartz inequality and \eqref{eqn_lipschitz_nabla_U} we can re write the previous expression as \begin{equation} \begin{split} U_{s_0}(h_{k+1}) &= U_{s_0}(h_k)+\left<\nabla_h U_{s_0}(h_k,\cdot),h_{k+1}-h_k\right>_{\ccalH} \\ &+\left<\nabla_h U_{s_0}(f_k,\cdot)-\nabla_hU_{s_0}(h_k,\cdot),h_{k+1}-h_k\right>_{\ccalH}\\ & \geq U_{s_0}(h_k)+\left<\nabla_h U_{s_0}(h_k,\cdot),h_{k+1}-h_k\right>_{\ccalH} \\ &-L_1\left\|h_{k+1}-h_k\right\|_{\ccalH}^2-L_2\left\|h_{k+1}-h_k\right\|_{\ccalH}^3. \end{split} \end{equation} % Let us consider next the conditional expectation of the random variable $U_{s_0}(h_{k+1})$ with respect to the sigma-field $\ccalF_k$. Combine the monotonicity and the linearity of the expectation with the fact that $h_k$ is measurable with respect to $\ccalF_k$ to write % \begin{equation}\label{eqn_first_supermartingale_bound_pars} \begin{split} \mathbb{E}\left[{U_{s_0}(h_{k+1})|\ccalF_k}\right] \geq U_{s_0}(h_k)\\ +\left<\nabla_h U_{s_0}(h_k,\cdot),\mathbb{E}\left[h_{k+1}-h_k|\ccalF_k\right]\right>_{\ccalH} \\ -L_1\mathbb{E}\left[\left\|h_{k+1}-h_k\right\|_{\ccalH}^2|\ccalF_k\right]-L_2\mathbb{E}\left[\left\|h_{k+1}-h_k\right\|_{\ccalH}^3|\ccalF_k\right]. \end{split} \end{equation} % Using the result of Proposition \ref{prop_error_bound} we can write the expectation of the quadratic term in the right hand side of \eqref{eqn_first_supermartingale_bound_pars} as % \begin{equation} \begin{split} L_1\mathbb{E}\left[\left\|h_{k+1}-h_k\right\|_{\ccalH}^2|\ccalF_k\right] \\ \leq L_1\eta^2 \mathbb{E}\left[\left\|\hat{\nabla}_h U_{s_k}(h_k,\cdot)\right\|_{\ccalH}^2|\ccalF_k\right]+L_1\epsilon_{K}^2 \\ +2L_1\eta\epsilon_{K}\mathbb{E}\left[\left\|\hat{\nabla}_h U_{s_k}(h_k,\cdot)\right\|_{\ccalH}|\ccalF_k\right] , \end{split} \end{equation} % Using the bounds on the moments of the estimate (cf., \cite[Lemma 6]{paternain2018stochastic}), the previous expression can be upper bounded by % \begin{equation} \begin{split} L_1\mathbb{E}\left[\left\|h_{k+1}-h_k\right\|_{\ccalH}^2|\ccalF_k\right] &\leq \eta^2L_1\left(\sigma^2+2\frac{\epsilon_{K}}{\eta}\sigma +\frac{\epsilon_{K}^2}{\eta^2}\right). \end{split} \end{equation} % where $\sigma$ is the constant in \eqref{eqn_sigma_moment}. Choosing the compression budget as $\epsilon_{K} = K \eta$ and using the definition of $C_1$ in \eqref{eqn_bound_for_radius_convergence_1} it follows that \begin{equation} L_1\mathbb{E}\left[\left\|h_{k+1}-h_k\right\|_{\ccalH}^2|\ccalF_k\right] = \eta^2L_1\left(\sigma^2+2K\sigma +K^2\right)=\eta^2 C_1. \end{equation} % Likewise, we have that % \begin{equation} \begin{split} L_2\mathbb{E}\left[\left\|h_{k+1}-h_k\right\|_{\ccalH}^3|\ccalF_k\right] &\leq \eta^3 L_2\left(\sigma^2+2\frac{\epsilon_{K}}{\eta}\sigma +\frac{\epsilon_{K}^2}{\eta^2}\right)^{3/2}\\ &= \eta^3 L_2\left(\sigma^2+2K\sigma +K^2\right)^{3/2} \\ &= \eta^3C_2. \end{split} \end{equation} % Replacing the previous two bounds regarding the moments of $\left\|h_{k+1}-h_k\right\|$ in \eqref{eqn_first_supermartingale_bound_pars} reduces to \begin{equation} \begin{split} \mathbb{E}\left[{U(h_{k+1})|\ccalF_k}\right] &\geq U(h_k)-\eta^2C_1-\eta^3C_2\\ & +\left<\nabla_h U(h_k),\mathbb{E}\left[h_{k+1}-h_k|\ccalF_k\right]\right>_{\ccalH}. \end{split} \end{equation} % Using the result of Proposition \ref{prop_error_bound} and the fact that $\hat{\nabla}_hU_{s_k}(h_k)$ is unbiased (cf., Proposition \ref{prop_unbiased_grad}) we can write the inner product in the previous equation as % \begin{equation} \begin{split} \left<\nabla_h U_{s_0}(h_k),\mathbb{E}\left[h_{k+1}-h_k|\ccalF_k\right]\right>_{\ccalH} =\\ \eta\left<\nabla_h U_{s_0}(h_k),\nabla_hU_{s_k}(h_k)\right>_{\ccalH} +\left<\nabla_h U_{s_0}(h_k), b_k\right>_{\ccalH}. \end{split} \end{equation} % The proof is then completed using the Cauchy-Schwartz inequality and fact that the norm of the bias is bounded by $\epsilon_{K} = K\eta$ (cf., Proposition \ref{prop_error_bound}). % \end{proof} The previous lemma establishes a lower bound on the expectation of $U_{s_0}(h_{k+1})$ conditioned to the sigma algebra $\ccalF_k$. This lower bound however, is not enough for $U_{s_0}(h_k)$ to be a submartingale, since the sign of the term added to $U_{s_0}(h_k)$ in the right hand side of \eqref{eqn_supermartingale_equation_pars} is not necessarily positive. The origin of this is threefold. The first two reasons stem from algorithmic reasons. These are that we are using the estimate of $\nabla_hU_{s_k}(h_k)$ to ascend on the functionial $U_{s_0}(h)$ -- which does not guarantee the inner product to be always positive -- the bias that results from projecting into a lower dimension via the KOMP algorithm as stated in Proposition \ref{prop_error_bound}. The third reason comes from the analysis in Lemma \ref{lemma_supermartingale_pars} where we bounded the value of the functional using a first order approximation. To overcome the first limitation we will use the result from Theorem \ref{prop_all_gradients} that guarantees that the inner product in the right hand side of \eqref{eqn_supermartingale_equation_pars} is lower bounded by $\varepsilon\beta_{\rho}/(2B_\rho)$ as long as $\left\|\nabla_h U_{s_0}(h)\right\|^2>\varepsilon$. The latter suggests that the definition of the following stopping time is necessary for the analysis \begin{equation}\label{eqn_stopping_time} N = \min_{k\geq 0} \left\{\left\|\nabla_h U_{s_0}(h_{k},\cdot)\right\|_{\ccalH}^2 \leq \varepsilon \right\}. \end{equation} % We will show that by choosing the compression factor $\epsilon_{K}$ and the step size sufficiently small we can overcome the other two limitations and establish that $U_{s_0}(h_k)$ is a submartingale as long as $k<N$. To be able to use the result of Theorem \ref{prop_all_gradients} we require, condition \eqref{eqn_kernel_condition} to be satisfied. As previously explained, this requires the norm of $h$ not to grow unbounded, yet due to the stochastic nature of the update there is no guarantees that this will be the case. We assume, however, that policies with infinite norm are poor policies which leads to the conclusion that if the norm of the gradient is not too small, then it has to be the case that the norm of $h$ is bounded. We formalize these ideas next. { \begin{assumption}\label{assumption_large_h} For every $\ccalH$ it follows that $\lim_{\left\|h\right\|\to \infty} U_{s_0}(h) = \min_{h\in\ccalH} U_{s_0}(h)$. \end{assumption} } { \begin{lemma}\label{lemma_bound_h} For every $\varepsilon>0$ there exists a constant $B_h(\varepsilon)$ such that if $\left\|\nabla_h U_{s_0}(h)\right\|^2 \geq \varepsilon$ then $ \left\| h\right\| \leq B_h(\varepsilon)$. \end{lemma} \begin{proof} Since the function $U_{s_0}(h)$ is bounded (cf., \cite[Lemma 1]{paternain2018stochastic}), Assumption \ref{assumption_large_h} implies that $\lim_{\left\|h\right\|\to \infty} \nabla_hU_{s_0}(h) = 0$ and therefore for every $\varepsilon>0$ there exists $B_h(\varepsilon)>0$ such that if $\left\|h\right\| > B_h(\varepsilon)$ then $\left\|\nabla_hU_{s_0}(h)\right\| <\varepsilon$. Hence it has to be the case that if $\left\|\nabla_hU_{s_0}(h)\right\|^2 \geq \varepsilon$, then $\left\|h\right\| \leq B_h(\varepsilon)$. \end{proof} } As previously discussed to guarantee that $U_{s_0}(h_k)$ is a submartingale we need to choose the compression budget $\epsilon_{K}$ and the step-size $\eta$ small enough. In particular observe that the compression budget multiplies a term that depends on the norm of the gradient in \eqref{eqn_supermartingale_equation_pars}. Hence, to be able to guarantee that reducing the compression budget is enough to have a submartingale we require that the norm of the gradient of the value function is bounded. This is the subject of the following lemma. % \begin{lemma}\label{lemma_bound_nabla_U} The norm of the gradient of $\nabla_h U_{s_0}(h)$ is bounded by $B_{\nabla}$ where % \begin{equation} B_{\nabla}:= \frac{\sqrt{p}B_r}{(1-\gamma)^2\lambda_{\min}\Sigma^{1/2}}. \end{equation} \end{lemma} \begin{proof} Use \eqref{eqn_nabla_U}, the fact that $\left|Q(s,a;h)\right|\leq B_r/(1-\gamma)$ (cf., \cite[Lemma 1]{paternain2018stochastic}) and that $\left\|\kappa(s,\cdot)\right\|= 1$ to upper bound the norm of $\nabla_h U_{s_0}(h)$ by % \begin{equation} \left\|\nabla_hU_{s_0}(h)\right\|^2\leq \frac{B_r^2}{(1-\gamma)^4 }\mathbb{E}\left[\left\|\Sigma^{-1}(a-h(s))\right\|^2|h\right]. \end{equation} % Since the action a is drawn from a normal distribution with mean $h(s)$ and covariance matrix $\Sigma$ it follows that $\left\|\Sigma^{-1/2}(a-h(s))\right\|^2$ is a $\chi^2$ distribution and thus its expectation is $p$. Hence, the above expectation is bounded by $p\lambda_{\min}(\Sigma)^{-1}$. This completes the proof of the result. \end{proof} % We are now in conditions of introducing the convergence of the online policy gradient algorithm presented in Section \ref{sec_online} to a neighborhood of the critical points of the value functional $U_{s_0}(h)$. In addition, the update is such that it guarantees that the model order remains bounded for all iterations. % \begin{theorem}\label{theo_convergence} Let Assumptions \ref{assumption_reward_function}--\ref{assumption_large_h} hold. For any $\varepsilon>0$ chose $K$ such that % \begin{equation}\label{eqn_compression_budget} K<\frac{\varepsilon}{2B_{\nabla}}\frac{\beta_{\rho}}{B_\rho}, \end{equation} % algorithm step-size $\eta>0$ such that % \begin{equation}\label{eqn_step_max} \eta\leq \frac{\sqrt{C_1^2+4C_2\left(\frac{\varepsilon \beta_\rho}{2 B_\rho}-B_{\nabla}K\right)}-C_1}{2C_2}. \end{equation} % and compression budget of the form $\epsilon_{K} = K\eta$. Under the hypotheses of Lemma \ref{lemma_lipshitz}, and for any kernel such that $\Sigma_{\ccalH}$ verifies \eqref{eqn_kernel_condition}, the sequence of policies that arise from Algorithm \ref{alg_online_policy_gradient} satisfy that $\liminf_{k\to\infty}\left\|\nabla_hU_{s_0}(h_k)\right\|^2 <{\varepsilon}$. In addition, let $M_k$ be the model order of $h_k$, i.e., the number of kernels which expand $h_k$ after the pruning step KOMP. Then, there exists a finite upper bound $M^\infty$ such that, for all $k\geq 0$, the model order is always bounded as $M_k\leq M^\infty$. \end{theorem} \begin{proof} Define the following sequence of random variables % \begin{equation} V_k=\left(U(h^\star)-U(h_{k})\right)\mathbbm{1}(k\leq N), \end{equation} % with $\mathbbm{1}(\cdot)$ being the indicator function and $N$ the stopping time defined in \eqref{eqn_stopping_time}. We next work towards showing that $V_k$ is a non-negative submartingale. Because $U(h^\star)$ maximizes $U(h)$, $V_k$ is always non-negative. In addition $V_k\in \ccalF_k$ since $U(h_k)\in\ccalF_k$ and $\mathbbm{1}(k\leq N)\in \ccalF_{k}$. Thus, it remains to be shown that $\mathbb{E}[V_{k+1} | \ccalF_k] \leq V_k$. Notice that for any $k> N$ it follows that $\mathbbm{1}(k\leq N) = 0$ and hence $V_k = 0$. Thus we have that $V_{k+1}= V_k$ for all $k\geq N$. We are left to show that $\mathbb{E}[V_{k+1} | \ccalF_k] \leq V_k$ for $k\leq N$. Using the result of Lemma \ref{lemma_supermartingale_pars} we can upper bound $\mathbb{E}[V_{k+1} | \ccalF_k]$ as % \begin{equation} \begin{split} \mathbb{E}[V_{k+1} | \ccalF_k] \leq V_k +{{\eta^2}}C_1+{{\eta^3}}C_2+K\eta \left\|\nabla_hU_{s_0}(h_k)\right\| \\ -\eta\left<\nabla_hU_{s_0}(h_k),\nabla_hU_{s_k}(h_k) \right>_{\ccalH}. \end{split} \end{equation} % Since we have that $\left\|\nabla_hU_{s_0}(h_k)\right\|^2 \geq \varepsilon$ by virtue of Assumption \ref{assumption_large_h} it follows that {$\left\|h\right\|_\ccalH \leq B_h(\varepsilon)$.} Therefore, there exists some Hilbert Space for which condition \eqref{eqn_kernel_condition} holds and the result of Theorem \ref{prop_all_gradients} implies that the inner product in the right hand side of the previous expression is lower bounded by $\varepsilon\beta_\rho/(2B_{\rho})$. In addition, the norm of $\nabla_hU_{s_0}(h_k)$ is bounded by virtue of Lemma \ref{lemma_bound_nabla_U}. Hence, the previous expression can be further upper bounded by % \begin{equation}\label{eqn_submartingale} \begin{split} \mathbb{E}[V_{k+1} | \ccalF_k] &\leq V_k +{\eta^2}C_1+\eta^3C_2+\eta K B_{\nabla} -\eta\frac{\varepsilon}{2}\frac{\beta_\rho}{B_\rho} \\ &= V_k +{\eta}\alpha(K,\eta), \end{split} \end{equation} % where we define $\alpha(K,\eta)$ as \begin{equation}\label{eqn_alpha} \alpha(K,\eta) := K B_{\nabla}-\frac{\varepsilon}{2}\frac{\beta_\rho}{B_\rho}+\eta C_1+\eta^2C_2. \end{equation} % With the condition for the compression factor satisfying \eqref{eqn_compression_budget} we guarantee that the sum of the first two terms on the right hand side of \eqref{eqn_alpha} is negative. The latter is sufficient to guarantee that the expression is negative for all $\eta$ satisfying \eqref{eqn_step_max}. This completes the proof that $V_k$ is a non-negative submartingale. Thus, $V_k$ converges to random variable $V$ such that $\mathbb{E}[V]\leq \mathbb{E}[V_0]$ (see e.g., \cite[Theorem 5.29]{durrett2010probability}). Then, by unrolling \eqref{eqn_submartingale} we obtain the following upper bound for the expectation of $V_{k+1}$ % \begin{equation} \mathbb{E}\left[V_{k+1}\right] \leq V_0 + \alpha \eta\mathbb{E}N. \end{equation} % Since $V_{k+1}$ is bounded the Dominated Convergence Theorem holds and we have that % \begin{equation} \mathbb{E}[V]= \lim_{k \to\infty} \mathbb{E}\left[V_{k+1}\right] \leq V_0 + \alpha \eta\mathbb{E}N. \end{equation} % Since $\alpha<0$, rearranging the terms in the previous expression we can upper bound $\mathbb{E}N$ by % \begin{equation} \mathbb{E}N \leq \frac{\mathbb{E}{V}-V_0}{\eta \alpha}. \end{equation} % Therefore it must be case that $P(N=\infty)=0$. Which implies that the event $\left\| \nabla_h U_{s_0}(h_k)\right\| < \varepsilon$ occurs infinitely often. Thus completing the proof of the result. It remains to be shown that the model order of the representation is bounded for all $k$. The proof of this result is identical to that in \cite[Theorem 3]{koppel2016parsimonious}. \end{proof} The previous result establishes the convergence to a neighborhood of the critical points of $U_{s_0}(h)$ of the online gradient ascent algorithm presented in Section \ref{sec_online}. For such result to hold, we require that the kernel width, the compression budget and the step size to be small enough. In addition, the compression introduced by KOMP guarantees that the model order of the function $h_k$ remains bounded for all $k\geq 0$. In the next section we explore the implications of these theoretical results in {a cyclic navigation problem.} \section{Introduction}\label{sec_intro} Reinforcement learning (RL) problems--which is the interest in this paper--are a special setting for the analysis of Markov decision processes (MDPs) in which both the transition probabilities are unknown. The agent interacts with the environment and observes samples of a reward random variable associated to a given state and action pair \cite{sutton1998reinforcement}. These rewards samples are used to update the policy of the agent so as to maximize the Q- function, defined as the expected cumulative reward conditioned to the current state and action. The solutions to RL problems are divided in two main approaches. On one hand, those approaches that aim to learn the Q-function to then choose the action that for the current state maximizes said function. Among these algorithms the standard solution is Q-learning \cite{watkins1992q}, whose earlier formulations were applicable in scenarios where the state and the action are discrete. The aforementioned algorithms suffer from the \emph{curse of dimensionality}, with complexity growing exponentially with the number of actions and states \cite{friedman2001elements}. This is of particular concern in problems where the state and the actions are continuous spaces, and thus, any reasonable discretization leads to a large number of states and possible actions. A common approach to overcome this difficulty is to assume that the Q-function admits a finite parameterization that can be linear \cite{sutton2009convergent}, rely on a nonlinear basis expansion \cite{bhatnagar2009convergent}, or be given by a neural network \cite{mnih2013playing}. Alternatively one can assume that the Q-function \cite{koppel2017breaking, tolstayanonparametric} belongs to a reproducing kernel Hilbert space. However, in these cases, maximizing the Q-function to select the best possible action is computationally challenging. Moreover, when using function approximations Q-learning may diverge \cite{baird1995residual}. This motivates the development of another class of algorithms that attempts to learn the optimal policy by running stochastic gradient ascent on the Q-function with respect to the policy parameters \cite{williams1992simple,sutton2000policy, deisenroth2013survey} or with respect to the policy itself in the case of non-parametric representations \cite{lever2015modelling,paternain2018stochastic}. These gradients involve the computation of expectations which requires knowledge of the underlying probabilistic model. With the goal of learning from data only, they provide unbiased estimates of the gradients which are used for stochastic approximation \cite{robbins1951stochastic}. One of the classic examples of estimates of the gradients used in discrete state-action spaces is REINFORCE \cite{williams1992simple}. Similar estimates can also be computed in the case of parametric \cite{baxter2001infinite} and non-parametric function approximations \cite{paternain2018stochastic}. Once these unbiased estimates have been computed convergence to the critical points can be established under a diminishing step-size as in the case in parametric optimization \cite{bertsekas1999nonlinear}. A drawback of said estimators is that they have high variance and therefore they suffer from slow convergence. This issue can be mitigated using Actor-Critic methods \cite{konda2000actor,bhatnagar2009natural,degris2012off} to estimate the policy gradients. To compute these estimates however, one is required to re-initialize the system for every new iteration. Hence, limiting its application to episodic tasks \cite{williams1992simple, paternain2018stochastic}. A common workaround to this hurdle is to modify the value function so to consider the average rate of reward instead of the cumulative reward \cite[Chapter 13]{sutton1998reinforcement}. This formulation also requires that under every policy the MDP converges to a steady state distribution that is independent of the initial state. The convergence to a stationary distribution is restrictive in many cases, as we discus in Section \ref{sec_problem_formulation}, since it prevents the agents from considering policies that result in cyclic behaviors for instance. Not being able to reproduce these behaviors is a drawback for problems like surveillance where the policy that the agent should follow is one that visits different points of interest. Moreover, even for problems where the target is a specific state, and thus the convergence to the stationary distribution is a reasonable assumption, the average reward formulation may modify the optimal policies in the sense that it is a formulation that ignores transient behaviors. We discuss this issue in more detail also in Section \ref{sec_problem_formulation}. Given the offline policy gradient algorithm in \cite{paternain2018stochastic}, we aim to avoid the reinitialization requirement while keeping the cumulative reward as value function. In particular, we compute stochastic gradients as in \cite{paternain2018stochastic} which are guaranteed to be unbiased estimates of the gradient of the value function at the state that systems finds itself at the beginning of the iteration. Because this estimation requires rollouts at each iteration, the agent is in fact computing estimates of the gradients of value functions at different states. Building on our preliminary results \cite{paternain2019cdc}, we establish in Theorem \ref{prop_all_gradients} that the gradients of the value function at any state are also ascent directions of the value function at the initial state. Leveraging this result we address the convergence of the online policy gradient algorithm to a neighborhood of the critical points in Theorem \ref{theo_convergence}, hence dropping the assumption of the convergence to\textemdash and existence of\textemdash the stationary distribution over states for every intermediate policy. These results are backed by Proposition \ref{prop_common_critical_points}, which establishes that a critical point of the value function conditioned at the initial state is also a critical point for the value functions conditioned at states in the future, suggesting that the landscape of different value functions is still very similar. Finally, as an accessory computational refinement, we add a compression step to the online algorithm to reduce the number of kernels by trading-off a discretionary convergence error. This refinement uses Orthogonal Kernel Matching Pursuit \cite{koppel2016parsimonious}. Other than concluding remarks the paper ends with numerical experiments {where we consider an agent whose goal is to surveil a region of the space while having to visit often enough a charging station. } The cyclic nature of this problem evidences the ability of our algorithm to operate in a non stationary setup and carry the task by training in a fully online fashion, without the need of episodic restarts. The experiment is also useful to corroborate our theoretical findings about the ascending direction properties of stochastic gradients computed at different points of the trajectory. \subsubsection{#1}\vspace{-3\baselineskip}\color{black}\bigskip{\noindent \bf \thesubsubsection. #1.}} \newcommand{\myparagraph}[1]{\needspace{1\baselineskip}\medskip\noindent {\it #1.}} \newcommand{\myparagraphtc}[1]{\needspace{1\baselineskip}\medskip\noindent {\it #1.}\addcontentsline{toc}{subsubsection}{\qquad\qquad\quad#1}} \section{Numerical Experiments}\label{sec_numerical} Next we test the performance of our non-epsodic RL method in a suvelliance and navigation task. The setup includes an area in $\mathbb R^2$ with a point to be surveilled located at $x_g=[-1,-5]$ and a battery charger located at $x_b=[-1,5]$. These points are depicted in green and red, respectively, in Figure \ref{fig:trayectoria}. An agent starts moving from its initial point at $ x_0=[3,0]$, depicted in blue in figures \ref{fig:trayectoria} and \ref{fig:fases}, towards its goal at $x_g$. The agent model consist in second order point mass acceleration dynamics, with position $x\in\mathbb R^2$ and velocity $v\in\mathbb R^2$ as state variables. It also includes second order battery charging and discharging equations with state variables $b\in \mathbb R$ modeling the remaining charge of the battery, and $d\in \mathbb R$ representing the difference between charge levels at two consecutive time instants. The battery charges at a constant rate $\Delta B$ if the agent is located within a neighborhood of the battery charger, and discharges at the same rate $\Delta B$ otherwise. Vector $s=(x,v,b,d)$ collects all the state variables of this model. The reward is shaped so that the agent is stimulated to move towards the goal $x_g$ when $b$ is grater than or equal to $40\%$ of its full capacity and it is discharging $d<0$. And towards the battery charger $x_c$ if $b$ is lower than $40\%$ and discharging $d<0$, or if $b$ is lower than $90\%$ and charging $d>0$. The use of a second order model for the battery allow us to leave room for some hysteresis on the charging and discharging loop, so that the battery does not start discharging as soon as $b$ surpasses the $40\%$ level. Instead, it keeps charging until it reaches $90\%$ of its capacity before moving back towards the goal. A logarithmic barrier is added to the reward for helping the agent to avoid an elliptic obstacle centered at $x_0=[0,0]$ with horizontal and vertical axes of length $1.8$ and $0.9$, respectively Under these dynamics, the agent decides its acceleration $a_k\in\mathbb R^2$ using the randomized Gaussian policy $a_k\sim \pi_{h_k}(.|s_k)$ where the mean of $a_k\sim \pi_{h_k}(.|s_k) $ is the kernel expansion $h_k(s_k)$ updated via \eqref{eqn_stochastic_update}. The $Q$-function in step 7 of Algorithm \ref{alg_stochastic_gradient} is estimated as the sum of $T_Q$ consecutive rewards with $T_Q$ drawn from a geometric distribution of parameter $\gamma$. The Gaussian noise $n_k$ that is added to $h_k(s_k)$ in step 2 of Algorithm \ref{alg_stochastic_grad} is selected at random when $k$ is even, and equal to $n_k=-n_{k-1}$ when $k$ is odd. This is a practical trick to improve the ascending direction of the stochastic gradient without adding bias or violating the Gaussian model for the randomized policy $\pi_{h}(a|s)$, see \cite{paternain2018stochastic} for more details. Figure \ref{fig:trayectoria} shows the trajectory of the agent, with its color changing gradually from blue to red as it starts from $x_0$ and loops between $x_g$ and $x_b$. \begin{figure} \includegraphics[scale=0.2]{figures/trayectoriaGrid.png} \caption{Online cycling trajectory of an agent starting at $x_0=[3,0]$ with the goal of surveilling the location represented by a green point at $x_b=[-1,-5]$. The agent needs to recharge its battery when it discharges below $40\%$ of its maximum capacity, at the charger location $x_b=[-1,5]$ represented by the red point. When navigating towards $x_b$ the agent must avoid the ellipsoidal obstacle centered at $[-1,0].$ }\label{fig:trayectoria} \end{figure} The four stages of this looping trajectory are detailed in Figure \ref{fig:fases}, with Figure \ref{fig:fases} (left) showing the trace from $x_0$ to the neighborhood of $x_g$ which includes some initial exploring swings. Then the trajectory in \ref{fig:fases} (center left) starts when the agent's battery crosses the threshold of $40\%$. In this case the agent is rewarded for moving towards the charger and staying in its neighborhood until $b$ reaches $90\%$. The next stage in Figure \ref{fig:fases} (center right) starts when the battery level reaches $90\%$ and the agent moves back to the goal. And finally the trace in Figure \ref{fig:fases} (right) starts when the battery discharges under the safety level of $40\%$, moving back towards the charger and closing the loop. \begin{figure*} \centering \includegraphics[scale=0.1]{figures/fase1Grid.png} \includegraphics[scale=0.1]{figures/fase2Grid.png} \includegraphics[scale=0.1]{figures/fase3Grid.png} \includegraphics[scale=0.1]{figures/fase4Grid.png} \caption{Detail of the four stages of the online trajectory in Figure \ref{fig:trayectoria}. Trace from $x_0$ to the neighborhood of $x_g$ (left). Trace when the agent's battery crosses the threshold of $40\%$ (center left). Trace when the battery level reaches $90\%$ and the agent moves back to the goal (center right). Trace when the battery discharges under the safety level of $40\%$ (right). }\label{fig:fases} \end{figure*} This coherence between the battery level and the agent trajectories is further illustrated in figures \ref{fig:step} and \ref{fig:cycle}. Figure \ref{fig:step} depicts the battery level across iterations in time, alongside the vertical position of the agent. The vertical position shows {an oscillating step-response like behavior,} as the agent reaches the neighborhood of the goal and the charger sequentially and hovers around them. The battery level shows the desired hysteresis, transitioning according to the thresholds at $40\%$ and $90\%$ and depending on the charging slope. \begin{figure} \includegraphics[scale=0.2]{figures/step_response.png} \caption{Vertical position and battery charge as a function of the online gradient update index $k$. The horizontal dashed lines correspond to the positions of the goal and the charger, and to the battery safety and fully charged thresholds. The vertical dashed lines mark the transitions when the agent is directed to move to the charger or to the goal. } \label{fig:step} \end{figure} Such a loop is further evidenced in Figure \ref{fig:cycle}, which represents the agent's vertical position versus its battery level. The horizontal dashed lines represent the full charge and low battery thresholds, and the vertical dashed lines correspond to the positions of the goal and the charger. This figure shows how starting from $x_0$ the agent moves towards $x_g$ until it reaches the $40\%$ level, and then towards the charger hovering around it until the battery charge is $90\%$. Then it closes the loop by moving towards the goal and the charger sequentially while its battery charges and discharges. \begin{figure} \includegraphics[scale=0.2]{figures/cycle.png} \caption{Cyclic evolution of the agent's vertical position versus the battery charge. Horizontal dashed lines correspond to the positions of the goal and the charger, and vertical dashed lines represent the battery safety and fully charged thresholds. }\label{fig:cycle} \end{figure} Figure \ref{fig:rewards} is included to corroborate the theoretical findings of Section \ref{sec_important_properties}. More specifically, it depicts the evolution of $U_s(h_k)$ as a function of the online iteration index $k$. % The starting point $s$ in $U_s(h_k)$ is the same for all $k$, and it is selected as the state when the battery level crosses the line of $40\%$ for the first time. It corresponds to the location near $x_g$ where the stage 2 starts in Figure \ref{fig:fases}(b). For completeness $s=[x,v, b,d]$ with {$x=[-0.72,-4.58]$, $v=[-0.092,0.049]$, $b=39.99$, and $d=3\times 10^{-4}$.} The value function $U_{s}(h_k)$ is estimated using rewards obtained by an episodic agent that starts at $s$ and runs $N=100$ sample trajectories of length $T$ selecting actions according to the policy $h_k$, which is kept constant during the $T$ state transitions. These rewards are averaged according to \begin{equation} \hat U_s(h_k)=\frac{1}{N}\sum_{i=1}^N R_{ik} \label{eq:hatushk} \end{equation} where $R_{ik}=\sum_{t=0}^T \gamma^t r_{itk}$ and $r_{itk}$ is the instantaneous reward obtained by the episodic agent at time $t$, using policy $h_k$, over the sample trajectory $i$. These episodic trajectories are carried out for assessing performance of a fixed $h_k$, but the algorithm for updating these policies is non-episodic, as it evolves in the fully online fashion of \eqref{eqn_stochastic_update}. The horizon $T=100$ for these episodes was selected so that that the discarded tail of the geometric series becomes negligible, with $\gamma^T\simeq 2\times 10^{-5}$ staying under the noise deviation. It is remarkable that when the online agent travels through $s$ on its online journey of Figure \ref{fig:trayectoria}, the policy figures out how to increase the reward. And such a reward will not decrease when the policy is updated in the future. This is coherent with our theoretical findings in Theorem \ref{prop_all_gradients}, which states that gradients at future states are ascent directions for the value function at a previous state, that is $s$ in this case. As stated before, each point on the blue line in Figure \ref{fig:rewards} represents the mean of rewards in \eqref{eq:hatushk}, and it is accompanied by its deviation interval. Notice that, even if the improvement in reward is relative minor, at $0.3\%$, it is good enough to direct the agent towards the battery charger. This can be better seen in the next figure. \begin{figure} \includegraphics[scale=0.2]{figures/plot_s05497_desv1_kinter100_gamma09_trials100.png} \caption{Evolution of the mean accumulative reward in \eqref{eq:hatushk} as a function of the online iteration step $k$.} \label{fig:rewards} \end{figure} Figure \ref{fig:trayectoriaColor} shows five different trajectories starting at the same point $x=[-0.72,-4.58]$ represented by a blue dot. The trajectory that passes through the colored dots corresponds to an agent running our online algorithm, and coincides with part of the second stage in Figure \ref{fig:fases} (center left). Let $k_0$, $k_1$, $k_2$, and $k_3$ be the iteration indexes when the online agent reaches the points $x_{k_0}=x$, $x_{k_1}$, $x_{k_2}$, $x_{k_3}$, represented by the blue, cyan, green, and purple dots, respectively. At these iterations the agent produces policies $h_{k_0}$, $h_{k_1}$, $h_{k_2}$, and $h_{k_3}$. The blue, cyan, green, and purple lines in Figure \ref{fig:trayectoriaColor} represent the trajectories of an episodic agent starting at $x$ and navigating with constant policies $h_{k_0}$, $h_{k_1}$, $h_{k_2}$, and $h_{k_3}$, respectively. Figure \ref{fig:trayectoriaColor} corroborates that the policies improve as the online agent moves along its trajectory, allowing the episodic agent to navigate better. Indeed, at first the episodic agent only knows to go north west on the straight blue line, but eventually it manages to follow the purple line moving towards the charger and avoiding the obstacle. This apparent improvement in Figure \ref{fig:trayectoriaColor} is not reflected in a significant step increase in Figure \ref{fig:rewards}. This is because the forgetting factor $\gamma=0.9$ weights a few steps of the trajectory in the value function, and the fist steps are where the trajectories are not significantly separated. Overall, this numerical example shows that the algorithm developed in this paper is capable of learning how to navigate on a loop in between to goal locations, avoiding an obstacle, and following a cyclic trajectory that does not comply with the standard stationary assumptions in the literature. \begin{figure} \includegraphics[scale=0.2]{figures/trayectoriasColor.png} \caption{Trajectories of an episodic agent using four policies that are produced by the online agent when following the cyclic trajectory of Figure \ref{fig:trayectoria}. Each colored point represents a location $x_k$ in which the online agent updates policy to obtain $h_k$. The line of the corresponding color represents the trajectory of the episodic agent that uses the fixed policy $h_k$ to navigate from $x$ towards the charger. } \label{fig:trayectoriaColor} \end{figure} \section{Online Policy Gradient}\label{sec_online} \subsection{Stochastic Gradient Ascent}\label{sec_offline_alg} In order to compute a stochastic approximation of $\nabla_h U_{s_0}(h)$ given in \eqref{eqn_nabla_U} we need to sample from the distribution $\rho_{s_0}(s,a)$ defined in \eqref{eqn_discounted_distribution}. The intuition behind $\rho_{s_0}(s,a)$ is that it weights by $(1-\gamma)\gamma^t$ the probability of the system being at a specific state-action pair $(s,a)$ at time $t$. Notice that the weight $(1-\gamma)/\gamma^t$ is equal to the probability of a geometric random variable of parameter $\gamma$ to take the value $t$. Thus, one can interpret the distribution $\rho_{s_0}(s,a)$ as the probability of reaching the state-action pair $(s,a)$ after running the system for $T$ steps, with $T$ randomly drawn from a geometric distribution of parameter $\gamma$, and starting at state $s_0$. The geometric sampling transforms the discounted infinite horizon problem into an undiscounted episodic problem with random horizon (see e.g. \cite[pp.39-40]{bertsekas1996NDP}). This supports steps 2-7 in Algorithm \ref{alg_stochastic_grad} which describes how to obtain a sample $(s_T,a_T)\sim\rho_{s_0}(s,a)$. Then to compute an unbiased estimate of $\nabla_h U_{s_0}(h)$ (cf., Proposition \ref{prop_unbiased_grad}) one can substitute the sample $(s_T,a_T)$ in the stochastic gradient expression \begin{equation}\label{eqn_stochastic_gradient} \hat{\nabla}_h U_{s_0}(h,\cdot) = \frac{1}{1-\gamma}\hat{Q}(s_T,a_T;h)\kappa(s_T,\cdot)\Sigma^{-1}(a_T-h(s_T)), \end{equation} with $\hat Q(s_T,a_T;h)$ being an unbiased estimate of $Q(s_T,a_T;h)$. Algorithm \ref{alg_stochastic_grad} summarizes the steps to compute the stochastic approximation in \eqref{eqn_stochastic_gradient}. We claim that it is unbiased in Proposition \ref{prop_unbiased_grad} as long as the rewards are bounded. We formalize this assumption next as long with some other technical conditions required along the paper. \begin{assumption}\label{assumption_reward_function} There exists $B_r>0$ such that $\forall (s,a) \in \ccalS\times\ccalA$, the reward function $r(s,a)$ satisfies $|r(s,a)|\leq B_r$. In addition $r(s,a)$ has bounded first and second derivatives, with bounds $|\partial r(s,a)/ \partial s|\leq L_{rs}$ and $|\partial r(s,a)/\partial a |\leq L_{ra}$. \end{assumption} Notice that these assumptions are on the reward which is user defined, as such they do not impose a hard requirement on the problem. \begin{algorithm} \caption{StochasticGradient}\label{alg_stochastic_grad} \begin{algorithmic}[1] \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \Require $h$, $s_0$ \State Draw an integer $T$ form a geometric distribution with parameter $\gamma$, $P(T = t) = (1-\gamma)\gamma^t$ \State Select action $a_{0} \sim \pi_h(a|{s})$ \For {$t = 0,1,\ldots T-1 $} \State Advance system $s_{t+1} \sim P_{s_t\to s_{t+1}}^{a_t}$ \State Select action $a_{t+1} \sim \pi_h(a|{s_{t+1}})$ \EndFor \State Get estimate of $Q(s_T,a_T;h)$ \label{step_Q} \State Compute the stochastic gradient $\hat{\nabla}_hU(h,\cdot)$ as in \eqref{eqn_stochastic_gradient} \Return $\hat{\nabla}_hU(h,\cdot)$ \end{algorithmic}\label{alg_stochastic_gradient} \end{algorithm} \begin{proposition}[(Proposition 3 \cite{paternain2018stochastic})] \label{prop_unbiased_grad} The output $\hat{\nabla}_h U_{s_0}(h,\cdot)$ of Algorithm \ref{alg_stochastic_gradient} is an unbiased estimate of $\nabla_h U_{s_0}(h,\cdot)$ in \eqref{eqn_nabla_U}. \end{proposition} {An unbiased estimate of $Q(s_T,a_T)$ can be computed considering the cumulative reward from $t=T$ until a randomly distributed horizon $T_Q\sim geom(\gamma)$ (cf., Proposition 2 \cite{paternain2018stochastic}). The variance of this estimate may be high resulting on a slow convergence of the policy gradient algorithm (Algorithm \ref{alg_stochastic_grad}). For these reasons, the literature on RL includes several practical improvements. Variance can be reduced by including batch versions of the gradient method, in which several stochastic gradients are averaged before performing the update in \eqref{eqn_stochastic_gradient}. One particular case of a batch gradient iteration in \cite{paternain2018stochastic}, averages two gradients sharing the same state $s_i$ with stochastic actions. Other approaches include the inclusion of baselines \cite{williams1992simple} and actor critic methods \cite{konda2000actor,bhatnagar2009natural,degris2012off}. Irrespective of the form selected to estimate the $Q$ function with the estimate \eqref{eqn_stochastic_gradient} one could update the policy iteratively running stochastic gradient ascent} \begin{equation}\label{eqn_stochastic_update} h_{k+1} = h_k + \eta_k \hat{\nabla}_h U_{s_0}(h_k,\cdot), \end{equation} where $\eta_k>0$ is the step size of the algorithm. Under proper conditions stochastic gradient ascent methods can be shown to converge with probability one to the local maxima \cite{pemantle1990nonconvergence}. This approach has been widely used to solve parametric optimization problems where the decision variables are vectors in $R^n$ and in \cite{paternain2018stochastic} these results are extended to non-parametric problems in RKHSs. Observe however, that in order to provide an estimate of $\nabla U_{s_0}(h_k,\cdot)$, Algorithm \ref{alg_stochastic_grad} requires $s_0$ as the initial state. Hence, it is not possible to get estimates of the gradient without resetting the system to the initial state $s_0$, preventing a fully online implementation. {As discussed in Section \ref{sec_continuing}, this is a common challenge in continuing task RL problems and in general the alternative is to modify the objective the function and to assume the existence of a steady-state distribution to which the MDP converges (see e.g., \cite[Chapter 13]{sutton1998reinforcement} or \cite{degris2012off}), to make the problem independent of the initial state. In this work we choose to keep the objective \eqref{eqn_problem_statement} since the ergodicity assumption is not necessarily guaranteed in practice and the alternative formulation makes transient behaviors irrelevant, as it was also discussed in Section \ref{sec_continuing}. } Notice that, without loss of generality, Algorithm \ref{alg_stochastic_grad} can be initialized at state $s_k$ and its output becomes an unbiased estimate of $\nabla U_{s_k}(h_k,\cdot)$. The main contribution of this work is to show that the gradient of $U_{s_k}(h)$ is also an ascent direction for $U_{s_0}(h)$ (cf., Theorem \ref{prop_all_gradients}) and thus, these estimates can be used to maximize $U_{s_0}(h)$ hence allowing a fully online implementation. We describe the algorithm in the next section. \subsection{Online Implementation} As suggested in the previous section it is possible to compute unbiased estimates of $\nabla_h U_{s_k}(h_k)$ by running Algorithm \ref{alg_stochastic_gradient} with inputs $h_k$ and $s_k$. The state $s_k$ is defined for all $k\geq 1$ as the state resulting from running the Algorithm \ref{alg_stochastic_gradient} with inputs $h_{k-1}$ and $s_{k-1}$. This is, at each step of the online algorithm \textemdash which we summarize under Algorithm \ref{alg_online_policy_gradient}\textemdash the system starts from state $s_k$ and transits to a state $s_{T_k}$ following steps 3--6 of Algorithm \ref{alg_stochastic_gradient}. Then, it advances from $s_{T_k}$ to $s_{k+1}$ to perform the estimation of the $Q$-function, one that admits an online implementation, for instance by adding the rewards of the next $T_Q$ steps with $T_Q$ being a geometric random variable. The state $s_{k+1}$ is the initial state for the next iteration of Algorithm \ref{alg_online_policy_gradient}. \begin{algorithm} \caption{Online Stochastic Policy Gradient Ascent} \begin{algorithmic}[1] \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \Require step size $\eta_0$ \State \textit{Initialize}: $h_0=0$, and draw initial state $s_0$ \For{$k=0 \ldots$} \State Compute the stochastic gradient and next state:\\ $\left(\hat{\nabla}_h U(h_k,\cdot), s_{k+1} \right) = \textrm{StochasticGradient}(h_k, s_k)$ \State Stochastic gradient ascent step $$ \tilde{h}_{k+1} = h_k +\eta_k \hat{\nabla}_h U(h_k,\cdot) $$ \State Reduce model order $h_{k+1} =$ KOMP($\tilde{h}_{k+1},\epsilon_K$) \EndFor \end{algorithmic}\label{alg_online_policy_gradient} \end{algorithm} Notice that the update \eqref{eqn_stochastic_update} \textemdash step 5 in Algorithm \ref{alg_online_policy_gradient} \textemdash requires the introduction of a new element $\kappa(s_{T_k},\cdot)$ in the kernel dictionary at each iteration, thus resulting in memory explosion. {To overcome this limitation we modify the stochastic gradient ascent by introducing a projection over a RKHS of lower dimension as long as the induced error remains below a given compression budget. This algorithm, which runs once after each gradient iteration, prunes the kernel expansion that describes the policy $h$ to remove the kernels that are redundant up to an admissible error level $\epsilon_k>0$. The subroutine is known as Kernel Orthogonal Match and Pursuit (KOMP) \cite{vincent2002kernel} \textemdash step 6 in Algorithm \ref{alg_online_policy_gradient} The fundamental reason to do this pruning projection over a smaller subspace is that it allow us to control the model order of the policy $h_k$, as it is shown in Theorem \ref{theo_convergence}. However, the induced error translates into a bias on the estimate of $\nabla_h U_{s_k}(h,\cdot)$. We formalize this claim in the next proposition.} \begin{proposition}\label{prop_error_bound} The update of Algorithm \ref{alg_online_policy_gradient} is equivalent to running biased stochastic gradient ascent % \begin{equation}\label{eqn_error_bound} h_{k+1} = h_k +\eta \hat{\nabla}_h U_{s_k}(h,\cdot)+b_k, \end{equation} % with bias bounded by the compression budget $\epsilon_K$ for all $k$, i.e., $\left\|b_k\right\|_\ccalH<\epsilon_K$. \end{proposition} \begin{proof} The proof is identical to that in \cite[Proposition 5]{paternain2018stochastic}. \end{proof} As stated by the previous proposition the effect of introducing the KOMP algorithm is that of updating the policy by running gradient ascent, where now the estimate is biased. The later will prevent the algorithm to converge to a critical point of the value function. However, we will be able to establish convergence to a neighborhood of the critical point as long as the compression is such that the error introduced is not too large. A difference between the online algorithm and the offline one presented in \cite{paternain2018stochastic} is that even for a compression error of $\epsilon_K=0$ we cannot achieve exact convergence to the critical points, because the directions that are being used to ascend in the function $U_{s_0}(h)$ are in fact estimates of the gradients of $U_{s_k}(h)$. In the next section we discuss this in more detail and we establish that the inner product of gradients of $U_{s_k}(h)$ and $U_{s_0}(h)$ is positive when $h$ belongs to a properly selected Gaussian RKHS (Theorem \ref{prop_all_gradients}). \section{Problem Formulation}\label{sec_problem_formulation} In this work we are interested in the problem of finding a policy that maximizes the expected discounted cumulative reward of an agent that chooses actions sequentially. Formally, let us denote the time by $t \in \left\{\{0\},\mathbb{N} \right\}$ and let $\ccalS \subset \mathbb{R}^n$ be a compact set denoting the state space of the agent, and $\ccalA = \mathbb{R}^p$ be its action space. The transition dynamics are governed by a conditional probability $ P_{s_t\to s_{t+1}}^{a_t}(s) :=p(s_{t+1}=s|(s_t,a_t) \in \ccalS\times \ccalA)$ satisfying the Markov property, i.e., $p(s_{t+1}=s\big|(s_u,a_u) \in \ccalS\times \ccalA, \forall u\leq t) =p(s_{t+1}=s|(s_t,a_t) \in \ccalS\times \ccalA).$ % The policy of the agent is a multivariate Gaussian distribution with mean $h: \ccalS \to \ccalA$. The later map is assumed to be a vector-valued function in a vector-valued RKHS $\ccalH$. We formally define this notion next, with comments ensuing. \begin{definition}\label{def_rkhs} A vector valued RKHS $\ccalH$ is a Hilbert space of functions $h:\ccalS\to \mathbb{R}^p$ such that for all $\bbc\in\mathbb{R}^p$ and $s \in \ccalS$, the following reproducing property holds \begin{equation}\label{eqn_reproducing} <h(\cdot),\kappa(s,\cdot)\bbc>_{\ccalH} = h(s)^\top\bbc. \end{equation} where $\kappa(s,s^\prime)$ is a symmetric matrix-valued function that renders a positive definite matrix when evaluated at any $s,s^\prime \in \ccalS$. \end{definition} If $\kappa(s,s^\prime)$ is a diagonal matrix-valued function with diagonal elements $\kappa(s,s^\prime)_{ii}$, and $\mathbf c$ is the $i$-th canonical vector in $\mathbb R^p$, then \eqref{eqn_reproducing} reduces to the standard one-dimensional reproducing property per coordinate % % $h_i(s) = <h_i(\cdot),\kappa(s,\cdot)_{ii}>.$ % With the above definitions the policy of the agent is the following conditional probability of the action $\pi_h(a|s):\ccalS\times \ccalA \to \mathbb{R}_+$, with \begin{equation}\label{eqn_gaussian_policy} \pi_h(a|s) = \frac{1}{\sqrt{\det(2\pi\Sigma)}}e^{-\frac{(a-h(s))^\top\Sigma^{-1}(a-h(s))}{2}}. \end{equation} The latter means that given a function $h\in\ccalH$ and the current state $s\in\ccalS$, the agent selects an action $a\in\ccalA$ from a multivariate normal distribution $\ccalN(h(s),\Sigma)$. The choice of a random policy over a deterministic policy $a=h(s)$ makes the problem tractable both theoretically and numerically as it is explained in \cite{paternain2018stochastic}. The actions selected by the agent result in a reward defined by a function $r:\ccalS\times\ccalA \to \mathbb{R}$. The objective is then to find a policy $h^\star \in \ccalH$ such that it maximizes the expected discounted reward \begin{equation}\label{eqn_problem_statement} h^\star := \argmax_{h\in\ccalH} U_{s_0}(h) = \argmax_{h\in\ccalH} \mathbb{E}\left[\sum_{t=0}^\infty \gamma^t r(s_t,a_t)\Big| h,s_0\right] , \end{equation} where the expectation is taken with respect to all states except $s_0$, i.e., $s_1,\ldots $ and all actions $a_0,a_1,\ldots,$. The parameter $\gamma \in(0,1)$ is a discount factor that gives relative weights to the reward at different times. Values of $\gamma$ close to one imply that current rewards are as important as future rewards, whereas smaller values of $\gamma$ give origin to myopic policies that prioritize maximizing immediate rewards. It is also noticeable that $U_{s_0}(h)$ is indeed a function of the policy $h$, since policies affect the trajectories $\{s_t,a_t\}_{t=0}^\infty$. As discussed in Section \ref{sec_intro} problem \eqref{eqn_problem_statement} can be tackled using methods of the policy gradient type \cite[Chapter 13]{sutton1998reinforcement}. These methods have been extended as well to non-parametric scenarios as we consider here \cite{lever2015modelling,paternain2018stochastic}. A drawback of these methods is that they require restarts which prevents them from a fully online implementation. To better explain this claim let us write down the expression of the gradient of the objective in \eqref{eqn_problem_statement} with respect to $h$. Before doing so, we are required to define the discounted long-run probability distribution $\rho_{s_0}(s,a)$ \begin{align}\label{eqn_discounted_distribution} &\hspace{.3cm}\rho_{s_0}(s,a) := (1-\gamma)\sum_{t=0}^\infty \gamma^t p(s_t=s,a_t=a|s_0), \end{align} where $p(s_t=s,a_t=a|s_0)$ is the distribution of the MDP under a policy $h$ \begin{equation}\label{eqn_mdp_distribution} \begin{split} p(s_t=s,a_t=a|s_0)= \\ \pi_h(a_t|s_t) \int \prod_{u=0}^{t-1} p(s_{u+1}|s_u,a_u)\pi_h(a_u|s_u) \, d\bbs_{t-1} d\bba_{t-1}, \end{split} \end{equation} with $d\bbs_{t-1} = (ds_1,\ldots ds_{t-1})$ and $d\bba_{t-1} = (da_0,\ldots da_{t-1})$. We also require to define $Q(s,a;h)$, the expected discounted reward for a policy $h$ that at state $s$ selects action $a$. Formally this is \begin{equation}\label{eqn_q_function} Q(s,a;h) := \mathbb{E}\left[\sum_{t=0}^\infty \gamma^t r(s_t,a_t)\Big| h, s_0=s, a_0=a\right]. \end{equation} With these functions defined, the gradient of the discounted rewards with respect to $h$ yields \cite{sutton2000policy,lever2015modelling} \begin{align}\label{eqn_nabla_U} &\nabla_h U_{s_0}(h,\cdot)= \\ &\frac{1}{1-\gamma}\mathbb{E}_{(s,a)\sim \rho_{s_0}(s,a)}\left[ Q(s,a;h)\kappa(s,\cdot)\Sigma^{-1}\left(a-h(s)\right) \Big| h\right], \nonumber \end{align} where the gradient of $U_{s_0}(h)$ with respect to the continuous function $h$ is defined in the sense of Frechet, rendering a function in $\mathcal H$. This is represented by the notation in $\nabla_h U_{s_0}(h,\cdot)$, where the dot substitutes the second variable of the kernel, belonging to $\mathcal S$, which is omitted to simplify notation. Observe that the expectation with respect to the distribution $\rho_{s_0}(s,a)$ is an integral of an infinite sum over a continuous space. Although this could have a tractable solution in some specific cases, this would require the system transition density $p(s_{t+1}|s_t,a_t)$ which is unknown in the context of RL. Thus, computing \eqref{eqn_nabla_U} in closed form becomes impractical. In fact, a large number of samples might be needed to obtain an accurate Monte Carlo approximation even if $p(s_{t+1}|s_t,a_t)$ were known. In \cite{paternain2018stochastic} an offline stochastic gradient ascent algorithm is proposed to overcome these difficulties and it is shown to converge to a critical point of the functional $U_{s_0}$. {Notice that to compute stochastic approximations of the gradient \eqref{eqn_nabla_U} on is required to sample from the distribution $\rho_{s_0}$ which depends on the initial condition. This dependency results in a fundamental limitation for online implementation.} We present in Section \ref{sec_offline_alg} the algorithm and a summary of the main results in \cite{paternain2018stochastic} since it serves as the basis for a fully online algorithm and to understanding the aforementioned difficulties associated to the online problem in detail. {Before doing so we discuss a common workout to the continuing task problem\textemdash or the problem of avoiding restarts. } { \subsection{Reinforcement learning in continuous tasks}\label{sec_continuing} When considering continuing tasks it is customary to modify the objective \eqref{eqn_problem_statement} and instead attempt to maximize the undiscounted objective \cite[Chapter 13]{sutton2018reinforcement} % \begin{equation}\label{eqn_average_return} U_{s_0}^\prime(h) = \lim_{T\to \infty} \frac{1}{T}\sum_{t=1}^T\mathbb{E}\left[r(s_t,a_t)\Big| s_0\right]. \end{equation} % Consider a steady state distribution $\rho^\prime(s)$ that is ergodic and independent of the starting point, this is, a distribution that satisfies % \begin{equation}\label{eqn_ergodic_distribution} \rho^\prime(s^\prime) = \int \rho^\prime(s)\pi_h(a|s)p(s^\prime|s,a) \, ds da, \end{equation} % for all $s^\prime\in\ccalS$. Under the assumptions that such distribution exists and that the distribution of the MDP converges to it, the limit in \eqref{eqn_average_return} is finite. Then, using Stolz-Cesaro's Lemma (see e.g. \cite[pp. 85-88]{muresan2009concrete}), then \eqref{eqn_average_return} reduces to \begin{equation} U_{s_0}^\prime(h) = \lim_{t\to \infty} \mathbb{E}\left[r(s_t,a_t)\Big| s_0\right], \end{equation} % where the expectation is with respect to the stationary distribution~\eqref{eqn_ergodic_distribution}. Thus, we can rewrite the previous expression as \begin{equation}\label{eqn_value_function_stationary} U_{s_0}^\prime(h) = \mathbb{E}_{s\sim \rho^\prime, a\sim\pi_h}\left[r(s,a)\right]. \end{equation} % The advantage of this formulation is that the objective function is now independent of the initial state and therefore estimates of the gradient can be computed without requiring the reinitialization of the trajectory. The convergence to a stationary distribution however, prevent us from achieving cyclical behaviors, for the most part. In particular, a sufficient condition for the convergence is that the Markov chain is aperiodic \cite[Theorem 6.6.4]{durrett2010probability}. Which hints to the fact that in some situations cycles are not achievable under these conditions. Let us consider the following scenario as an example. An agent is required to visit three different locations denoted by states $s_1, s_2$ and $s_3$ and there is a charging station $s_0$. In this scenario is not surprising that the optimal policy is such that it cycles in the different locations and the charging station. Consider that the resulting Markov Chain is such that with probability one we transition from $s_i$ to $s_{i+1}$ for $i=0,\ldots, 2$ and from $s_3$ to $s_0$. In this scenario there exists a stationary distribution that places equal mass in every state, i.e = $\rho(s_i) =1/4$ for all $i=0,\ldots 3$. However, the convergence to this distribution is only guaranteed if the initial distribution is the stationary one. This assumption may not be realistic for this scenario since the agent is most likely to start in the charging station than in the other locations for instance. Even if a stationary distribution is not attainable for the cyclic example just described, the return \eqref{eqn_average_return} is still well defined. Thus, we could attempt to extend the theory for continuing tasks starting from \eqref{eqn_average_return} and avoiding \eqref{eqn_value_function_stationary}, without relying on a stationary distribution. However, we argue that the discounted formulation in \eqref{eqn_problem_statement} may be the preferred choice when transient behaviors are deemed important. Consider for instance the following MDP where the states are defined as $\ccalS = \left\{0, 1,\ldots, 10\right\}$ and the actions are $\ccalA=\left\{-1,1\right\}$. The transition dynamics are such that for all $s\in\ccalS\setminus\left\{0,10\right\}$ we have that $s_{t+1}=s_t + a_t$, in the case of of $s_t = 0$ we have that $s_{t+1} = s_t +a_t\mathbbm{1}(a_t>0)$ and in the case of $s_t=10$ we have $s_{t+1} = s_t$ regardless of the action selected. All the states yield zero rewards except for $s_t = 10$ whose reward is 1. Notice that under any random policy, as long as $P(a_t=1) >0$, the state converges to $10$ and thus the average return \eqref{eqn_average_return} takes the value one. This is the same value as that of choosing the action $a_t = 1$ for any state. The discounted formulation \eqref{eqn_problem_statement} allows us to distinguish between these two policies since the larger the average time to reach the state $s=10$ the smaller the value function. Having argue the practical importance of considering problems of the form \eqref{eqn_problem_statement} for continuing tasks we proceed to describe a policy gradient based solution. } \section{All gradients are ascent directions}\label{sec_important_properties} As we stated in the previous section, the main difference when comparing the online \textemdash continuing task \textemdash with the offline setting \cite{paternain2018stochastic} \textemdash episodic task \textemdash is in the gradient of the value function that we estimate. In the online setting, we have access to estimates of the gradient of the value function conditioned on the state $s_k$, that is $\nabla U_{s_k}(h_k,\cdot)$, where $s_k$ changes from one iteration to another. On the other hand, in the offline setting we can restart the system to its original state $s_0$ or redraw it from a given distribution $P(s_0)$, so that we can compute estimates of $\nabla U_{s_0}(h_k,\cdot)$ at each iteration. Thus, in the offline case we perform ascent steps over the same function $U_{s_0}$, whereas in the online setting would perform gradient steps over functions $U_{s_k}$ which are different for each $k$. This main difference is as well a fundamental challenge since in principle we are not guaranteed that the gradients that can be computed are ascent directions of the function of interest $U_{s_0}(h)$. Moreover, a second question is whether finding the maximum of the value function conditioned at $s_0$ is a problem of interest or not after we reach a new state $s_k$. We answer the second question in Proposition \ref{prop_common_critical_points} by showing that if $h$ is a critical point of $U_{s_k}(h)$ it will also be a critical point of $U_{s_l}(h)$ for all $l\geq k$. The latter can be interpreted in the following way, having a policy that is optimal at a given time, makes it optimal for the future. An in that sense, maximizing the initial objective function is a valid problem, since finding a maximum for that function means that we had found one for all $U_{s_k}(h)$. To formalize this result, we analyze the critical points of $U_{s_k}(h)$. To do so write $\nabla_h U_{s_k}(h,\cdot)$ (cf., \eqref{eqn_nabla_U}) as the following integral \begin{equation}\label{eqn_gradient_aux} \begin{split} &\nabla_h U_{s_k} (h,\cdot) = \\ \frac{1}{1-\gamma}&\int Q(s,a;h)k(s,\cdot)\Sigma^{-1}(a-h(s))\rho_{s_k}(s,a) \,ds da, \end{split} \end{equation} where $\rho_{s_k}(s,a)$ is the distribution defined in \eqref{eqn_discounted_distribution}. We work next towards writing $\rho_{s_k}$ as a product of a distribution of states and a distribution of actions. To that end, write the MPD transition distribution $p(s_t=s,a_t=a|s_k)$ for any $t\geq k$ as \begin{equation} \begin{split} p(s_t=s,a_t=a|s_k) &= p(s_t=s|s_k)\pi_h(a_t=a|s_t,s_k) \\ &= p(s_t=s|s_k)\pi_h(a_t=a|s_t), \end{split} \end{equation} where the last equality follows from the fact that the action depends only on the current state conditional on the policy (cf.,\eqref{eqn_gaussian_policy}). By substituting the previous expression in \eqref{eqn_discounted_distribution}, $\rho_{s_k}(s,a)$ reduces to \begin{equation} \rho_{s_k}(s,a) = (1-\gamma)\sum_{t=k}^\infty \gamma^t \pi_h(a_t=a|s_t=s) p(s_t=s|s_k). \end{equation} Notice that the density $\pi_h(a_t=a|s_t=s)$ is independent of $t$ and thus, the previous expression yields \begin{equation} \rho_{s_k}(s,a) = \pi_h(a|s)(1-\gamma)\sum_{t=k}^\infty \gamma^t p(s_t=s|s_k). \end{equation} Hence, defining $\rho_{s_k}(s) :=(1-\gamma)\sum_{t=k}^\infty \gamma^t p(s_t=s|s_k)$, it follows that $\rho_{s_k}(s,a) = \rho_{s_k}(s) \pi_h(a|s)$. Having $\rho_{s_k}(s,a)$ written as a product of a function depending on the states only and a function depending on the action only, allows us to reduce the expression in \eqref{eqn_gradient_aux} to \begin{equation}\label{eqn_new_gradient_expression} \nabla_h U_{s_k}(h,\cdot) =\frac{1}{1-\gamma} \int D(s)\rho_{s_k}(s)\kappa(s,\cdot)\,ds, \end{equation} where the function $D(s)$ is the result of the integration of all the terms that depend on the action \begin{equation}\label{eqn_derivative_q} D(s) = \int Q(s,a;h) \Sigma^{-1}\left(a-h(s)\right)\pi_h(a|s)\,da. \end{equation} Writing the gradient as in \eqref{eqn_new_gradient_expression}, allows us to split the integrands in the product of a term $\rho_{s_k}(s)$ that depends on the state at time $k$ and a term $D(s)\kappa(s,\cdot)$ that do not depend on $s_k$. Hence, if a policy $h$ is such that $D(s)$ is zero for all $s$, then $h$ is a critical point for all value functions. This idea suggests that the quantity $D(s)$ is of fundamental importance in the problem. Indeed, $D(s)$ is an approximation of the derivative of the $Q$-function with respect to $a$. To see why this is the case, observe that because $\pi_h(a|s)$ is Gaussian, then $\Sigma^{-1}(a-h(s))\pi_h(a|s)$ is the derivative of $\pi_h(a|s)$ with respect to $a$. Hence, $D(s)$ can be written as \begin{equation} D(s) = \int Q(s,a;h) \frac{\partial \pi_h(a|s)}{\partial a} da. \end{equation} Notice that as the covariance matrix of $\pi_h(a|s)$ approaches the null matrix, the distribution $\pi_h(a|s)$ approaches a Dirac delta centered at $h(s)$. That being the case, $D(s)$ yields \begin{equation} D(s) \simeq \int Q(s,a;h) \delta^{\prime}(a-h(s)) \, da = \frac{\partial Q(s,a;h)}{\partial a}\Big|_{a=h(s)}. \end{equation} In this case, the fact that $D(s)$ is identically zero means that we have found a policy $h$ that makes every action a stationary point of the $Q$-function. The previous observation relates to Bellman's optimality condition, that establishes that a policy is optimal if it is such that it selects the actions that maximize the $Q$-function. When $\Sigma$ is different than the null matrix, $D(s)$ is an approximation of the derivative. In \cite{nesterov2017random} the aforementioned Gaussian smoothing is used as an approximation of the stochastic gradient in the context of zero-order optimization, and is formally established that it approximates the derivative with an error that depends linearly on the norm of the covariance matrix. The insights provided in the previous paragraphs regarding the importance of the function $D(s)$ are not enough to fully characterize the critical points of $U_{s_k}(h)$ since according to \eqref{eqn_new_gradient_expression} its gradient depends as well on the long run discounted distribution $\rho_{s_k}(s)$. The fact that this distribution might take the value zero at different states for different $s_k$ does not allow us to say that a policy can be a critical point of every value function. However, we will be able to prove that if a policy is a critical point for $U_{s_k}(h)$ it is also a critical point for $U_{s_l}(h)$ for every $l\geq k$. To formalize the previous statement we require the following auxiliary result. \begin{lemma}\label{lemma_distribution} Let $S_0$ be the following set \begin{equation} \ccalS_0 = \left\{ s\in \ccalS : \exists \,t \geq 0, p(s_t=s|s_0) >0\right\}. \end{equation} For all $s^\prime,s\in \ccalS_0$ and $s^{\prime\prime}\in \ccalS \setminus \ccalS_0$ we have that % \begin{equation} \rho_{s_0}(s)>0 \quad \mbox{and} \quad \rho_{s^\prime}(s^{\prime\prime}) = 0. \end{equation} \end{lemma} \begin{proof} See appendix \ref{appendix_lemma_distribution}. \end{proof} The set $\ccalS_0$ contains the states for which the probability measure conditioned on the policy and on the initial state $s_0$ is strictly positive. We term $S_0$ the set of reachable states from $s_0$. The previous result, ensures that for all reachable states $s\in\ccalS_0$, the probability measure $\rho_{s_0}(s)$ is strictly positive. The latter is not surprising, since intuitively, the distribution $\rho_{s_0}(s)$ is a weighted sum of the distributions of reaching the state $s$ starting from $s_0$ at different times. Moreover, and along the same lines, we establish that if a point cannot be reached starting from $s_0$, it cannot be reached starting from any other point that is reachable from $s_0$. The previous result can be summarized by saying that set of reachable points does not increase as the system evolves, i.e., $\ccalS_k \subseteq \ccalS_0$ for all $k\geq 0$. Building on the previous result we show that the set of critical points of $U_{s_k}(h)$ can only increase with the iterations. This means that a critical point of the functional $U_{s_k}(h)$ is also a critical point of the functional conditioned at any state visited in the future. Without loss of generality we state the result for $k=0$ { and with the dimension of the action space $p=1$} . \begin{proposition}\label{prop_common_critical_points} If $h\in\ccalH$ is a critical point of $U_{s_0}(h)$, then it is also a critical point for $U_{s_{l}}(h)$ for all $l \geq 0$, with $s_l\in \ccalS_0$. % \end{proposition} \begin{proof} Let us start by writing the square of norm of $\nabla_h U_{s_0}(\cdot)$ according to \eqref{eqn_new_gradient_expression} as % \begin{equation}\label{eqn_gradient_norm} \left\|\nabla_h U_{s_0}(h,\cdot) \right\|^2 = \int \int D(s)\rho_{s_0}(s)\kappa(s,s^\prime) D(s^\prime)\rho_{s_0}(s^\prime) \, dsds^\prime. \end{equation} From Mercer's Theorem (cf., \cite{j1909xvi}) there exists $\lambda_i > 0$ and orthornormal basis $e_i(s)$ of $L^2(\ccalS)$ such that % \begin{equation}\label{eqn_mercer} \kappa(s,s^\prime) = \sum_{i=1}^\infty \lambda_i e_i(s) e_i(s^\prime). \end{equation} % Using the previous result, we can decompose the expression in \eqref{eqn_gradient_norm} as the following sum of squares \begin{equation}\label{eqn_norm_of_gradient} \begin{split} \left\|\nabla_h U_{s_0}(h,\cdot) \right\|^2 = \sum_{i=1}^\infty \lambda_i\left[\int D(s)\rho_{s_0}(s)e_i(s) \, ds\right]^2. \end{split} \end{equation} % Notice that the previous expression can take the value zero if and only if for all $i=1.\ldots$ we have that % \begin{equation}\label{eqn_crit_point_condition} \int D(s)\rho_{s_0}(s)e_i(s)ds =0. \end{equation} Because $e_i(s)$ with $i=1\ldots $ form an orthogonal basis of $L^2(\ccalS)$ it means that \eqref{eqn_crit_point_condition} holds if and only if $D(s)\rho_{s_0}(s) \equiv 0$. To complete the proof, we are left to show that if $D(s)\rho_{s_0}(s) \equiv 0$ then it holds that $D(s)\rho_{s_l}(s) \equiv 0$ for all $l\geq 0$. The latter can be established by showing that for any $s \in S$ such that $\rho_{s_0}(s) =0$ we also have that $\rho_{s_l}(s) = 0$ which follows by virtue of Lemma \ref{lemma_distribution}. % \end{proof} The previous result formalizes the idea that if we find an optimal policy at given time, then it is optimal for all future states. Moreover, the latter is true for every critical point, which suggests, that the value functions conditioned at different initial states should be similar. We formalize this intuition in Theorem \ref{prop_all_gradients} where we show that $\nabla_h U_{s_k}(h)$ is an ascent direction for $U_{s_0}(h)$ if the distribution $\rho_{s_k}(s)$ is bounded above and bounded away from zero. We also require some smoothness assumptions on the transition probability which we formalize next. \begin{assumption}\label{assumption_prob_dist} There exists $\beta_{\rho}>0$ and $B_{\rho}$ such that for all $s_k,s\in\ccalS_0$ and for all $h\in\ccalH$ we have that % \begin{equation} B_{\rho} \geq \rho_{s_k}(s) \geq \beta_{\rho}. \end{equation} % In addition we have that the transition probability is Lipschitz with constant $L_p$, i.e., \begin{equation} \left|p(s_t=s|s_{t-1},a_{t-1})-p(s_t=s^\prime|s_{t-1},a_{t-1}) \right| \leq L_p\left\|s-s^\prime\right\|. \end{equation} % We require as well the following smoothness properties of the probability transition % \begin{equation} p^\prime(s,a):= \frac{\partial p(s_{t+1}|s_t,a_t)}{\partial a_t}\big|_{s_t=s,a_t=a} \end{equation} % to be Lipschitz with constants $L_{ps}$ and $L_{pa}$, this is % \begin{equation} \left|p^\prime(s,a)-p^\prime(s^\prime,a^\prime)\right| \leq L_{ps}\left\|s-s^\prime\right\|+L_{pa}\left\|a-a^\prime\right\|. \end{equation} % \end{assumption} Notice that the lower bound on $\beta_\rho(s)$ requires that every state is reachable. The latter can be achieved with any sufficiently exploratory policy unless there are states that are attractive. The previous assumptions allow us to establish that $\nabla_h U_{s_k}(h)$ is an ascent direction for the function $U_{s_0}(h)$. Notice that for the latter to hold, we require that \begin{equation} \left\langle\nabla_hU_{s_0}(h), \nabla_hU_{s_k}(h)\right\rangle_{\ccalH} \geq 0. \end{equation} By writing the gradient as in \eqref{eqn_new_gradient_expression} and using the reproducing property of the kernel it follows that the previous condition is equivalent to \begin{equation} \int D(s)^\top\rho_{s_0}(s)\kappa(s,s^\prime)D(s^\prime)\rho_{s_k}(s^\prime) \, ds ds^\prime\geq 0. \end{equation} where $(\cdot)^\top$ denotes transpose. Notice that if $\kappa(s,s^\prime)$ approaches a Dirac delta, the integral with respect to $s^\prime$, in the limit reduces to evaluating $D(s^\prime)\rho_{s_k}(s^\prime)$ at $s^\prime=s$. Thus, the double integral is an approximation of \begin{equation} \int \|D(s)\|^2\rho_{s_0}(s)\rho_{s_k}(s) \, ds \end{equation} which is always non-negative. To formalize the previous argument we will consider a Gaussian Kernel and we will show that if the width of the kernel is small enough, then the previous result holds (Theorem \ref{prop_all_gradients}). We require to establish first that $D(s)\rho_{s_0}(s)$ is bounded and Lipschitz. This is subject of the following lemma. \begin{lemma}\label{lemma_lipshitz} Let $\kappa_{\Sigma_\ccalH}(s,s^\prime)$ be a matrix-valued Gaussian kernel with covariance matrix $\Sigma_{\ccalH}\succ 0$, i.e. for all $i=1,\ldots, p$ we have that % \begin{equation}\label{Gaussian_lemma_lipschitz} \kappa_{\Sigma_\ccalH}(s,s^\prime)_{ii} = e^{-(s-s^\prime)^\top \Sigma_{\ccalH}^{-1}(s-s^\prime)/2}, \end{equation} % and $\kappa(s,s^\prime;\Sigma_\ccalH)_{ij} = 0$ for all $j=1\ldots p$ with $j\neq i$. Let $B_r, L_{rs}$ and $L_{ra}$ be the constants defined in Assumption \ref{assumption_reward_function}. Likewise, let $B_{\rho}, L_p, L_{ps}$ and $L_{pa}$ be the constants defined in Assumption \ref{assumption_prob_dist}. Furthermore, define the following constants % \begin{equation}\label{eqn_bound_D} B_D:=\frac{\sqrt{2}B_r}{1-\gamma}\frac{\Gamma\left(\frac{p+1}{2}\right)}{\Gamma\left(\frac{p}{2}\right)}, \end{equation} with $\Gamma(\cdot)$ being the Gamma function, % $L_{Qs}=L_{rs}+\frac{B_r}{1-\gamma}L_{ps} |\ccalS|$, $L_{Qa}=L_{ra}+\frac{B_r}{1-\gamma}L_{pa} |\ccalS|$, % \begin{equation} L_h :=\left\|h\right\|\lambda_{\min}(\Sigma_\ccalH)^{-1/2}, \end{equation} and $L_{D}:=L_{Qs}+L_{Qa}L_h$. Then, we have that $D(s)\rho_{s_k}(s)$ for any $s_k\in \ccalS_0$ is bounded by $B:=B_\rho B_D$ and it is Lipschitz with constant $L:=B_DL_p+B_\rho L_D$. \end{lemma} \begin{proof} See Appendix \ref{appendix_lipshitz}. \end{proof} As it was previously discussed we require a Gaussian Kernel whose width is small enough for the inner product of gradients at different initial states to be positive. We next formalize this condition. Define the normalization factor $Z:= \sqrt{\det{2\pi \Sigma_\ccalH}}$ and let \begin{equation}\label{eqn_kernel_condition} \sqrt{np}\left(1+\frac{\beta_\rho}{B_\rho}\right)\left\|\Sigma_\ccalH\right\|ZL(h,\Sigma_{\ccalH}) B|\ccalS|\leq \frac{\varepsilon}{2}\frac{\beta_\rho}{B_\rho}. \end{equation} The previous condition in a sense defines the maximum width of the kernel. Since if the norm of $\Sigma_\ccalH$ is large, the previous condition cannot hold. This intuition is not exact since the term $Z$ includes the determinant of the matrix $\Sigma_\ccalH$ and thus, it is possible to have a kernel that has some directions being wide as long as the product of the eigenvalues is small enough. Likewise the Lipschitz constant in \eqref{eqn_kernel_condition} depends on the norm of the function $h$, and in that sense it is necessary to ensure that the norm remains bounded for said condition to hold. We are now in conditions of establishing the main result in this work, which states that as long as the norm of $\nabla_h U_{s_0}(h)$ is large, the gradient of any value function $\nabla_h U_{s_k}(h)$ is an ascent direction for $U_{s_0}(h)$. This result will be instrumental also to the proof of convergence of the online algorithm (Section \ref{sec_convergence}). \begin{theorem}\label{prop_all_gradients} % Under the hypotheses of Lemma \ref{lemma_lipshitz}, for every $\varepsilon>0$ and for every $\ccalH$ and $h\in\ccalH$ satisfying \eqref{eqn_kernel_condition} it holds that if $\left\| \nabla_h U_{s_0}(h,\cdot)\right\|^2_{\ccalH} \geq \varepsilon$ then we have that for all $k\geq 0$ % \begin{equation}\label{eqn_prod_diff_grad} \left\langle\nabla_hU_{s_0}(h,\cdot),\nabla_hU_{s_k}(h,\cdot) \right\rangle_{\ccalH}>{\frac{\varepsilon}{2}\frac{\beta_\rho}{B_{\rho}}}. \end{equation} % \end{theorem} \begin{proof} % % Consider the following integral, with the kernel covariance matrix $\Sigma_\ccalH$ as a parameter \begin{equation}\label{eqn_I} I_{\Sigma_\ccalH} = \int D(s)^\top\rho_{s_l}(s)\kappa_{\Sigma_\ccalH}(s,s^\prime)\rho_{s_k}(s^\prime)D(s^\prime)\,dsds^\prime, \end{equation} % where $\kappa_{\Sigma_\ccalH}(s,s^\prime)$ is a kernel of the form \eqref{Gaussian_lemma_lipschitz}. Observe that by writing the gradients of $U_{s_0}(h)$ and $U_{s_k}(h)$ as in \eqref{eqn_new_gradient_expression}, it follows that $I_{\Sigma_{\ccalH}}$ is the inner product in \eqref{eqn_prod_diff_grad}. Hence, to prove the claim, it suffices to show that for all $\Sigma_\ccalH$ satisfying condition \eqref{eqn_kernel_condition}, $I_{\Sigma_\ccalH}> {\varepsilon \beta_\rho/(2B_\rho)}$. To do so, apply the change of variables $u=s^\prime-s$, and divide and multiply the previous expression by $Z:=\sqrt{\det{2\pi \Sigma_\ccalH}}$ to write $I_{\Sigma_\ccalH}$ as \begin{align}\label{eqn_def_ivarsigma} \nonumber I_{\Sigma_\ccalH}& =\int D(s)^\top\rho_{s_0}(s)\kappa_{\Sigma_\ccalH}(s,s+u)\rho_{s_k}(s+u) D(s+u) ds du\\ &\hspace{-0.4cm}=Z \int D(s)^\top\rho_{s_0}(s)g(u;0,\Sigma_\ccalH)\rho_{s_k}(s+u) D(s+u) \, ds du. \end{align} where the normalization factor $Z$ was introduced to identify $g(u;0,\Sigma_\ccalH):=\kappa_{\Sigma_\ccalH}(s,s+u)_{ii}/Z$ as a Gaussian probability density function with zero mean and covariance $\Sigma_\ccalH$ (cf. \eqref{Gaussian_lemma_lipschitz}). Then we write the partial integral with respect to $u$ as the expectation of $D(s+u)\rho_{s_k}(s+u)$, % \begin{equation} I_{\Sigma_\ccalH}\hspace{-2pt}=Z\hspace{-2pt}\int\hspace{-2pt} D(s)^\top\rho_{s_0}(s)\mathbb{E}_{u\sim\ccalN(0,\Sigma_\ccalH)}\left[D(s+u) \rho_{s_k}(s+u)\right] \, ds. \end{equation} From Lemma \ref{lemma_lipshitz} it follows that $D(s)\rho_{s_k}(s)$ is Lipschitz with constant $L$. Then, by virtue of \cite[Theorem 1]{nesterov2017random} we have that \begin{equation} \left\| \mathbb{E}\left[D(s+u) \rho_{s_k}(s+u)\right] - D(s)\rho_{s_k}(s)\right\| \leq \sqrt{np}\left\|\Sigma_\ccalH\right\| L.\label{eq:nesetrov} \end{equation} where again the expectation is taken with respect to the random variable $u\sim\ccalN(0,\Sigma_\ccalH)$. The result in \eqref{eq:nesetrov} allows us to lower bound $I_{\Sigma_\ccalH}$ by \begin{align} I_{\Sigma_\ccalH} &\geq {Z}\int \|D(s)\|^2\rho_{s_0}(s)\rho_{s_k}(s) \, ds \nonumber \\ &-{Z}\sqrt{np}\left\|\Sigma_\ccalH\right\| L\int \left\|D(s)\rho_{s_0}(s)\right\| \, ds \nonumber\\ &=\bar I_{\Sigma_\ccalH}-\sqrt{np}\left\|\Sigma_\ccalH\right\| {Z}L\int \left\|D(s)\rho_{s_0}(s)\right\| \, ds \label{eqn_diff_I} \end{align} where $\bar I_{\Sigma_\ccalH}$ was implicitly defined in \eqref{eqn_diff_I} as \begin{align}\bar I_{\Sigma_\ccalH}:={Z}\int \left\|D(s)\right\|\rho_{s_0}(s)\rho_{s_k}(s)ds\\=\sqrt{\det{2\pi \Sigma_\ccalH}} \int \left\|D(s)\right\|^2\rho_{s_0}(s)\rho_{s_k}(s)ds \end{align} Let us next define the following integrals, identical to $I_{\Sigma_\ccalH}$ and $\bar I_{\Sigma_\ccalH}$, but for $\rho_{s_0}$ substituting $\rho_{s_k}$ \begin{align} J_{\Sigma_\ccalH}&:= \int D(s)^\prime\rho_{s_0}(s)\kappa_{\Sigma_\ccalH}(s,s^\prime) D(s^\prime)\rho_{s_0}(s^\prime) \, dsds^\prime\\ \bar J_{\Sigma_\ccalH}&:= Z \int \|D(s)\|^2\rho^2_{s_0}(s) ds. \end{align} % and use the bounds on the probability distribution (cf., Assumption \ref{assumption_prob_dist}) to write \begin{equation} \begin{split} \bar J_{\Sigma_\ccalH}&\leq {Z} \int \|D(s)\|^2\rho_{s_0}(s)\frac{B_p}{\beta_\rho}\rho_{s_k}(s) \, ds = \frac{B_p}{\beta_\rho}\bar I_{\Sigma_\ccalH}. \end{split} \end{equation} % Hence, we can write \eqref{eqn_diff_I} as \begin{equation}\label{eqn_Ivarsigma} I_{\Sigma_\ccalH} \geq \frac{\beta_\rho}{B_{\rho}}\bar J_{\Sigma_\ccalH} - \sqrt{np}\left\|\Sigma_\ccalH\right\| ZL\int \left\|D(s)\rho_{s_0}(s)\right\| \, ds. \end{equation} % Repeating steps \eqref{eqn_def_ivarsigma}-\eqref{eqn_diff_I}, after substituting $\rho_{s_0}$ for $\rho_{s_k}$, we can bound the difference between $J_{\Sigma_\ccalH}$ and $\bar J_{\Sigma_\ccalH}$ as we did it for $I_{\Sigma_\ccalH}$ and $\bar I_{\Sigma_\ccalH}$ in \eqref{eqn_diff_I}. Specifically, the following inequality holds \begin{align} \bar J_{\Sigma_\ccalH} &\geq J_{\Sigma_\ccalH}-\sqrt{np}\left\|\Sigma_\ccalH\right\| ZL\int \left\|D(s)\rho_{s_0}(s)\right\| \, ds \label{eqn_diff_J} \end{align} This allows us to further lower bound $I_{\Sigma_\ccalH}$ by % \begin{equation} I_{\Sigma_\ccalH} \geq \frac{\beta_\rho}{B_{\rho}}J_{\Sigma_\ccalH} - \sqrt{np}\left(1+\frac{\beta_\rho}{B_\rho}\right)\left\|\Sigma_\ccalH\right\| ZL\int \left\|D(s)\rho_{s_0}(s)\right\| \, ds. \end{equation} By virtue of Lemma \ref{lemma_lipshitz} we have that $\left\|D(s)\rho_{s_0}(s)\right\|\leq B$. Defining $|\ccalS|$ as the measure of the set $\ccalS$, $I_{\Sigma_\ccalH}$ can be further lower bounded by \begin{equation} I_{\Sigma_\ccalH} \geq \frac{\beta_\rho}{B_{\rho}}J_{\Sigma_\ccalH} - \sqrt{np}{\left(1+\frac{\beta_\rho}{B_\rho}\right)}\left\|\Sigma_\ccalH\right\| ZL B|\ccalS|. \end{equation} Notice that $J_{\Sigma_\ccalH}=\left\| \nabla_h U_{s_0}(h,\cdot)\right\|^2 \geq \varepsilon$, hence the previous inequality reduces to \begin{equation} I_{\Sigma_\ccalH} \geq \frac{\beta_\rho}{B_{\rho}}{\varepsilon} -\sqrt{np} \left(1+\frac{\beta_\rho}{B_\rho}\right)\left\|\Sigma_\ccalH\right\| ZL B|\ccalS|. \end{equation} Then, for any $\Sigma_\ccalH$ satisfying \eqref{eqn_kernel_condition}, we can lower bound the right hand side of the previous expression by $\varepsilon\beta_\rho/(2B_{\rho})$, obtaining % \begin{equation} I_{\Sigma_\ccalH} \geq {\frac{\beta_\rho}{2B_{\rho}}\varepsilon,} \end{equation} % which completes the proof of the theorem. \end{proof} The previous result establishes that for kernels that satisfy the condition \eqref{eqn_kernel_condition} with $h$ outside of an $\varepsilon$ neighborhood of the critical points, i.e., for $h$ such that $\left\|\nabla_h U_{s_0}(h)\right\| > \varepsilon$, the inner product between $\nabla_h U_{s_k}(h)$ and $\nabla_h U_{s_0}(h)$ is larger than a constant that depends on $\varepsilon$. The latter means that for all state $s_k\in\ccalS$, $\nabla_h U_{s_k}(h)$ is an ascent direction of the function $U_{s_0}(h)$. In the next section we exploit this idea to show that the online gradient ascent algorithm proposed in Section \ref{sec_online} converges with probability one to a neighborhood of a critical point of $U_{s_0}(h)$. % % % % %
{'timestamp': '2020-10-19T02:19:34', 'yymm': '2010', 'arxiv_id': '2010.08443', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08443'}
arxiv
\section{Introduction} Artificial neural networks have become increasingly popular over the last decade as they excel in tasks such as object detection and speech recognition {\cite{deep_learning}}, which are becoming more commonplace with the use of self-driving cars and virtual assistants. The rapid development of deep neural networks has also made them the dominant approach for natural language processing (NLP) applications, ranging from neural machine translation (NMT) \cite{Bahdanau2014NeuralMT, Klein2017OpenNMTOT, 45610} and text summarization \cite{Rush2015ANA, Nallapati2016AbstractiveTS, Liu2018GeneratingWB} to virtual assistants such as Apple Siri, Amazon Alexa, and Google Home. Unfortunately, neural networks are slow for training, inference and use due to their vast computational complexity. Several approaches have been proposed to address these issues including (\emph{a})~quantization and pruning, (\emph{b})~efficient models with less computational demand, and (\emph{c})~specialized hardware accelerators~\cite{ml_overview}. While direction (\emph{a}) has been well-studied~\cite{optimal_brain_damage, pruning_and_quantization, sparse_lstm, quantization_survey, quinn2018}, and can be considered complementary to (\emph{b,c}), optimizing the combination of (\emph{b}) and (\emph{c}) has not been considered, to the best of our knowledge. Thus, here we propose a novel {\emph{vector-vector-matrix architecture}} (VVMA) that compresses neural networks, while optimizing for hardware performance at inference time. Therefore, we optimize (\emph{b}) and (\emph{c}), without conflicting with (\emph{a}), i.e.,~using quantization and pruning can potentially further boost the efficiency of our framework. Figure~\ref{figure:1} illustrates this VVMA in contrast to a traditional vector-matrix architecture. Moreover, the inherently sequential nature of many NLP tasks can increase the latency at inference time. Constrained by their memory bandwidth and footprint, modern accelerators rely on large batch sizes to avoid under-utilization. However, it is not always possible to increase the batch size if conclusions have to be inferred quickly, e.g.,~for real-time inference. For example, the matrix multiply unit of state-of-the-art accelerators, such as Google's Tensor Processing Unit (TPU), will ``stall'' when translating a single sentence, thus increasing the overall latency \cite{tpu}. Our architecture can improve the TPU and other AI accelerators for \textit{small-batch inference}. Thus, unlike other methods for compressing neural networks, the VVMA is designed to take advantage of the dataflow and the architecture of certain kinds of hardware accelerators such as the TPU. Our contributions are as follows: \begin{itemize} \item We tailor an efficient model to state-of-the-art hardware accelerators. \item We provide an efficient vector-vector-matrix architecture (VVMA) framework for inference with small batch sizes. \item We use VVMAs to speed up inference in the computationally expensive Neural Machine Translation (NMT) task by a factor of four without losing much in terms of quality. \item We highlight promising applications of the VVMA in other deep learning domains and novel Artificial Intelligence~(AI) accelerators. \end{itemize} The rest of this paper is organized as follows: In Section~\ref{background}, we elaborate on directions (\emph{b}) and (\emph{c}), and we relate them to VVMAs. In Section~\ref{architecture}, we motivate VVMAs as a faster improvement of the TPU's architecture and dataflow at inference time, and we then analyze our framework in its universality, including tips for efficient implementation of VVMAs. As a proof of concept, in Section~\ref{results} we demonstrate empirical inference speed-ups for NMT using Seq2seq-LSTM and Transformer models, which are both notorious for their computational complexity. We also show ablation studies and extensions to other tasks. In Section~\ref{discussion}, we explore novel accelerators that can benefit from VVMAs. Finally, we offer concluding remarks in Section~\ref{conclusion}, and we point to possible directions for future work. \section{Background} \label{background} Here, we look at efficient models from the software and the hardware side, and we discuss the advantages of merging them in a \emph{co-design} manner. We further discuss the importance of wall-clock speed versus floating point operations and why from this perspective our weight sharing matrices will decrease inference rather than training time. \subsection{Efficient Models from the Software Side for Training and Inference} Efficient model architectures can decrease the complexity of neural networks. Some techniques to achieve this are described in \cite{hashing,shuffle,group_rnn}. {\citet{shuffle}} added a new type of layer, a \emph{channel shuffle layer}, to neural networks that use group convolution. By shuffling the data between layers, they reduced the number of parameters in the other layers while retaining similar accuracy. {\citet{group_rnn}} used a technique similar to group convolution, but applied it to recurrent neural networks. They used shuffling operations with a group recurrent neural network and showed improvements for NMT and text summarization. {\citet{hashing}} compressed a weight matrix into a learned vector of weights. They used a hash function to map entries in the weight matrix to elements in the vector. As a result, many matrix entries share a single weight in the vector. As Transformers are becoming the standard building block for NLP tasks, there is a growing effort to make them efficient, since their inference time scales as $O(N^2)$, where $N$ is the number of input tokens. \citet{Child2019GeneratingLS} proposed Sparse Transformers with $O(N\sqrt{N})$ complexity. Likewise,~\citet{Sukhbaatar2019AdaptiveAS} developed Adaptive Attention Span and~\citet{Kitaev2020ReformerTE} proposed Reformer using locality-sensitive hashing, and achieved $O(N\log N)$ complexity. See \cite{ganesh2020compressing} for a broader overview. In a similar fashion, our VVMA is an efficient model because it reduces the computational complexity at inference time without much decrease in performance. However, unlike the above models, VVMAs focus on the low levels of execution: the VVMA is an architecture that speeds up matrix multiplications. Thus, it is an efficient model that relates to hardware accelerators directly and it is universal, as matrix multiplication is the dominant computational factor for neural network inference. \subsection{Efficient Models from the Hardware Side} As we have mentioned above, successful NLP applications have been based on a variety of neural network models: recurrent and convolutional neural networks, memory-augmented networks, attention mechanism, Transformers, etc. These models were designed to solve numerous tasks ranging from language modeling and named entity recognition to NMT and other sequence modeling and sequence generation tasks. Most of the computation in such models is matrix multiplication both at inference and at training time, which is expensive. Therefore, specialized hardware accelerators for neural networks have been designed, focusing on making matrix multiplication efficient. Note that the above techniques assume general hardware, i.e.,~they do not utilize the specific dataflow or architecture of an AI accelerator to improve efficiency. Yet, several such accelerators have been developed recently, e.g.,~the Horizon Robotics Brain Processing Unit, Graphcore Intelligence Processing Unit, NVIDIA Tensor Core, and Google Tensor Processing Unit (TPU). A \textit{matrix-matrix} architecture is a hardware unit that takes two matrices and multiplies them, e.g.,~NVIDIA Tensor Core. A \textit{vector-matrix} architecture such as Google's TPU multiplies a vector and a matrix. As shown in Figure~{\ref{figure:1}}, the VVMA \textit{vector-vector-matrix} architecture takes two vectors and a matrix, and it multiplies element-wise the first vector by the second vector, and then multiplies the resulting vector by the matrix. Furthermore, VVMAs are optimized for certain AI accelerators, such as the TPU architecture. We specifically take advantage of the dataflow of the matrix multiply unit in the TPU, which is described in \cite{tpu}. This matrix multiply unit allows to re-use weights for multiple batches of data, while also using a systolic loop to perform matrix multiplication extremely fast. Therefore, we reduce the computational complexity of the ``matrix'' component in the TPU's vector-matrix unit, but we also maintain representational accuracy by inserting an extra ``vector'' part to get the vector-vector-matrix unit. By switching to this unit, we introduce a trade-off by increasing the efficiency of the model while decreasing its flexibility and generalization power. Likewise, we expect to have comparable accuracy to other compression techniques while also providing even faster performance at inference time. \subsection{Trade-Off between Flexibility and Efficiency at Inference Time} While every neural network requires a certain budget of floating point operations for a target computation, how fast such computations are in practice depends not on the size of this budget but rather on the number of wall clocks needed in order to cover all floating point operations. Thus, it is important to combine the software and the hardware advances in a co-design manner to optimize an efficient model for the correct metric: wall clocks. Designed to optimize for the number of wall clocks, our \change{VVMA} introduces an extra vector component that maintains accuracy, but increases the computational complexity. We achieve this in part by optimizing our VVMA to specifically take advantage of the TPU architecture and dataflow. This creates a trade-off between flexibility and efficiency, e.g.,~the more we reuse weights, the more we have to compensate for the model accuracy. Neural networks that are specifically designed to work in conjunction with certain AI accelerators will encounter a similar trade-off. That is, the more a neural network is tuned for efficiency, the less flexibility for change the model will have {\cite{more_pruning}}. Nonetheless, we find regimes that suppress this trade-off and yield faster neural networks inference with VVMA. Thus, we believe that our VVMAs provide enough flexibility to be useful in a variety of existing neural architectures. Training is the process of using (large) datasets to learn specific weights in neural networks. This process is usually very computationally expensive and can take days or months to complete. Once a neural network has finished training, the set of weights that were learned through the training process can remain fixed while making predictions. This process of using a fixed set of weights to make predictions with a neural network is called \emph{inference} {\cite{ml_overview}}. Training can be done faster when parallelizing the process and increasing the amount of data fed into the network at a given time. This roughly translates to increasing the throughput of the training process. However, when performing inference on a single data point, the latency of making predictions seems to dominate the run-time {\cite{tpu}}. The VVMA we propose can be used specifically to decrease the latency of a neural network. Likewise, we expect this technique to be used to decrease inference time rather than to decrease training time. \section{Architecture} \label{architecture} In this section, we present our approach to constructing a VVMA, including implementation details that are necessary to use VVMAs in practice. \subsection{Motivation} Google announced their first application-specific AI accelerator called the \emph{Tensor Processing Unit} (TPU) in 2016. As described by {\citet{tpu}}, the TPU uses a systolic loop to perform matrix multiplications \cite{tpu}, which are the most demanding computations in deep neural networks. Let $W$ be an $n \times n$ weight matrix and $x$ be an $n$-dimensional input vector. In order to perform $Wx$ on the TPU, we must first break up $W$ and $x$ into $k \times k$ sections, where $k \times k$ is the size of the matrix multiply unit: \begin{equation} Wx = \begin{bmatrix} W_{1, 1} & W_{1, 2} & \cdots \\ W_{2, 1} & W_{2, 2} & \cdots \\ \vdots & \vdots & \ddots \end{bmatrix} \begin{bmatrix} x_1 \\ x_2 \\ \vdots \end{bmatrix}. \end{equation} Here, $W_{i, j}$ is a $k \times k$ block of $W$, and $x_j$ is a $k$-dimensional block of $x$. Likewise, the TPU must load each block $W_{i, j}$ onto the matrix multiply unit before multiplying it by $x_{j}$. Loading a $k \times k$ block takes $O(k)$ clocks on the TPU. After loading a block $W_{i,j}$ onto the TPU, it takes $O(2k + t)$ clocks to multiply $t$ $k$-dimensional vectors $x_j$ by the matrix $W_{i, j}$. So, the total number of clocks to multiply $t$ $n$-dimensional vectors $x$ by $W$ is \begin{equation}\label{original_clocks} O\left(\frac{n^2}{k^2} (k + 2k + t) \right). \end{equation} Note the large latency for single-batch inference, i.e.,~for $t=1$. In order to decrease it, we tweak the weight matrix $W$, so that we only have to load a single $k \times k$ block $M$ onto the matrix multiply unit. We then perform vector operations to each $x_{j}$ in order to make up for the extra parameters that are lost by re-using the same $k \times k$ matrix $M$. Figure~{\ref{figure:2}} shows an illustration of this process. \begin{figure}[t] \centering \tikz \node [scale=1, inner sep=0] { \begin{tikzpicture} \node[minimum size = 1cm, circle, draw, fill=green!10, ultra thick] at (0, 0) (x1) {$x_j$}; \node[minimum height=1.5cm, minimum width=1.5cm, rectangle, rounded corners, draw, fill=cyan!10, ultra thick] at (2, 1) (w1) {$W_{i, j}$}; \node[minimum height=1cm, minimum width=2.5cm, rectangle, rounded corners=15pt, draw, fill=yellow!10, ultra thick] at (5.5, 1) (out1) {$W_{i, j} x_j$}; \node[minimum height=1.5cm, minimum width=.75cm, rectangle, draw, rounded corners, fill=red!10, ultra thick] at (1.25, -1) (v2) {$v_{i,j}$}; \node[minimum height=1.5cm, minimum width=1.5cm, rectangle, draw, rounded corners, fill=cyan!10, ultra thick] at (3, -1) (w2) {$M$}; \node[minimum height=1cm, minimum width=2.5cm, rectangle, rounded corners=15, draw, fill=yellow!10, ultra thick] at (5.5, -1) (out2) {$M (v_{i,j} \odot x_j)$}; \draw [ultra thick, ->] (x1.north) to [out=90, in=180] (w1); \draw [ultra thick, ->] (w1) to (out1); \draw [ultra thick, ->] (v2) to (w2); \draw [ultra thick, ->] (w2) to (out2); \draw [ultra thick, ->] (x1.south) to [out=270, in=180] (v2); \end{tikzpicture} }; \caption{Illustration of how we can save time by sharing a weight matrix $M$. The top path shows the traditional dataflow, where each $W_{i, j}$ must be loaded onto the matrix multiply unit. The bottom path shows our approach, where $M$ is loaded onto the matrix multiply unit only once. We then add a vector-vector operation $v_{i,j} \odot x_j$ before doing the matrix multiplication, where $\odot$ denotes element-wise multiplication.}\label{figure:2} \end{figure} With this new procedure, the total number of clocks to multiply $t$ $n$-dimensional vectors by the larger matrix is given by \begin{equation}\label{weight_sharing_clocks} O\left(k + 2k + \frac{n^2 t}{k^2}\right). \end{equation} We can see that this new procedure significantly decreases the total number of clocks for single-batch inference with $t=1$. \subsection{Vector-Vector-Matrix Architecture} We construct the VVMA as follows. Let $W$ be a large $n \times n$ weight matrix and let $M$ be a smaller $k \times k$ weight matrix. First, we tile $M$ into a larger matrix, so that its size is greater than or equal to the weight matrix $W$. Then, we multiply each copy of $M$ by a unique diagonal matrix. Mathematically, we replace $W$ with a structured matrix as shown below: \begin{equation}\label{shared_matrix} \begin{bmatrix} M D_{1, 1} & M D_{1, 2} & \cdots \\ M D_{2, 1} & M D_{2, 2} & \cdots \\ \vdots & \vdots & \ddots \end{bmatrix}, \end{equation} \noindent where $M$ is a shared $k \times k$ weight matrix and $D_{i, j}$ is a diagonal $k \times k$ weight matrix. We use the diagonal matrices $D_{i, j}$ in order to introduce variation to each of the copies of $M$. We found that this is necessary for a VVMA to be able to effectively replace the original matrix $W$. Each of the entries in the matrix $M$ is shared in multiple blocks of the new matrix, thus decreasing the total number of parameters compared to the original weight matrix $W$. Moreover, each of the entries of $M$ as well as the entries in each diagonal matrix $D_{i, j}$ are learned as part of the training process. Even though each entry $D_{i, j}$ is mathematically represented as a matrix in Equation {\ref{shared_matrix}}, we can also see it as a $k$-dimensional vector $v_{i, j}$. We can then perform the matrix multiplication $D_{i, j} x$ as an element-wise multiplication $v_{i,j} \odot x_j$, as shown in Figure~{\ref{figure:2}}. \begin{table*}[tb] \small \centering \begin{tabular}{lllllll} \toprule \bf Task & \bf Model & \bf Architecture & \bf \# Params & \bf BLEU & \bf \# Clocks & \bf FLOPs \\ \midrule German-English & Seq2Seq-LSTM & Original & 210.9M & 22.42 & 322.1M & 421.7M \\ & & VVMA & 115.4M & 21.53 & 98.3M & 230.9M \\ & Transformer & Original & 61.4M & 29.66 & 145.2M & 122.6M \\ & & VVMA & 18.8M & 23.32 & 42.2M & 37.5M \\ \midrule English-German & Seq2Seq-LSTM & Original & 210.9M & 20.70 & 322.1M & 421.7M \\ & & VVMA & 115.4M & 18.90 & 98.3M & 230.9M \\ & Transformer & Original & 61.4M & 24.57 & 145.2M & 122.6M \\ & & VVMA & 18.8M & 18.99 & 42.2M & 37.5M \\ \midrule Vietnamese-English & Seq2Seq-LSTM & Original & 32.3M & 22.42 & 46.3M & 64.6M \\ & & VVMA & 21.9M & 20.86 & 21.9M & 43.8M \\ \midrule English-Vietnamese & Seq2Seq-LSTM & Original & 27.5M & 25.34 & 34.8M & 54.9M \\ & & VVMA & 17.1M & 24.42 & 10.3M & 34.1M \\ \bottomrule \end{tabular} \caption{Comparing the original Seq2seq-LSTM and Transformer models to such with VVMAs. Shown are the number of parameters, the BLEU score, and the estimated number of clock cycles and floating point operations.}\label{table:all:nmt} \end{table*} \subsection{Implementation Details} In order to implement \eqref{shared_matrix} as a trainable matrix, we found that it was inefficient to actually construct the entire matrix representation. Instead, it was better to take advantage of broadcasting, which allows us to element-wise multiply tensors of different shapes. Likewise, we use broadcasting to multiply the input vector $x$ by a larger diagonal tensor $D$. We then perform a matrix multiplication with the broadcasted vector and the matrix $M$. Thus, our program constructs a single $k \times k$ matrix $M$, and it does so only once rather than actually tiling it as shown in \eqref{shared_matrix}. We further found that a more aggressive gradient clipping was needed when training Seq2seq-LSTM models that use VVMAs; otherwise, the gradient grew extremely large and as a result eventually overflowed. We believe that this is because gradients accumulate as we propagate them back to a single small matrix $M$. \section{Results} \label{results} In this section, we present empirical results showing that VVMAs can substitute different types of weight matrices in neural networks (NNs). Specifically, we use our VVMAs in Seq2seq-LSTM and Transformer NMT. We report some theoretical speedups that VVMAs provide when using a TPU-style architecture. We then present a small ablation study where we modify our VVMAs by removing the diagonal terms $D_{i, j}$ or by varying the value of $k$. We also compare VVMA to standard low-rank approximations. Finally, we show that our technique extends to language modelling with Transformer-XL, and beyond NLP tasks. Unless otherwise noted, all results in this section use VVMAs with $k = 32$. That is, the matrix $W$ in the neural network is replaced with a VVMA that uses a $32 \times 32$ matrix $M$ along with $32 \times 32$ diagonal matrices $D_{i, j}$ as shown in {\eqref{shared_matrix}}. \subsection{Neural Machine Translation}\label{section:nmt} We tested our VVMAs on NMT: we integrated them as part of Seq2seq-LSTM and Transformer models, as they are most commonly used today. \subsubsection{Sequence-to-Sequence Models} For the Seq2seq-LSTM models \cite{cho2014gru,sutskever2014seq2seq}, we slightly modified the code by {\citet{tf_code}}, and we ran it on the two benchmarks provided in the repository. In particular, we used WMT datasets to train German-English and English-German models. We further used IWSLT datasets to train Vietnamese-English and English-Vietnamese models. We prepared the datasets according to the instructions found in the repository. For the German-English and English-German models, we used newstest2015 for testing. Both models are Seq2seq models with LSTM layers and attention mechanism. We used four VVMAs for the LSTM cells: for the forget gate, for the input gate, for the output gate, and for the cell state vector. We also used VVMAs for the matrices in the attention mechanism. For the Seq2seq-LSTM models, we decreased the gradient clipping value from 5 to 1 in order to prevent the gradient from overflowing. We also decreased the batch size to 32, to fit the models on a single GPU. We trained for 340,000 iterations for German-English and English-German, and 48,000 for Vietnamese-English and English-Vietnamese. The results comparing the original models with models that use VVMAs are shown in Table~{\ref{table:all:nmt}}. We can see that the BLEU scores decrease when using VVMAs, which should be expected given that the overall number of parameters in the model decreased noticeably. Overall, when taking into account the number of parameters, the observed decrease in the BLEU scores is very reasonable. \subsubsection{Transformer Models}\label{section:transformer} For the Transformer models {\cite{transformer}}, we replaced the matrices in the feed-forward layers with VVMAs.\footnote{We modified code from \url{github.com/tensorflow/models/tree/master/official/transformer}} We trained these models on WMT datasets for German-English and English-German translation. We prepared the datasets according to the instructions found in the repository that we modified. We used the base Transformer models with a hidden size of 512 (rather than the big models, which have a hidden size of 1024). We trained these models with a batch size of 2048 for 6 epochs. In Table~\ref{table:all:nmt}, we present our results on the Transformer models with VVMAs. We achieved reasonable BLEU scores compared to the original Transformer. For German-English, the original model had 61.4M parameters and an uncased test BLEU score of 29.66. The VVMA model had 37M parameters and a BLEU score of 28.5. For English-German, the original model had 61.4M parameters and a BLEU score of 24.57. The VVMA model had 37M parameters and a BLEU score of 23.13. To recap, each matrix in these models was replaced by VVMAs except for the embedding and the projection matrices. We found that restricting these with the VVMA constraints had a sizable negative impact on performance. \subsection{Theoretical Speedups}\label{section:speedups} We also calculated two measures for the inference time of the models described in Section~{\ref{section:nmt}}: (\emph{i})~the estimated number of clock cycles, and (\emph{ii})~the number of floating point operations (FLOPs). Both roughly correspond to the real time needed to perform the inference at run time. We computed the former for a TPU-style architecture with one matrix multiply unit of size $k \times k$, and we estimated the latter for the original and the VVMA models using Equations {\ref{original_clocks}} and {\ref{weight_sharing_clocks}} with $k=32$, $t=1$, and sequence lengths of 25. Note that the vector-vector operation before $M$ takes zero extra clock cycles, as illustrated in Figures {\ref{figure:1}} and {\ref{figure:2}}. This happens because we pipeline these vector-vector processes as we feed the data into the matrix multiply unit. Moreover, we initialize these operations while loading weights into the matrix multiply unit. We used a TensorFlow profiling tool in order to measure the number of FLOPs in our models. Looking at Table {\ref{table:all:nmt}}, we can see that the original Seq2seq-LSTM models require three to four times more clock cycles and roughly twice as many FLOPs compared to the VVMA models. For the Transformer models with VVMAs, we saw less noticeable speed-ups. For similar accuracy, the estimated number of clock cycles and FLOPs were roughly 1.7 and 1.5 times more in the original Transformer models compared to models with VVMAs. This is expected since we use VVMAs only in the feed-forward layers. We tried to use VVMAs for the attention layers as well, but this led to larger decrease in accuracy, due to the significant reduction in the number of parameters. As the Transformer is already getting noticeable impact in industrial settings, e.g.,~for machine translation and Web search, there is active research in developing more efficient Transformer architectures~\citep{Sanh2019DistilBERTAD, Kitaev2020ReformerTE,Beltagy2020LongformerTL,Zaheer2020BigBT}. Thus, with each new version of a Transformer architecture, new VVMA experiments would be needed in order to measure the potential improvements in efficiency that VVMA would yield. \subsection{Ablation Study} Next, we performed an ablation study for the Seq2seq-LSTM models described in Section {\ref{section:nmt}} for the English-Vietnamese machine translation task. In particular, we slightly modified the VVMAs in the Seq2seq-LSTM models by removing the diagonal terms ${D_{i, j}}$ or by changing the value of $k$. Here, we trained with a batch size of 32 for 48,000 steps. In order to prevent the gradient from overflowing, we needed to multiply the shared matrix $M$ by a scaling factor of 0.1 when removing the diagonal terms $D_{i, j}$. The results are shown in Table {\ref{table:2}}. We can see that removing the diagonal terms significantly decreases the BLEU scores for our models, while changing the value of $k$ has no significant impact. Additionally, Figure~\ref{figure:3} presents BLEU scores as the number of clock increases. We can see that compared to their original counterparts, VVMA models do not yield degradation in performance when then number of clocks gets large. \begin{table*}[tb] \centering \small \begin{tabular}{lccccrc} \toprule \bf Architecture & \bf $k$ & \bf Diags & \bf \# Params & \bf BLEU & \bf \# Clocks & \bf FLOPs \\ \midrule Original & N/A & N/A & 27.5M & 25.34 & 34.8M & 54.9M \\ VVMA & 32 & T & 17.1M & 24.42 & 10.3M & 34.1M \\ VVMA & 32 & F & 16.7M & 15.62 & 10.3M & 33.8M \\ VVMA & 16 & T & 17.4M & 24.76 & 22.7M & 34.8M \\ VVMA & 64 & T & 16.9M & 23.96 & 5.0M & 33.9M \\ \bottomrule \end{tabular} \caption{Ablation study for English-Vietnamese NMT with Seq2seq-LSTM models. Here, $k$ is the size of $M$ in VVMAs, Diags shows whether diagonal terms are present (T=true, F=false), then follow the number of parameters, BLEU score, number of clocks and FLOPs. Original's clock is on a TPU with a block size of 32.}\label{table:2} \end{table*} \begin{table}[tb] \small \centering \begin{tabular}{lrcccc} \toprule \bf Architecture & \multicolumn{1}{c}{\bf $k$} & \bf \# Params & \bf \# Clocks & \bf PPL \\ \midrule Original & N/A & 151.1M & 99.4M & 24.05 \\ VVMA & 32 & 138.2M & 67.0M & 30.70 \\ VVMA & 64 & 138.1M & 35.9M & 30.55 \\ QRNN & N/A & 151.0M & N/A & 33.0 \\ \bottomrule \end{tabular} \caption{ Language modeling on WikiText-103 using Transformer-XL with and without VVMA, as well as using QRNN. (Original: TPU with a block size of 32.) }\label{table:transformer-xl} \end{table} \subsection{Comparison to Standard Low-Rank Approximation} First, note that the rank of VVMA is maximum $k$ for a $k \times k$ sharing matrix. To prove that, we can represent the matrix in \eqref{shared_matrix} as a product of matrices of maximal rank $k$. Then, we can use the property that $\mathrm{rank}(AB) \leq \min(\mathrm{rank}(A), \mathrm{rank}(B))$. Second, we compare to low-rank approximation. We fix $k=128$ and we choose $n=$1,024; 2,048; 4,096. We sample a random matrix and we fit VVMA parametrization to it using Adam~\citep{Kingma2015AdamAM} with a learning rate of $0.0001$ ran for $30,000$ steps, and using the Frobenius norm as a loss. We do the same experiment with $UV^\top$ low-rank rank-$p$ approximation, where $p$ is chosen to match the number of parameters in VVMA. Additionally, we use Eckart--Young--Mirsky’s theorem to get the Optimal low-rank fit. Table~\ref{tbl:low-rank} shows some Frobenius norm losses from these experiments. We can see that VVMA's expressiveness is comparable to standard low-rank approximation; note, however, that standard low-rank approximation does not yield the inference speedups of VVMA. \begin{table}[tb] \small \centering \begin{tabular}{crrr} \toprule \bf $n$ / Fit ($\times 10^3$) & \bf VVMA & \bf Low-rank & \bf Optimal \\ \midrule 1,024 & 3.0 & 2.9 & 2.9 \\ 2,048 & 6.1 & 5.9 & 5.8 \\ 4,096 & 12.2 & 11.9 & 11.7 \\ \bottomrule \end{tabular} \caption{VVMA's closeness of fit to a target matrix is comparable to that of (\emph{i})~standard low-rank approximation and (\emph{ii})~optimal approximation, but it is orders of magnitude faster at inference time.}\label{tbl:low-rank} \end{table} \subsection{Extension to Language Modelling} Even though the main focus of this paper is the contribution of VVMA to neural machine translation, we also demonstrate that VVMA is compatible to state-of-the-art language modelling architectures. For that purpose, we perform an experiment on WikiText-103~\citep{Merity2017PointerSM} using the Transformer-XL model~\citep{Dai2019TransformerXLAL}. In this experiment, we directly integrate VVMA into the Transformer-XL architecture, keeping all hyper-parameter values as in the original Transformer-XL paper \cite{Dai2019TransformerXLAL}, except for reducing the batch size to 30, in order to fit the optimization on two GPUs. We chose to replace the weights of the attention mechanism with VVMA. Replacing the weights of the positional feed-forward layers drastically decreases the number of parameters, which yields poor performance, as Transformer-XL's perplexity is sensitive to the number of parameters. We present our results in Table~\ref{table:transformer-xl}, where we can see that VVMA with a block size of 256 yields reasonable performance, and the perplexity decreases noticeably with the reduction of parameters. \subsection{Extension to Other Areas} We further extended our VVMAs beyond NLP, to image classification. We modified the convolutional filters in ResNet \cite{he2016} to use VVMAs and we trained on CIFAR-10.\footnote{We modified code from \url{github.com/tensorflow/models/tree/master/official/resnet}} We prepared the CIFAR-10 dataset following the instructions in the repository we modified. We trained all ResNet models with a batch size of 128 for 250 epochs. Figure {\ref{figure:3}} bottom shows the accuracy of the ResNet models as a function of the number of parameters. We can see that the ResNet models with VVMAs outperform the original ResNet models when keeping the number of parameters fixed. \begin{figure}[tb] \begin{tikzpicture} \begin{semilogxaxis}[ width=7.8cm, height=5.8cm, xlabel=\# Clocks, ylabel=BLEU, mark size=2.25, legend cell align=left, legend pos=south east, legend entries={Original, VVMA}, tick align=outside, every x tick/.style={color=black, thin}, every y tick/.style={color=black, thin}, xlabel near ticks, ylabel near ticks, xtick pos=left, ytick pos=left, xtick={1000000, 10000000, 100000000}, scatter/classes={ original_legend={mark=cube*, fill=blue!50}, weight-sharing_legend={mark=square*, fill=yellow!50}, original2-128={mark=*, fill=blue!50}, original2-256={mark=triangle*, fill=blue!50}, original2-512={mark=square*, fill=blue!50, rotate=45}, original2-1024={mark=diamond*, fill=blue!50}, original2-2048={mark=pentagon*, fill=blue!50}, original4-512={mark=triangle*, fill=blue!50, rotate=180}, weight-sharing2-128={mark=*, fill=yellow!50}, weight-sharing2-256={mark=triangle*, fill=yellow!50}, weight-sharing2-512={mark=square*, fill=yellow!50, rotate=45}, weight-sharing2-1024={mark=diamond*, fill=yellow!50}, weight-sharing2-2048={mark=pentagon*, fill=yellow!50}, weight-sharing4-512={mark=triangle*, fill=yellow!50, rotate=180} weight-sharing98={mark=pentagon*, fill=yellow!50} } ] \addplot[scatter, only marks, scatter src=explicit symbolic] table[meta=label] { x y label 3928550 23.7 original2-128 11038650 25.1 original2-256 34803650 25.2 original2-512 120512850 24.5 original2-1024 444648050 23.3 original2-2048 2440550 20.7 weight-sharing2-128 4957050 22.9 weight-sharing2-256 10347650 24.4 weight-sharing2-512 22559250 24.8 weight-sharing2-1024 52704050 24.8 weight-sharing2-2048 }; \legend{Original, VVMA} \end{semilogxaxis} \end{tikzpicture} \begin{tikzpicture} \begin{semilogxaxis}[ width=7.8cm, height=5.8cm, xlabel=\# Parameters, ylabel=Accuracy, mark size=2.25, legend cell align=left, legend pos=south east, legend entries={Original, VVMA}, tick align=outside, every x tick/.style={color=black, thin}, every y tick/.style={color=black, thin}, xlabel near ticks, ylabel near ticks, xtick pos=left, ytick pos=left, xtick={10000, 100000, 1000000}, scatter/classes={ original_legend={mark=cube*, fill=blue!50}, weight-sharing_legend={mark=square*, fill=yellow!50}, original8={mark=*, fill=blue!50}, original14={mark=triangle*, fill=blue!50}, original32={mark=square*, fill=blue!50, rotate=45}, original50={mark=diamond*, fill=blue!50}, original98={mark=pentagon*, fill=blue!50}, original74={mark=triangle*, fill=blue!50, rotate=180}, original8_c8={mark=pentagon*, fill=blue!50, rotate=180}, original14_c8={mark=diamond*, fill=blue!50, rotate=90}, weight-sharing8={mark=*, fill=yellow!50}, weight-sharing14={mark=triangle*, fill=yellow!50}, weight-sharing32={mark=square*, fill=yellow!50, rotate=45}, weight-sharing50={mark=diamond*, fill=yellow!50}, weight-sharing98={mark=pentagon*, fill=yellow!50}} ] \addplot[scatter, only marks, scatter src=explicit symbolic] table[meta=label] { x y label 466970 92.47 original32 758618 93.03 original50 1147482 93.94 original74 1536346 94.24 original98 78106 87.4 original8 175322 90.87 original14 19922 80.96 original8_c8 44338 86.41 original14_c8 14026 82.81999826 weight-sharing8 23818 86.82000041 weight-sharing14 53194 89.8999989 weight-sharing32 82570 90.32999873 weight-sharing50 160906 91.76999927 weight-sharing98 }; \legend{Original, VVMA} \end{semilogxaxis} \end{tikzpicture} \caption{BLEU scores and validation accuracy as a function of the number of trainable parameters in the original and in the VVMA Seq2seq-LSTM models for English-Vietnamese (top) and ResNet~\citep{he2016} models on CIFAR-10 (bottom). The number of parameters is varied by changing the depth and the size of the hidden state. Unique shapes with different colors refer to the same Seq2seq-LSTM model, with the original model in blue and the VVMA model in yellow. }\label{figure:3} \end{figure} \section{Discussion} \label{discussion} Below, we discuss new AI hardware that could optimize inference for neural networks via VVMAs. This hardware would decrease latency at inference time rather than decreasing the training time. \paragraph{Tensor Processing Unit.} As mentioned above, Google's Tensor Processing Units (TPU) has a dedicated matrix multiply unit~\cite{tpu}. We believe that a modified version of the TPU could take advantage of VVMAs. The necessary modifications would be relatively simple. As illustrated in Figure~{\ref{figure:2}}, we would add a dedicated vector-vector unit before the matrix multiply unit, and we would pipeline it and initialize it at the same time as the matrix multiply unit. As seen in Section~\ref{section:speedups}, this would noticeably decrease the number of inference clock cycles in Seq2seq-LSTM models. \paragraph{Tensor Cores.} NVIDIA's newest GPUs have dedicated matrix multiply units called \emph{Tensor Cores}, which can perform $4 \times 4$ matrix multiplications in a single clock cycle {\cite{tensor_core}}. Adding vector-vector units before each Tensor Core would make them more efficient for VVMAs. The largest speedup would come from the time spent loading matrices from the memory into the Tensor Cores. For instance, if multiple Tensor Cores share the same matrix elements, this would decrease the latency when performing inference. \paragraph{Optical Processing Unit.} A newer, more experimental architecture, is to use VVMAs with optical computing. \citet{opu}~proposed to use an Optical Processing Unit (OPU) to perform matrix multiplications at the speed of light. Likewise, it is possible to use an OPU in order to accelerate inference on a neural network. Note, however, that the OPU would run into some of the same problems that the TPU has. That is, there will be a large delay when loading the matrix weights from the memory onto the OPU. Thus, we propose to add an electronic vector-vector unit before the OPU, which would be pipelined and initialized as weights are loaded onto the OPU. This extra unit will not increase the overall latency of a system that uses an OPU because the input vectors will still need to be fetched from the digital electronic memory. Likewise, performing vector-vector operations with the input data will not significantly increase the latency of the entire system. \section{Conclusion and Future Work} \label{conclusion} We have proposed a novel vector-vector-matrix architecture for low-latency inference, and we have demonstrated theoretical and empirical speed-ups for Seq2seq-LSTM and Transformer models, with application to neural machine translation, language modeling, and image classification. We hope that this work would bring the novel concept of AI \textit{co-design} (between software and hardware) to the domain of NLP applications. In future work, we plan to optimize the low-level code and to develop new hardware to deploy VVMAs in real-world applications. Distilling models to their VVMA counterparts would be an interesting experiment, and potentially an orthogonal enhancement to pre-existing frameworks~\citep{Sanh2019DistilBERTAD}. VVMAs could also be an orthogonal contribution to other factorizations of NLP models, such as in~\citep{Lan2020ALBERT}.
{'timestamp': '2020-10-19T02:18:12', 'yymm': '2010', 'arxiv_id': '2010.08412', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08412'}
arxiv
\section{Introduction} Sound source localisation applications can be tackled by inferring the time-difference-of-arrivals (TDOAs) between a sound-emitting source and a set of microphones. Among the referred applications, one can surely list room-aware sound reproduction \cite{b1}, room geometry's estimation \cite{b2,b3,b4,b5,b6}, speech enhancement \cite{b7,b21} and de-reverberation \cite{b8,b9,b10}. \textcolor{modifica}{Despite a broad spectrum of prior works estimate TDOAs from an known audio source \cite{KleinVo,Cavallaro,LasVegas}, even when the signal emitted from the acoustic source is \emph{unknown}, TDOAs can be inferred by comparing the signals received at two (or more) spatially separated microphones \cite{b10,b11,b14,b17,b18} using the notion of \textbf{cross-corrlation identity} (CCI) - see Fig. \ref{fig:CCI}. This is the key theoretical tool, not only, to make the ordering of microphones irrelevant during the acquisition stage, but also to solve the problem as \emph{blind} channel identification \cite{b10,b11,b14,b17,b18}, robustly and reliably inferring TDOAs from an unknown audio source (see Sec. \ref{sec:probl-stat-nd-relwork}).} \begin{figure}[t!] \centering \includegraphics[width=\columnwidth]{images/figure_paper_1.png} \caption{We are given an unknown sound-emitting source, where in the actual applicative scenario that we encompass, we have no prior knowledge about the sound source and can be therefore arbitrary. We are interesting in (robustly) inferring TDOAs in an (unknown as well) environment given a pool of microphones, using the the following principle. Given the pair of grey microphone, the audio that each of them acquires from the source (solid arrow) must ``agree'' with the other. That is, if any of the two mic could ``hear'' the other, the registered signal has to be the very same (dashed arrows). This is called \emph{cross-correlation identity} and it was empirically studied in the case $N =2$, only. In this paper we answer to what happens then if $N > 2$? Can we improve in robustness and/or accuracy in the estimate, for instance, by adding the yellow microphones?} \label{fig:CCI} \end{figure} However, when dealing with natural environments, such ``mutual agreement'' between microphones can be tampered by a variety of audio ambiguities such as ambient noise. Furthermore, each observed signal may contain multiple distorted or delayed replicas of the emitting source due to reflections or generic boundary effects related to the (closed) environment. Thus, robustly estimating TDOAs is surely a challenging problem and CCI-based approaches cast it as single-input/multi-output blind channel identification \cite{b10,b11,b14,b17,b18}. Such methods promotes robustness in the estimate from the methodological standpoint: using either energy-based regularization \cite{b11}, sparsity \cite{b10,b17,b18} or positivity constraints \cite{b17}, while also pre-conditioning the solution space \cite{b10}. In this paper, we posit that there is a much easier practical strategy to ensure robustness while inferring TDOAs: \emph{the possibility of exploiting a larger pool of microphones}. In fact, it is surprising to observe that, in prior state-of-the-art methods based on CCI, experimental evidences are provided for the case $N = 2$ microphones only \cite{b10,b11,b14,b17,b18}. Despite such a number is the bare minimum to solve the problem, it remains elusive whether $N > 2$ can, \emph{by itself}, boost the estimate of TDOAs in accuracy/robustness, without requiring any changes in the computational pipeline. In fact, since all methods \cite{b10,b11,b14,b17,b18} can \emph{theoretically} accommodate for $N > 2$, why not test them in such a regime? The purpose of this work is to answer this question and back up the investigation of state-of-the-art methods based on CCI \cite{b10,b11,b14,b17,b18} in handling the case $N > 2$. Our goal is to understand whether an increase in the number of microphones will translate into an improved TDOAs estimate. {\bf Our contributions.} Among all state-of-the-art methods based on CCI \cite{b10,b11,b14,b17,b18}, we consider the most effective one: IL1C \cite{b10}. \textcolor{modifica}{Despite, in fact, recent advances were essentially devoted in estimating TDOAs given a known audio source in how to exploit the TDOAs \cite{KleinVo,Cavallaro,LasVegas}, the problem of achieving the very same task while being blindly unaware of which audio source was deployed can be still efficiently and effectively solved using methods such as \cite{b10,b11,b14,b17,b18} out of which IL1C \cite{b10} is the best in terms of robustness and efficacy. IL1C} infers TDOAs by solving a stack of convex problems through a weighted sparsity promoting ($\ell^1$) constraint, leveraging the non-negativity of the Acoustic Impulse Response (AIR), from which TDOAs are easily estimated using peak finding \cite{b10}. To guarantee robustness while inferring TDOAs, in addition to sparsity, IL1C \cite{b10} takes advantage of a pre-conditioning mechanism to better initialize the AIRs using a data-driven initialization. We setup a broad experimental validation, measuring the performance of IL1C on a variety of audio signals, going well beyond the experimental evidences provided in \cite{b10}. That is, on the one side, we test the effectiveness of this method on many more audio signals: synthetic (pink and white) noise and a list of natural audio sources (two different plastic rustles -- obtained from either scraping a bag or compacting a bottle before thrashing, adult male voice, dog barking, stapler and hand-clapping). On the other side, differently to \cite{b10}, we do not only consider the case $N =2$, but we also consider a bigger number of microphones $N=3, 4, 5, 10$ motivated by encompassing the scenario of multiple microphones. As our experimental evidences show, we stably register improvements in either the robustness (towards outliers) or the accuracy in retrieving the peaks of the AIRs. We evaluate on that by exploiting two well known performance metrics as in prior work \cite{b10,b11,b14,b17,b18}, and, although there are (sound-specific) cases in which one of the two indicators show a damaged performance, still the other one shows improvements. In fact, we can demonstrate that, across the wide number of different audio sources that we consider, the general trend is that, while averaging the absolute improvement across different choices for $N =3, 4, 5$ or $6$ over the baseline case $N =2$, we score positive signed improvements (see Table \ref{tab:improvementsIL1C}) which seems not to be effected on whether the source is emitting synthetic or natural sounds. At the same time, we register a very positive trend if we are enriched by an oracle knowledge of the optimal number of microphones that have to be arranged before the acquisition stage. In such a case, we \emph{always} register positive improvements over the baseline $N = 2$, which are, in the worst case, by $+3\%$, while achieving more than $+28\%$ as well. Inspired by our evidences, in Section \ref{sez:future_perspectives}, we attempt to warm up future research directions towards optimization approaches which explicitly account for the case $N > 2$. Although proposing a new paradigm which falls inside this new family of methods is out of scope for us, we still deem interesting to inform practitioners about the effect of two straightforward modifications of IL1C \cite{b10}, using either an incremental pre-conditioning or an ensemble strategy - see Section \ref{sez:future_perspectives}. Regardless of the scores results (in which the ensemble strategy is better than the incremental pre-conditioning, while also improving the baseline IL1C method \cite{b10}), we deem our effort to be effective in stimulating the research towards methods which explicitly account for the case $N > 2$ when dealing with an unknown audio source. \section{Problem Statement \& Related Work}\label{sec:probl-stat-nd-relwork} Let us formalize the problem of inferring TDOAs, so that we can easily refer to prior related works. Let us consider a given enviroment (e.g., a room) of unknown geometry in which an audio source emits together with $N$ microphones: the task is to reconstruct TDOAs. Let $\vec{h}_n$ represent the AIR (Acoustic Impulse Response) from a fixed audio source and the $n$-th microphone, $n = 1,\dots,N$. The signal $\vec{h}_n$ is sampled into a fixed number of temporal bins $\vec{h}_n(k)$. The signal $y_n(k)$ received at microphone $n$ can be written as the discrete convolution between the transmitted signal $x(k)$ and the $n$-th AIR: \begin{equation} y_n(k) = \vec{h}_n(k) \ast x(k)+\nu_n(k), \hspace{0.5 cm} n = 1,\ldots,N \label{eq:conv} \end{equation} where $\nu_n(k)$ is an additive noise term. The ultimate goal of the problem is leveraging the measurements $y_n(k)$ to recover the AIRs $\vec{h}_n(k)$ without knowing the transmitted signal $x(k)$. \vspace{5 pt} \noindent \emph{Cross-correlation identity}. When multiple microphones are recording the same audio source, the acquisition should be independent of the order of the microphones according to the following constraint: \begin{equation}\label{eq:cri} \vec{h}_m(k)~\ast~\vec{h}_n(k)~\ast~x(k) = \vec{h}_n(k)~\ast~\vec{h}_m(k)~\ast~x(k), \end{equation} for every pairs of microphones $m$ and $n$. In turn, using eq. \eqref{eq:conv}, we rewrite eq. \eqref{eq:cri} as $\vec{h}_m(k)~\ast~y_n(k) = \vec{h}_n(k)~\ast~y_m(k)$. Hence, by using the well-known fact that the convolutional operator $\ast$ is linear, we obtain \begin{equation}\label{eq:cri-mat} \mat{Y}_n \vec{h}_m = \mat{Y}_m \vec{h}_n, \hspace{1cm} m,n = 1,\dots,N \end{equation} where $\vec{h}_n$ is the column vector which stacks the AIRs $\vec{h}_n(k)$ by columns, while $\mat{Y}_n$ is the diagonal-constant matrix with first row and column given by $[y_n(k - K + 1), y_n(k - K), \ldots , y_n(k - K - L + 2)]$ and $[y_n(k - K + 1), y_n(k - K +2), \ldots , y_n(k), 0, \ldots , 0]^\top$ respectively, with $K$ and $L$ being the signal length and channel length. In order to solve for \eqref{eq:cri-mat}, a number of prior approaches have took advantage of regularization \cite{b11,b10}. For instance, Tong \textit{et al.}~ \cite{b11} have framed the problem of TDOAs estimation as the following regularized Least Squares fitting \begin{equation}\label{eq:tong94} \underset{\vec{h}_1,\dots,\vec{h}_N}{min}\sum_{m\neq n}\|\mat{Y}_n\vec{h}_m-\mat{Y}_m\vec{h}_n\|_2^2 \hspace{0.4 cm} {\rm s.t.} \sum_i \| \vec{h}_i \|_2^2 = 1, \end{equation} to ensure robustness by means of regularization. Clearly, adding a regularization term is fundamental to avoid the optimization to converging towards the trivial solution $\vec{h}_n = 0$ for every $n = 1,\dots,N.$ Remarkably, the real problem is choosing a proper regularization term. In fact, when using $\ell^2$ regularization - as in eq. \eqref{eq:tong94}, the solution can be computed in closed-form by means of eigenvalue decomposition \cite{b11}. Unfortunately, $L^2$ regularization neglects some crucial physical properties of the expected solution - such as non-negativity \cite{b13,b14}. Additionally, requiring $\sum_i \|\vec{h}_i\|^2_2 = 1$ as in \eqref{eq:tong94} makes the AIRs to be co-prime\cite{b15} and constraint each of them to have a fixed norm - each of such requirements are likely to introduce numerical instabilities and artifacts during the optimization process. As a remedy for this, sparsity priors have been successfully applied to a broad spectrum of prior work in TDOAs estimation~\cite{b1,b2,b3,b4,b5,b6} \cite{b15}, while also encompassing speech enhancement \cite{b16} and de-revereberation \cite{b8}. Therefore, as to impose sparsity in the reconstructed $\vec{h}_n$, replacing the $L^2$ regularization in eq. \eqref{eq:cri-mat} with a $L^1$ counterpart \cite{b17,b18,b10} seems an appealing solution. Precisely, in \cite{b18} a $L^1$-norm penalty was added to eq. \eqref{eq:tong94}, yielding \begin{equation}\label{eq:kow13} \underset{\vec{h}_1,..,\vec{h}_N}{min}\sum_{m\neq n}\|\mat{Y}_n\vec{h}_m-\mat{Y}_m\vec{h}_n\|_2^2 \hspace{0.1cm} s.t. \begin{cases} \sum_i\|\vec{h}_i\|_2^2 = 1, \\ \sum_i \|\vec{h}_i\|_1 < \varepsilon. \end{cases}. \end{equation} Unfortunately, a quadratic optimization subject to mixed quadratic and linear constraints do not preserve the convexity of \eqref{eq:tong94}. Hence, the method as in \eqref{eq:kow13} is prone to local solutions. To cope with this issue, we can relax eq. \eqref{eq:cri-mat} into \begin{equation}\label{eq:Lin07} \underset{\vec{h}_1,..,\vec{h}_N}{min}\sum_{m\neq n}\|\mat{Y}_n\vec{h}_m-\mat{Y}_m\vec{h}_n\|_2^2 \hspace{0.1cm} s.t. \begin{cases} |\vec{h}_1(a)| = 1, \\ \sum_i \|\vec{h}_i\|_1 < \varepsilon. \end{cases}, \end{equation} where the fixed index $a$ is an anchor constraint \cite{b17} which makes the optimization in eq. \eqref{eq:Lin07} convex and more robust towards spectrum holes of $x(k)$ if compared to eq. \eqref{eq:tong94}. However, the anchor constraints $|\vec{h}_1(a)| = 1$ together with $\sum_i \| \vec{h}_i \|_1 < \varepsilon$ penalizes all the peaks intensities but one, often leading to peak cancellations in noisy conditions. The approach of \cite{b17} has been modified in \cite{b14} adding an ancillary non-negativity constraint on the AIRs \begin{equation}\label{eq:Lin07NNeg} \underset{\vec{h}_1,..,\vec{h}_N}{min}\sum_{m\neq n} \hspace{-0.1cm} \|\mat{Y}_n\vec{h}_m-\mat{Y}_m\vec{h}_n\|_2^2 \hspace{0.1cm} s.t. \begin{cases} |\vec{h}_1(a)| = 1, \\ \sum_i \|\vec{h}_i\|_1 < \varepsilon \\ \vec{h}_1,..,\vec{h}_N\geq0 . \end{cases}, \end{equation} where, for each $n$, $\vec{h}_n\geq0$ means $\vec{h}_n(k)\geq0$ for each $k$. Non-negativity yields increased robustness against noise by further regularizing the problem \cite{b19,b20}, but it is arguably limited in addressing the limitations of the anchor constraints. To directly tackle the latter problem, Crocco \textit{et al.}~ \cite{b10} replaced the anchor constrained $|\vec{h}_1(a)| = 1$ by means of the introduction of a slack variables $\vec{p}_1,\dots,\vec{p}_N$ such that \begin{equation}\label{eq:Crocco16} \underset{\vec{h}_1,..,\vec{h}_N}{min}\sum_{m\neq n} \hspace{-0.1cm} \|\mat{Y}_n\vec{h}_m-\mat{Y}_m\vec{h}_n\|_2^2 \hspace{0.1cm} s.t. \begin{cases} \vec{p}_n^{\hspace{0.5mm}\top}{\vec{h}}_n = 1, \\ \sum_i \|\vec{h}_i\|_1 < \varepsilon \\ \vec{h}_1,..,\vec{h}_N\geq0 . \end{cases} \end{equation} In this way, all the components of the AIRs are equally taken into account without privileging the $a$-th of the $\vec{h}_1$. At the same time, differently from eqs. \eqref{eq:kow13}, \eqref{eq:Lin07}, the constraints as in eq. \eqref{eq:Crocco16} are differentiable, since $\vec{h}_1,..,\vec{h}_N\geq0$ implies $\sum_i \| \vec{h}_i \|_1 = \sum_i \sum_a \vec{h}_i(a).$ The optimization problem as in eq. \eqref{eq:Crocco16} is convex with respect to $\vec{h}_n$ while fixing the slack variables $\vec{p}_n$ and vice-versa. Inspired by this consideration, Crocco \textit{et al.}~ \cite{b10} proposed an alternated iterative scheme in which, $\vec{p}_n$ are firstly initialised as the AIRs computed using Tong \textit{et al.}~ method's \cite{b11}, while cycling between: 1) optimizing for $\vec{h}_1,..,\vec{h}_N$ in \eqref{eq:Crocco16} given $\vec{p}_1,..,\vec{p}_N$ and 2) use the newly computed AIRs to update $\vec{p}_n$ for every $n$. As discussed in \cite{b10}, although the proposed initialization introduces a distortion in the amplitude of the AIRs, then the iterative procedure is able to compensate. More crucially, initializing $\vec{p}_n$ at the first iteration by using \cite{b14} makes the slack variable sparse. Therefore, the first two constraints as in eq. \eqref{eq:Crocco16} make the computed AIRs sparse again. Such property is preserved during optimization because of the updating scheme in which slack variables at a given iteration are selected as the solution of eq. \eqref{eq:Crocco16} as in the prior iteration. \vspace{ 5 pt} \noindent \underline{\emph{A sharp limitation of prior blind methods}}. None of the prior methods \cite{b10,b11,b14,b17,b18} was generalized to the case $N > 2$. Despite $N = 2$ has the appealing formal property of achieving minimality among the number of microphones necessary to solve the optimization problem, still it remains elusive from a practical standpoint whether allocating for a bigger number $N$ of microphones can effectively boost the estimate of TDOAs. And, in the likely event of this case effectively happening, are we improving upon robustness towards outliers or in accuracy as well? The scope of the present work is to answer this question. \section{Multiple Cross-Correlation Identities}\label{sez:multiple_CCI} In this Section, we evaluate the effect of increasing the number of microphones when tackling the problem of inferring TDOAs by means of well established notion of cross-correlation identity (CCI) \cite{b10,b11,b14,b17,b18}. In details, we focus on IL1C \cite{b10}, the best out of such class of approaches: we optimize equation \eqref{eq:Crocco16} for the case of $N = 2,3,4,5,10$. By doing so, we are capable of starting from the minimal setup from which the problem can be solved ($N = 2$): note that this is the experimental playground analysed in prior works \cite{b10,b11,b14,b17,b18}. Differently, for the sake of inspecting whether a higher number of microphones can provide an improvement in the estimate of TDOAs, we also consider the cases $N=3,4,5$ up to the $N = 10$ microphones. This range of variability in $N$ is, in our opinion, a good trade-off between having a sufficiently large number of acquisition devices, while still framing a scenario which can be still useful from the applicative standpoint. Let us briefly introduce the types of source signals considered in this study, as well as the reproducibility and implementation details about our evaluation protocol and the error metrics to check on performance. The results of our analysis are reported in Tables \ref{tab:all_EPP} and \ref{tab:all_PUP}, while showing relative and absolute improvements in Table \ref{tab:improvementsIL1C}. An extended discussion on our findings is reported in Section \ref{ss:discussion_IL1C_N}. \begin{table*} \centering \caption{Average Peak Position Mismatch ($\mathcal{A}_{\rm PPM}$)) metrics for IL1C \cite{b10} when $N=2,3,4,5,10$. Synthetic source noise are denoted in italic, while bold italic refers to the natural source signal considered in this study. For each source signal considered, we provide an histogram visualization to better perceive the variability of the error metrics: the range of variability of each data bar is normalized within each different source signal. A better performance corresponds to a lower ($\mathcal{A}_{\rm PPM}$)) value or, equivalently, to a lower bar. The value $s$ quantifies the impact of the additive Gaussian noise on the registered signal: we span the case $s=0.01$ (easier) to $s=1$ (harder), while transitioning on the intermediate cases $s=0.1,0.2$ and $s=0.5$.} \label{tab:all_EPP} \includegraphics[width = .8\textwidth]{images/EPP.png} \end{table*} \begin{table*} \centering \caption{Average Percentage of Unmatched Peaks ($\mathcal{A}_{\rm PUP}$) metrics for IL1C \cite{b10} when $N=2,3,4,5,10$. Synthetic source noise are denoted in italic, while bold italic refers to the natural source signal considered in this study. For each source signal considered, we provide an histogram visualization to better perceive the variability of the error metrics: the range of variability of each data bar is normalized within each different source signal. A better performance corresponds to a lower ($\mathcal{A}_{\rm PUP}$)) value or, equivalently, to a lower bar. The value $s$ quantifies the impact of the additive Gaussian noise on the registered signal: we span the case $s=0.01$ (easier) to $s=1$ (harder), while transitioning on the intermediate cases $s=0.1,0.2$ and $s=0.5$.} \label{tab:all_PUP} \includegraphics[width = .8\textwidth]{images/PUP.png} \end{table*} \vspace{5 pt} \textit{The different types of source signals we considered.} \textcolor{modifica}{We considered two types of synthetic audio signals \textit{white noise} and \textit{pink noise}, which differ among each others in the considered frequencies of their spectrum (all vs. only wide ones, respectively). We also encompass a broad list of natural sounds as audio source: \textbf{\textit{plastic rustle no. 1 (bag)}}, \textbf{\textit{plastic rustle no. 2 (bottle)}}, \textbf{\textit{adult male voice}}, \textbf{\textit{dog barking}}, \textbf{\textit{stapler}} and \textbf{\textit{hand-clapping}}, all of them characterized by a narrow frequency spectrum.} \vspace{5 pt} \textit{Evaluation.} We run experiments by considering any of the source audio signals described in the prior paragraph located in the same environment analyzed in \cite{b10}. We model the Acoustic Impulse Response (AIR) for each microphones as seven different peaks, corresponding to one direct path source-microphones, together with six (first-order) reflections. In details, we applied the simulating image method as in \cite{b16}, using a reflection coefficient of $0.8$. We also introduce another degree of variability, by considering different Noise-to-Signal ratios ($s$). This is done by injecting additive Gaussian white noise on the output microphones according to the following specs: $0$ dB, $6$ dB , $14$ dB, $20$ dB and $40$ dB. This induces a signal-to-noise ratio $s=10^{-\mathrm{dB}/20}$ from the following inverse relationship $\mathrm{dB}=20 \log_{10}(1/s)$. When running the optimization \eqref{eq:Crocco16} of IL1C \cite{b10}, we take advantage of the official code directly shared by authors, while following the same pre-processing and evaluation techniques as in the referred prior work. In addition, as done \eqref{eq:Crocco16}, we perform model selection by doing cross-validation on the threshold $\varepsilon$ which controls the sparsity-promoting constraint. \vspace{5 pt} \textit{Error metrics.} Once the AIRs have been computed through \eqref{eq:Crocco16}, we apply the peak finding method of \cite{b10} and we evaluate performance by means of two standard error metrics: the Average Peak Position Mismatch ($\mathcal{A}_{\rm PPM}$) and the Average Percentage of Unmatched Peaks ($\mathcal{A}_{\rm PUP}$) \cite{b15}. To ensure statistical robustness towards the random generation of reflections using \cite{b16}, we performed $Z = 50$ random repetitions of the experiments using Monte-Carlo simulation \cite{b10}. A ground truth peak is considered to be unmatched if the closest estimated number is more than a fixed number of samples aways from it (we follow \cite{b10} in setting this value equal to 20). In formul\ae, we compute $\mathcal{A}_{\rm PPM}$ and $\mathcal{A}_{\rm PUP}$ in the following manner \begin{align} \mathcal{A}_{\rm PPM} & = \dfrac{1}{Z} \sum_{i=1}^{Z}\sum_{p=1}^{\bar{P}_i}\frac{|\tau_{p,i}-\widetilde{\tau}_{p,i}|}{\bar{P}_i} \label{eq:PPM} \\ \mathcal{A}_{\rm PUP} & = \dfrac{1}{Z} \sum_{i=1}^{Z}\frac{K-\bar{P}_i}{K} \label{eq:PUP} \end{align} where $\bar{P}_i$ is the number of ground truth peaks for which a matching has been found among the estimated ones: such value is indexed over the Monte-Carlo simulations $i = 1,\dots,Z$. For every $i$ and given an arbitrary $p = 1,\dots,P_i$ $\tau_{p,i}$, in eq. \eqref{eq:PPM}, $\tau_{p,i}$ and $\widetilde{\tau}_{p,i}$ are the $p$-th ground truth peak location and its corresponding estimate, respectively. In eq. \eqref{eq:PUP}, $K$ denotes is the number of ground truth peaks of the source signal. By means of such metrics, we can decouple the effect of the outliers (quantified by $\mathcal{A}_{\rm PUP}$) from the overall peak position accuracy (expressed by $\mathcal{A}_{\rm PPM}$), ultimately better evaluating on the robustness with which TDOAs are estimated. \section{The proposed Test-Case: a Discussion}\label{ss:discussion_IL1C_N} \vspace{5 pt} \emph{Performance differences across variable $s$ values.} An increasing value for $s$ will make the acquired signal noisier, so that, in Tables \ref{tab:all_EPP} and \ref{tab:all_PUP} the case $s = 0.01$ is (much) easier with respect to $s = 1$. This visually translates into errors (and histogram bars) which increase when moving from left to right in the referred error tables. A sharp increase of errors is registerd on \emph{white noise} (synthetic) and \textbf{\textit{bag plastic ruslte}}, \textbf{\textit{adult male voice}} and \textbf{\textit{dog barking}} (natural). Differently, on either pink noise (synthetic) or stapler, hand-clapping (natural), we can see that already the case $s = 0.01$ is challenging per se. We posit that a reason for that is the highly oscillatory natura of those sounds that, if compared to other cases, make them less influeced by the additive Gaussian noise (since they behave as if they were intrinsically noisy) \JC{Danilo per favore rileggi questo paragrafo bene e dimmi se possiamo trovare una spiegazione meno tirata per i capelli della mia per piacere!} \vspace{5 pt} \emph{Differences between synthetic and natural sound-emitting sources.} Let us comment on whether the usage of a synthetic versus a natural source emitting sound can have an impact on the final performance. According to the experimental results reported in Tables \ref{tab:all_EPP} and \ref{tab:all_PUP}, while also inspecting the signed absolute/relative improvements of Table \ref{tab:improvementsIL1C}, we can get that there seems not to be a sharp difference in performance between these two categories. In fact, we did not register any drop/raise when swapping from white/pink noise to the other sounds considered in this work. We deem this a valuable property of the cross-correlation identity (CCI) which can naturally accommodate for a variety of applicative scenarios where the audio source is unknown. \vspace{5 pt} \underline{\textit{\textbf{Does adding microphones improves upon performance?}}} We are intended in enriching this discussion with a detailed analysis on the ultimate question that our work is trying to respond. We believe that the findings of Tables \ref{tab:all_EPP} and \ref{tab:all_PUP} are plain: the honest answer to the aforementioned question we are intended to respond is neither positive nor negative, \emph{in general}. In fact, there is a quite number of cases in which the addition of microphones is not clearly beneficial, on the contrary damaging performance: for the sake of brevity, let us report the worst cases for the two metrics. That is, the cases $s=1$, $N=10$ and \textbf{\textit{hand-clapping}} for $\mathcal{A}_{\rm PPM}$ (-1.4031 absolute improvement) and $s=1$, $N=4$ and \textbf{\textit{adult male voice}} for $\mathcal{A}_{\rm PUP}$ (-0.0393 absolute improvement). These are definitely failure cases and, specifically, \textbf{\textit{hand-clapping}}, $s=1$ for $\mathcal{A}_{\rm PPM}$ is clearly not positive since the trend is that performance drops while $N$ increases. Albeit these cases are surely negative, let us observe that there are actually no cases where \emph{concurrently} the two metrics deteriorate. In fact, in the worst cases, only one of the two is damaged: we either loose in effectiveness on how we handle outliers or in how accurately we retrieve the peaks. But, globally the case $N > 2$ is never inferior to the baseline $N =2$ with respect to both metrics concurrently. At the same time, let us observe that these failure cases are limited since, in the majority of the (remaining) cases, the performance is either stable (therefore adding microphones is not detrimental) or better (and thus addding microphones actually help). The fact that performance is stable when varying the number of microphones is true for the (less noisy) cases $s = 0.01$, \textit{pink noise}, for $\mathcal{A}_{\rm PPM}$; $s = 0.01$, \textbf{\textit{adult male voice}}, for both $\mathcal{A}_{\rm PPM}$ and $\mathcal{A}_{\rm PUP}$; $s = 0.01$, \textit{pink noise}, for $\mathcal{A}_{\rm PUP}$; $s = 0.01$ \textit{\textbf{dog barking}}, for $\mathcal{A}_{\rm PPM}.$ Finally, let us concentrate on the ideal cases, where the performance improves when $N$ raises. This happens for (the more challenging) cases such as $s=1$ \textit{\textbf{dog barking}}, for $\mathcal{A}_{\rm PPM}$; $s=0.5$ \textit{\textbf{adult male voice}}, for $\mathcal{A}_{\rm PPM}$; $s=0.1$, \textit{\textbf{stapler}}, for $\mathcal{A}_{\rm PPM}$ and $s=0.5$, \textit{\textbf{adult male voice}}, for $\mathcal{A}_{\rm PUP}$, $s=0.1$ and $s=0.2$, \textit{\textbf{plastic rustle no. 2 (bottle)}} for $\mathcal{A}_{\rm PUP}$; $s=0.2$, \textit{\textbf{dog barking}} for $\mathcal{A}_{\rm PUP}$. Given the alternate nature of the results, when switching from one error metric to another and while varying different $s$ and $N$ values, we deem necessary to summarize the highlights of our findings in the next part of our discussion. \vspace{5 pt} \underline{\textit{\textbf{A summary of the improvements.}}} In Table \ref{tab:improvementsIL1C} (bottom), we report the average absolute signed improvement $\delta_{\rm avg}$ over the two error metrics $\mathcal{A}_{\rm PPM}$ and $\mathcal{A}_{\rm PUP}$: the overall majority of the cases show a superiority of the case $N > 2$ with respect to the baseline case $N = 2$ of IL1C \cite{b10}. This is exemplified from the fact that the signed improvement is positive ($\delta_{\rm avg} > 0$) for 5 out of 8 different audio signals, in terms of $\mathcal{A}_{\rm PPM}$, and 7 times out of 8, in terms of $\mathcal{A}_{\rm PUP}$. Despite of their sign, the absolute value of such improvements is controlled (it never exceeds $0.5$). This trend is explained from the fact that, there are high fluctuations, sometimes, between different configurations inside the case $N>2$ for an unknown audio source. To better investigate this trend, we also consider the signed relative improvements $\Delta^O$ of the error metrics $\mathcal{A}_{\rm PPM}$ and $\mathcal{A}_{\rm PUP}$ (Table \ref{tab:improvementsIL1C}, top). In this case, we allow for an oracle selection of the best number $N$ of the microphone configuration so that we can understand what is the ``upper'' bound on the improvement that we can expect to register. The results are extremely encouraging: we \emph{always} have significant positive improvements. In the worst cases (\textit{\textbf{plastic rustle no. 2 (bottle)}}, $\mathcal{A}_{\rm PPM}$), we get a +2.8\% while, in the most favorable case (\textit{\textbf{adult male voice}}, $\mathcal{A}_{\rm PPM}$), the relative improvement sharply raises, reaching +28.4\%. \begin{table}[t!] \centering \caption{Signed improvements for the metrics $\mathcal{A}_{\rm PPM}$ and $\mathcal{A}_{\rm PUP}$ when comparing $N > 2$ with the baseline $N=2$ using the state-of-the-art method \cite{b10}. \emph{Top}: we provide the percentage relative improvements $\Delta^O$ using the oracle selection for microphone number's configuration (reported as a superscript). \emph{Bottom}: We provide the mean absolute improvement $\delta_{\rm avg}$ across \emph{all} cases $N=3,4,5,10$ with respect to the baseline $N=2$. \emph{Top and Bottom}: We report the aforementioned statistics for the more challenging noise-to-signal ratio $s=1$.} \label{tab:improvementsIL1C} \includegraphics[width=\columnwidth]{images/tb.PNG} \end{table} \section{Future Perspectives}\label{sez:future_perspectives} In shed of the results of our test-case (Table \ref{tab:improvementsIL1C}), we deem now reasonable for practitioners to start investigating the regime $N > 2$ (unknown source) with computational methods which take advantage of this scenario in explicit terms. Although this actual effort is beyond the scope of the present submission, we are nevertheless interested in warming up the research in this direction by considering what are, to our opinion, the easiest modification that can be applied to the state-of-the-art method IL1C \cite{b10}. In the rest of the present Section, we will present two computational variants of IL1C which are either based on an \emph{incremental pre-codintioning} or an \emph{ensemble mechanism}. \textit{\textbf{Incremental pre-conditioning}}. Given the core contribution of pre-conditioning the solution that IL1C introduced, we can think about an \emph{incremental} preconditioning in which we gradually introduce one microphone, intertwining this operation with a fine-tuning of the AIRs. That is, we start from a pair of microphones and we optimize for it. Then, we use the solutions of IL1C for that pair to pre-condition the solution when solving for a third microphones: we the update also the AIRs for the first two microphones. The procedure iterates until the $N$-th microphones is added (so that the $N-1$ AIRs of the other microphones are fine-tuned, at least one time). Let us formalize the prior argument in the following pseudocode.\\ {\bf 1}. Sample two random microphones $m_1$, $m_2$.\\ {\bf 2}. Optimize eq. \eqref{eq:Crocco16}, using the \emph{standard} pre-conditioning \cite{b10}, thus obtaining the AIRs for $m_1$ $m_2$.\\ {\bf 3}. Add a third microphone $m_3$: optimize eq. \eqref{eq:Crocco16} again but now changing the preconditioning. The AIRs of $m_1$ and $m_2$ will be the ones obtained at the previous stage, while the AIR of $m_3$ will be initialized using the standard approach \cite{b10}.\\ {\bf 4}. Update the AIRs for all solved microphones.\\ {\bf 5}. Keep adding microphones, following the same procedure, until all $N$ ones are covered \emph{Results \& Discussion}. We did not register any substantial improvement using this sequential addition, to the point that even the case $N = 2$ is superior in performance. For the sake of brevity, let us report a glance of the scored results, providing a peculiar case which is aligned with the general trend which we do not report for the sake of brevity. For \textit{white noise}, the results of incremental strategy describe above are 0.0036 ($s=0.01$), 0.0357 ($s=0.1$), 0.09 ($s=0.2$), 0.1536 ($s = 0.5$) and 0.2343 ($s=1$) for $\mathcal{A}_{\rm PUP}$ and 0.2658 ($s=0.01$), 0.5866 ($s=0.1$), 1.0023 ($s=0.2$), 1.7345 ($s=0.2$) and 2.2391 ($s=1$) for $\mathcal{A}_{\rm PPM}$ -- all error values refer to the case with $N=4$, while averaging over $Z=50$ random extraction of the sequence with which microphones are incrementally added. We explain this lack of improvement with the fact that, despite adding microphones \emph{in a single solution} maybe beneficial, their sequential addition can be detrimental since, albeit on the one side the case $N > 2$ is providing more cues than the baseline $N =2$, the sequential addition of microphone would lead to ``over-fitting'' the AIRs of some of the microphones, ultimately damaging the final performance. \textit{\textbf{Ensemble mechanism}}. Let us observe that the inference stage of IL1C \cite{b10} is based on peaks finding, a method which is known to suffer when spurious peaks are present. To accommodate for that, let us take advantage of the following approach. We can split the case $N > 2$ into several $N = 2$ sub-problems, by pairing microphones into couples. We therefore create a number of playgrounds with 2 microphones only (unknown source) - so that we match the operative conditions on which IL1C \cite{b10} was originally tested. We therefore create some redundancy in the estimate of the AIRs: this is because one microphone can belong to several pairings at the same time, so there will be multiple candidate solutions for the same AIRs - two candidates, referring to two different microphones, from each artificial pairing. We solve for this redundancy by averaging out all different candidates referring to the same microphone. We deem this approach to be arguably simple, perhaps rough, but still effective in handling a well known computational issue which damages peak findings algorithm. In fact, the presence of spurious (noisy) peaks surely affect the estimate of TDOAs. We attempt to mitigate this problem by exploiting the well known smoothing and regularizing properties of averaging as our ensemble mechanism. \emph{Results \& Discussion}. The reader can refer to Table \ref{tab:medie} for the quantitative evaluation of our ensemble strategy applied to IL1C \cite{b10} evaluated in the test-case $N = 10$. We are expecting to register a very interpretable phenomenon out of a simple strategy such as averaging multiple candidate solutions corresponding to the same AIR: we should expect to register a regularizing effect which smooths out the AIRs, removing spurious peaks due to, for instance, numerical instability. This explains the improvements achieved from our proposed ensemble mechanism versus the IL1C \cite{b10} baseline: once spurious peaks have been removed, we expect that a peak finding algorithm such that the one applied in \cite{b10} can be more effective in finalizing the estimate of TDOAs. This consistently happen in the cases $s=0.01$, $s=0.1$ (for both $\mathcal{A}_{\rm PPM}$ and $\mathcal{A}_{\rm PUP}$) and $s=0.2$ (only for $\mathcal{A}_{\rm PUP}$), while, when considering the ``more difficult'' cases $s=0.5$ and $s=1$ we do not see a sharp improvement of the ensemble method. This is probably due to the fact that the candidate solutions that are averaged are, each of them, noisier. Therefore, the averaging effect produces an excessive over-regularization which excessively smoothens the peaks, damaging the performance of the peak finding. Nevertheless, the regularizing effect of averaging can be inspirational for practitioners in exploiting a large number of microphones to better estimate TDOAs. \begin{table}[t!] \centering \caption{The ensemble mechanism. We the report the performance of IL1C \cite{b10} ($N=10$, \emph{white noise}) versus the ensemble mechanism in which couples of microphones are solved, first, and the aggregated by averaging across the redundancy of AIRs referring to the same microphones. We denote a better performance in bold, across different signal-to-noise values $s$.} \label{tab:medie} \begin{tabular}{|r|c|c|c|c|c|} \hline & \multicolumn{5}{|c|}{$\mathcal{A}_{\rm PPM}$} \\ & $s = 0.01$ & $s = 0.1$ & $s = 0.2$ & $s = 0.5$ & $s = 1$ \\ \hline IL1C \cite{b10} & 2.2250 & 2.0199 & \textbf{2.2215} & \textbf{4.1515} & \textbf{4.1766} \\ Ensemble (\emph{us}) & \textbf{1.6982} & \textbf{1.8995} & 2.2643 & 4.4532 & 4.4647 \\ \hline \end{tabular}\\~\\~\\ \begin{tabular}{|r|c|c|c|c|c|} \hline & \multicolumn{5}{|c|}{$\mathcal{A}_{\rm PUP}$} \\ & $s = 0.01$ & $s = 0.1$ & $s = 0.2$ & $s = 0.5$ & $s = 1$ \\ \hline IL1C \cite{b10} & 0.3750 & 0.3543 & 0.3971 & \textbf{0.7186} & \textbf{0.7214} \\ Ensemble (\emph{us}) & \textbf{0.2157} & \textbf{0.2414} & \textbf{0.2550} & 0.7421 & 0.8250 \\ \hline \end{tabular} \end{table} \section{Conclusions}\label{sec:conclusions} In this work, we generalized the traditional experimental playground in which the notion of cross-correlation identity (CCI), applied to the estimation of TDOAs using blind channel deconvolution methods \cite{b10,b11,b14,b17,b18}, switching from the case $N = 2$ to $N > 2$. Our analysis shows that, by simply allowing for a increased number of microphones, the very same state-of-the-art method ILC1 \cite{b10} can be sharply boosted in performance (see Tab. \ref{tab:improvementsIL1C}) without requiring any change in the computational pipeline. We deem that our findings open up to a novel research trend in which CCI identities are better combined with the case $N > 2$, so that improvements in the error metrics can come from two different, yet complementary, factors: advances in the optimization standpoint and multiple CCI relationships. We warm-up the research efforts in this directions with two simple modifications of IL1C, showing that, with respect to an incremental addition of the microphones, the practitioners should preferred a late fusion ensemble mechanism - which has the understandable property of easing the peaks finding-based inference stage of \cite{b10}.
{'timestamp': '2020-10-19T02:18:49', 'yymm': '2010', 'arxiv_id': '2010.08428', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08428'}
arxiv
\section{Introduction} \textit{``If intelligence is a cake, the bulk of the cake is unsupervised learning, the icing on the cake is supervised learning and the cherry on the cake is reinforcement learning''}, Yann LeCun famously said \cite{lecun2016unsupervised}. Four years later, the entire cake is finally on the table---the representations learned via self-supervised learning now compete with supervised methods on ImageNet \cite{chen2020simple} and outperform supervised pre-training for object detection \cite{misra2020self}. But given this fundamentally different learning mechanism, \emph{how do recent self-supervised models differ from their supervised counterparts in terms of their behaviour?} We here attempt to shed light on this question by comparing eight flavours of ``cake'' (\texttt{PIRL}, \texttt{MoCo}, \texttt{MoCoV2}, \texttt{InfoMin}, \texttt{InsDis}, \texttt{SimCLR-x1}, \texttt{SimCLR-x2}, \texttt{SimCLR-x4}) with 24 common variants of ``icing'' (from the \texttt{AlexNet}, \texttt{VGG}, \texttt{Squeezenet}, \texttt{DenseNet}, \texttt{Inception}, \texttt{ResNet}, \texttt{ShuffleNet}, \texttt{MobileNet}, \texttt{ResNeXt}, \texttt{WideResNet} and \texttt{MNASNet} star cuisines). Specifically, our culinary test buffet aims to investigate: \begin{enumerate} \item Are self-supervised models more robust towards distortions? \item Do self-supervised models make similar errors as either humans or supervised models? \item Do self-supervised models recognise objects by texture or shape? \end{enumerate} For all of these questions, we compare supervised and self-supervised\footnote{``Unsupervised learning'' and ``self-supervised learning'' are sometimes used interchangeably. We use the term ``self-supervised learning''' since the methods use (label-free) supervision.} models against a comprehensive set of openly available human psychophysical data totalling over 130,000 trials \cite{geirhos2018generalisation, geirhos2019imagenettrained}. This is motivated on one hand by the fact that humans, too, rapidly learn to recognise new objects without requiring hundreds of labels per instance; and on the other hand by a number of fascinating studies reporting increased similarities between self-supervised models and human perception. For instance, \citet{lotter2020neural} train a model for self-supervised next frame prediction on videos, which leads to phenomena known from human vision, including perceptual illusions. \cite{orhan2020self} train a self-supervised model on infant video data, finding good categorisation accuracies on some (small) datasets. Furthermore, \citet{konkle2020instance} and \citet{zhuang2020unsupervised} report an improved match with neural data; \citet{zhuang2020unsupervised} also find more human-like error patterns for semi-supervised models and \citet{storrs2020unsupervised} observe that a self-supervised network accounts for behavioural patterns of human gloss perception. While methods and models differ substantially across these studies, they jointly provide evidence for the intriguing hypothesis that self-supervised machine learning models may better approximate human vision. \section{Methods} \paragraph{Models.} \texttt{InsDis} \cite{wu2018unsupervised}, \texttt{MoCo} \cite{he2020momentum}, \texttt{MoCoV2} \cite{chen2020improved}, \texttt{PIRL} \cite{misra2020self} and \texttt{InfoMin} \cite{tian2020makes} were obtained as pre-trained models from the \href{https://github.com/HobbitLong/PyContrast/}{PyContrast model zoo}. We trained one linear classifier per model on top of the self-supervised representation. A PyTorch \cite{paszke2019pytorch} implementation of \texttt{SimCLR} \cite{chen2020simple} was obtained via \href{https://github.com/tonylins/simclr-converter}{simclr-converter}. All self-supervised models use a \texttt{ResNet-50} architecture and a different training approach within the framework of contrastive learning \cite[e.g.][]{oord2018representation}. For supervised models, we used all 24 available pre-trained models from the \href{https://pytorch.org/docs/1.4.0/model_zoo.html}{PyTorch model zoo version 1.4.0} (\texttt{VGG}: with batch norm). \paragraph{Linear classifier training procedure}. The \href{https://github.com/HobbitLong/PyContrast}{PyContrast repository} by Yonglong Tian contains a Pytorch implementation of unsupervised representation learning methods, including pre-trained representation weights. The repository provides training and evaluation pipelines, but it supports only multi-node distributed training and does not (currently) provide weights for the classifier. We have used the repository's linear classifier evaluation pipeline to train classifiers for InsDis \cite{wu2018unsupervised}, MoCo \cite{he2020momentum}, MoCoV2 \cite{chen2020improved}, PIRL \cite{misra2020self} and InfoMin \cite{tian2020makes} on ImageNet. Pre-trained weights of the model representations (without classifier) were taken from the provided \href{https://www.dropbox.com/sh/87d24jqsl6ra7t2/AABdDXZZBTnMQCBrg1yrQKVCa?dl=0}{Dropbox link} and we then ran the training pipeline on a NVIDIA TESLA P100 using the default parameters configured in the pipeline. Detailed documentation about running the pipeline and parameters can be found in the \href{https://github.com/HobbitLong/PyContrast}{PyContrast repository} (commit \#3541b82). \paragraph{Datasets.} Models were tested on 12 different image degradations from \cite{geirhos2018generalisation}, as well as on texture-vs-shape datasets from \cite{geirhos2019imagenettrained}. Plotting conventions follow these papers (unless indicated otherwise). \section{Results} We here investigate four behavioural characteristics of self-supervised networks, comparing them to their supervised counterparts on the one hand and to human observers on the other hand: out-of-distribution generalisation (\ref{results_ood_generalisation}), category-level error patterns (\ref{results_category_level_errors}), image-level error patterns (\ref{results_image_level_errors}), and texture/shape biases (\ref{results_texture_shape_bias}). \input{assets/noise_generalisation.tex} \subsection{With the exception of SimCLR, supervised and self-supervised models show similar (non-human) out-of-distribution generalisation} \label{results_ood_generalisation} \paragraph{Motivation.} Given sufficient quantities of labelled training data, CNNs can learn to identify objects when the input images are noisy. However, supervised CNNs typically generalise poorly to novel distortion types not seen during training, so-called out-of-distribution images \cite{geirhos2018generalisation}. In contrast, human perception is remarkably robust when dealing with previously unseen types of noise. Given that recent self-supervised networks are trained to identify objects under a variety of transformations (like scaling, cropping and colour shifts), have they learned a more robust, human-like representation of objects, where high-level semantic content is unimpaired by low-level noise? \paragraph{Results.} In Figure~\ref{fig:results_accuracy_entropy}, we compare self-supervised and supervised networks on twelve different types of image distortions. Human observers were tested on the exact same distortions by \cite{geirhos2018generalisation}. Across distortion types, self-supervised networks are well within the range of their poorly generalising supervised counterparts. However, there is one exception: \texttt{SimCLR} shows strong generalisation improvements on uniform noise, low contrast and high-pass images---quite remarkable given that the network was trained using other augmentations (random crop with flip and resize, colour distortion, and Gaussian blur). Apart from \texttt{SimCLR}, however, we do not find benefits of self-supervised training for distortion robustness. These results for ImageNet models contrast with \cite{hendrycks2019using} who observed some robustness improvements for a self-supervised model trained on the CIFAR-10 dataset. \subsection{Self-supervised models make non-human category-level errors} \label{results_category_level_errors} \paragraph{Motivation.} On clean images, CNNs now recognise objects as well as humans. But do they also confuse similar categories with each other (which can be investigated using confusion matrices)? \input{assets/confusion_matrices.tex} \input{assets/error_consistency} \paragraph{Results.} In Figure~\ref{fig:confusion_matrices_noise-generalisation_uniform-noise}, we compare category-level errors of humans against a standard supervised CNN (\texttt{ResNet-50}) and three self-supervised CNNs. We chose uniform noise for this comparison since this is one of the noise types where \texttt{SimCLR} shows strong improvements, nearing human-level accuracies. Looking at the confusion matrices, both humans and CNNs start with a dominant diagonal indicating correct categorisation. With increasing noise level, however, all CNNs develop a strong tendency to predict one category and only one: ``knife'' for \texttt{ResNet-50}, ``clock'' for \texttt{InsDis}, \texttt{MoCoV2} and \texttt{SimCLR-x4}. Human observers, on the other hand, more or less evenly distribute their errors across classes. For supervised networks, this pattern of errors was already observed by \cite{geirhos2018generalisation}; we here find that this peculiar idiosyncrasy is shared by self-supervised networks, indicating that discriminative supervised training is not the underlying reason for this non-human behaviour. \subsection{Self-supervised models make non-human image-level errors (error consistency)} \label{results_image_level_errors} \paragraph{Motivation.} Achieving human-level accuracies on a dataset does not necessarily imply using a human-like strategy: different strategies can lead to similar accuracies. Therefore, it is essential to investigate \emph{on which stimuli} errors occur. If two decision makers---for instance, a human observer and a CNN---use a similar strategy, we can expect them to consistently make errors on the same individual images. This intuition is captured by \emph{error consistency} ($\kappa$), a metric to measure the degree to which decision makers make the same image-level errors \cite{geirhos2020beyond}. $\kappa>0$ means that two decision makers systematically make errors on the same images; $\kappa=0$ indicates no more error overlap than what could be expected by chance alone. \paragraph{Results.} Figure~\ref{fig:error_consistency} plots the consistency of errors (measured by $\kappa$). Humans make highly similar errors as other humans (mean $\kappa = 0.32$), but neither supervised nor self-supervised models make human-like errors. Instead, error consistency \emph{between} model groups (self-supervised vs.\ supervised) is just as high as consistency \emph{within} model groups: self-supervised models make errors on the same images as supervised models, an indicator for highly similar strategies. \subsection{Self-supervised models are biased towards texture} \label{results_texture_shape_bias} \input{assets/shape_bias} \paragraph{Motivation.} Standard supervised networks recognise objects by relying on local texture statistics, largely ignoring global object shape \cite{geirhos2019imagenettrained, baker2018deep, brendel2019approximating}. This striking difference to human visual perception has been attributed to the fact that texture is a shortcut sufficient to discriminate among objects \cite{geirhos2020shortcut}---but is texture also sufficient to solve self-supervised training objectives? \paragraph{Results.} We tested a broad range of CNNs on the texture-shape cue conflict dataset from \cite{geirhos2019imagenettrained}. This dataset consists of images where the shape belongs to one category (e.g.\ cat) and the texture belongs to a different category (e.g.\ elephant). When plotting whether CNNs prefer texture or shape (Figure~\ref{fig:shape_bias}), we observe that most self-supervised models have a strong texture bias known from traditional supervised models. This texture bias is less prominent for \texttt{SimCLR} (58.3--61.2\% texture decisions), which is still on par with supervised model \texttt{Inception-V3} (60.7\% texture decisions). These findings are in line with \cite{hermann2020the}, who observed that the influence of training data augmentations on shape bias is stronger than the role of architecture or training objective. Neither supervised nor self-supervised models have the strong shape bias that is so characteristic for human observers, indicating fundamentally different decision making processes between humans and CNNs. \section{Discussion} Comparing self-supervised networks to supervised models and human observers, we here investigated four key behavioural characteristics: out-of-distribution generalisation, category-level error patterns, image-level error patterns, and texture bias. Overall, we find that self-supervised models resemble their supervised counterparts much more closely than what could have been expected given fundamentally different training objectives. While standard models are notoriously non-robust \cite{dodge2016understanding, geirhos2018generalisation, hendrycks2019benchmarking, deza2020emergent, geirhos2020shortcut}, \texttt{SimCLR} represents a notable exception in some of our experiments as it is less biased towards texture and much more robust towards some types of distortions. It is an open question whether these benefits arise from the training objective or whether they are instead induced by the specific set of data augmentations used during \texttt{SimCLR} model training. Perhaps surprisingly, error consistency analysis suggests that the images on which supervised and self-supervised models make errors overlap strongly, much more than what could have been expected by chance alone. This provides evidence for similar processing mechanisms: It seems that switching label-based supervision for a contrastive learning scheme does not have a strong effect on the inductive bias of the resulting model---at least for the currently used contrastive approaches. Furthermore, we find little evidence for human-like behaviour in the investigated self-supervised models. We are clearly just witnessing the beginning of what could be called a self-supervised revolution of machine vision, and we expect future self-supervised models to behave significantly differently from supervised ones. What we are showing is that the current self-supervised CNNs are not yet more human-like in their strategies and internal representations than plain-vanilla supervised CNNs. We hope, however, that analyses like ours may facilitate the tracking of emerging similarities and differences, whether between different types of models or between models and human perception. \subsubsection*{Acknowledgement} \begin{footnotesize} We thank Santiago Cadena for sharing a PyTorch implementation of \texttt{SimCLR}, and Yonglong Tian for providing pre-trained self-supervised models on \href{https://github.com/HobbitLong/PyContrast}{github}. Furthermore, we are grateful to the International Max Planck Research School for Intelligent Systems (IMPRS-IS) for supporting R.G.; the Collaborative Research Center (Projektnummer 276693517---SFB 1233: Robust Vision) for supporting M.B. and F.A.W.; the German Federal Ministry of Education and Research through the Tübingen AI Center (FKZ 01IS18039A) for supporting W.B. and M.B.; and the German Research Foundation through the Cluster of Excellence ``Machine Learning---New Perspectives for Science'', EXC 2064/1, project number 390727645 for supporting F.A.W. \end{footnotesize} \subsubsection*{Author contributions} \begin{footnotesize} Project idea: R.G. and W.B.; project lead: R.G.; implementing and training self-supervised models: K.N.; model evaluation pipeline: R.G., K.N. with input from W.B.; data visualisation: R.G. and B.M. with input from M.B., F.A.W. and W.B.; guidance, feedback, infrastructure \& funding acquisition: M.B., F.A.W. and W.B.; paper writing: R.G. with input from all other authors. \end{footnotesize} \newpage \bibliographystyle{unsrtnat}
{'timestamp': '2020-10-19T02:17:05', 'yymm': '2010', 'arxiv_id': '2010.08377', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08377'}
arxiv
\section{Introduction} Network Time Protocol (NTP) is one of the core Internet protocols, used to synchronise time on Internet systems. Recently \cite{malhotra_attacking_2016} demonstrated a proof of concept time shifting attacks against NTP. The idea was to exploit overlapping IPv4 fragments, whereby a shifted time provided in the attacker's fragment would overwrite the time provided by the real NTP server in a response sent to the client. However, this attack is limited because it depends on various factors not typically present in the Internet, mainly minimum MTU support down to 68 bytes and an IP defragmentation algorithm not used by any current operating system. Due to the critical role that NTP plays in the Internet there was an immediate followup work, which devised enhancements to NTP, called Chronos \cite{ntp:chronos}, to block the attack. Chronos leverages ideas from distributed computing on clock synchronisation in the presence of Byzantine adversaries and is designed to provide security even against strong Man-in-the-Middle (MitM) attackers and corrupted NTP servers. \subsubsection*{Our contribution} In this work, we present an DNS-poisoning based attack on NTP, which is not only more practical than attacking NTP directly, but works even against the Chronos enhanced NTP clients. This attack is part of research on security of NTP with DNS \cite{ntp-over-dns}. \section{DNS Cache-Poisoning Attacks} DNS cache poisoning \cite{cns:frag:dns,shulman2015towards,brandt2018domain} allows off-path attackers to gain MitM capabilities for some target victim domain. This allows the attacker to intercept any communication with the victim domain, such as web, email, FTP or in this case -- NTP. Off-path cache poisoning attacks were demonstrated using BGP hijacking and defragmentation poisoning. BGP hijacking places the attacker in a MitM position for the victim network\cite{dns:venezuela,myetherwallet}. \subsection{Attacking DNS with De-fragmentation Poisoning} IP Defragmentation cache-poisoning allows off-path attackers to hijack the DNS without the necessity to control BGP routers for prefix hijacking. In 2011 \cite{cns:frag:dns} demonstrated practical DNS cache poisoning attacks that use fragmented IPv4 packets. The idea is to inject a spoofed fragment into the IP defragmentation cache that is to be reassembled with the real fragment from the nameserver. In \cite{ntp-over-dns} we evaluated fragmentation support of {\it pool.ntp.org} nameservers as well as DNS resolvers the internet. We found that 16 out of 30 nameservers for {\it pool.ntp.org} fragment DNS responses down to a MTU of 548 bytes while not supporting DNSSEC. There are also challenges with DNSSEC deployment \cite{herzberg2013towards,dai2016dnssec,shulman2017one}. Furthermore, using an ad-network based study we found that 90\% of resolvers accept fragments of some size and 64\% even the tiniest possible fragment size of 68 bytes MTU. Additionally we found that DNS resolvers are often shared by different systems in the internet. This simplifies fragmentation-based DNS poisoning because the attacker can execute the DNS-poisoning and time-shifting attacks independently, picking a protocol which allows for easy triggering of DNS queries and yields bigger DNS responses to get over the minimum MTU size of the namserver. For 14\% of DNS resolvers used by web clients attackers we were able to trigger queries via either SMTP servers or open resolvers. \section{Chronos -- Security Enhanced NTP} Chronos is a formally verified, backwards-compatible NTP client which aims to prevent attacks against NTP using distributed-computing techniques\cite{ntp:chronos}. In contrast to traditional NTP which queries few (typically up to 4) NTP servers, Chronos queries time from multiple NTP servers, applies a secure algorithm for eliminating suspicious responses and averages the time over the valid responses. The authors demonstrate that in order to shift time on a Chronos NTP client by 100ms a strong MitM attacker would need 20 years of effort. Chronos {\em implicitly} assumes that the attacks on NTP are launched when the NTP client queries the NTP servers in the Internet for time. It's attacker model is that of a MitM attacker that changes some responses to contain shifted time or an attacker that corrupts some of the NTP servers. The security of Chronos is guaranteed if the majority of the queried NTP servers provide correct time. The idea is that all the responses are fed to an algorithm which calculates time by discarding the bottom and top third of responses and sets the time to the average value of the surviving time samples. Therefore, compared to traditional NTP, Chronos changes NTP clients in two ways. First, by using a bigger pool of upstream NTP servers and second, by replacing the clock select algorithm with one which is formally verified to be secure against a minority of malicious responses. \section{Attacking Chronos with DNS} \label{sec:attackingchronos} In this work we identify the ``achilles heel'' of Chronos: generating a pool of NTP servers which satisfies it's assumption of a honest majority of servers. The idea is to collect a set of roughly hundred NTP servers, from which NTP servers are selected at random and queried for time samples. This pool is generated by querying the {\it pool.ntp.org} domain hourly for 24 hours, yielding a number of $96$ NTP servers when each DNS response contains $4$ NTP servers as in the case of {\it pool.ntp.org}. Chronos' server pool generation method is flawed in a way which ironically simplifies a DNS-based attack compared to traditional NTP clients. Because the DNS is queried 24 times, the attacker has potentially up to 24 tries to succeed with an cache-poisoning attack instead of just once in case of a traditional NTP client. We show that if the cache-poisoning attack succeeds until or during the 12th DNS request, the attacks still controls more than $\frac{2}{3}$ of the addresses included in the server pool, the definite maximum of servers required for a time-shifting attack on Chronos. How the cache poisoning is done -- via BGP hijacking or fragment injection -- and whether the query is triggered by Chronos directly of via a third party system like SMTP is not important for this attack to work. What simplifies the attack on Chronos is the fact that other than the benign {\it pool.ntp.org} namservers, (1) the attacker can fit more addresses in a single DNS query (up to 89 for a single non-fragmented DNS response) and (2) set the DNS Time-to-live (TTL) to a value bigger than 24 hours, to cause any subsequent queries to be answered from cache, effectively not adding any new server to the pool. When this is done as shown in Figure~\ref{fig:chronos_attack}, the resulting pool will consist of up to $4 \cdot 11 = 44$ benign and $89$ malicious NTP servers which is a $\frac{2}{3}$ majority for the attacker. To succeed with this attack, the attacker therefore only needs to successfully attack the DNS once out of 12 queries during the first 11 hours of Chronos server pool generation mechanism. \begin{figure}[t!] \centering \includegraphics[width=0.45\textwidth]{img/chronos-flow-eps-converted-to.pdf} \caption{DNS poisoning attack on chronos.} \label{fig:chronos_attack} \vspace{-13pt} \end{figure} \section{Conclusions} Our attack demonstrates the risks of building security on insecure Internet foundations like DNS, and the risks of analysing security in isolation. The Chronos server pool-generation method can be improved to limit the impact of our attack -- by not allowing more than 4 addresses in a single DNS reply and discarding responses with high TTL values. However, even with these mitigations, the dependency on the insecure DNS still remains and allows way easier attacks than Chronos was originally designed for -- e.g., when the attacker manages to hijack the victim's DNS for a period of 24 hours. To devise secure solutions based on DNS we recommend proposals for generating distributed consensus in a secure way, such as that proposed in \cite{jeitner:consensus:dsn:20}. \IEEEpeerreviewmaketitle \bibliographystyle{IEEEtran}
{'timestamp': '2020-10-19T02:20:00', 'yymm': '2010', 'arxiv_id': '2010.08460', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08460'}
arxiv
\section{Introduction} \label{sec:introduction_fq} Emerging applications such as cloud gaming \cite{jarschel_evaluation_2011} and remote virtual reality \cite{elbamby_toward_2018} applications require high throughput and low delay. Furthermore, ultra low latency communications have been made a priority for 5G \cite{li_5g_2018}. We argue that for achieving high throughput as well as low delay, congestion control must be taken into account. \textit{Delay-based} \glspl{cca} were proposed to provide high throughput and low delay for network flows. They use the queuing delay as an indication of congestion and lower their throughput as soon as the delay increases. Such approaches have been proposed in the last century \cite{brakmo_tcp_1995} and recently have seen a surge in popularity \cite{arun_copa_2018,hock_tcp_2017,mittal_timely_2015,cardwell_bbr:_2016}. While delay-based \glspl{cca} fulfill their goal of low delay and high throughput, they cannot handle competing flows with different \glspl{cca} well \cite{turkovic_fifty_2019, turkovic_interactions_2019}. This is especially prevalent when they compete against loss-based \glspl{cca}, the latter being more ``aggressive''. While the delay-based \glspl{cca} back off as soon as queuing delay increases, the loss-based ones continue increasing their throughput until the buffer is full and packet loss occurs. This results in the loss-based flows monopolize the available bandwidth and starve the delay-based ones \cite{hock_toward_2016,yuan-cheng_lai_improving_2001,awdeh_comparing_2004}. This unfairness can be mitigated by using \gls{fq} at the bottleneck link, isolating each flow from all other flows and assigning each flow an equal share of bandwidth \cite{dumazet_pkt_sched:_2013}. Consequently, loss-based flows can no longer acquire bandwidth that delay-based flows have released due to their network-friendly behavior. In this case, delay-based \glspl{cca} achieve their goal of high bandwidth and low delay. While \gls{fq} solves many problems regarding \gls{cc}, it is still not ubiquitously deployed. Flows can benefit from knowledge of \gls{fq} enabled bottleneck links on the path to dynamically adapt their \gls{cc}. In the case of \gls{fq} they can use a delay-based \gls{cca} and otherwise revert to a loss-based one. Our contribution is the design and evaluation of such a mechanism that determines the presence of \gls{fq} during the startup phase of a flow's \gls{cca} and sets the \gls{cca} accordingly at the end of the startup. We show that this solution reliably determines the presence of fair queuing and that by using this approach, queuing delay can be considerably lowered while maintaining throughput high if \gls{fq} is detected. In case no \gls{fq} is enabled, our algorithm detects this as well and a loss-based \gls{cc} is used, which does not starve when facing competition from other loss-based flows. While our mechanism is beneficial for network flows in general, we argue that it is most useful for long-running delay-sensitive flows, such as cloud gaming, video conferencing etc. To make our work reproducible and to encourage further research, we make the code, the results and the figures publicly available\footnote{\ifxnoyes $\langle$anonymized$\rangle$\else\url{https://github.com/CN-TU/PCC-Uspace}\fi}. \section{Related work} Our work depends on active measurements for the startup phase of \gls{cc} and proposes a new measurement technique to detect \gls{aqm}. This section discusses preliminary work related to these fields. \subsection{\gls{cc} using Active Measurements} Several approaches have been recently proposed which aim to incorporate active measurements into \glspl{cca}. \citep{dong_pcc_2015,dong_pcc_2018} introduced the \gls{cca} \textit{PCC}, which uses active measurements to find the sending rate which optimizes a given reward function. \citep{cardwell_bbr:_2016} introduce the \textit{BBR} \gls{cca}, which uses active measurement to create a model of the network connection. This model is then used to determine the optimal sending rate. An approach proposed by \citep{goyal_elasticity_2018} aims to differentiate bulk transfer flows, which they deem ``elastic'' because they try to grab as much bandwidth as available, from other flows that send at a constant rate, which they call ``unelastic''. They use this elasticity detection to determine if delay-based \gls{cc} can be used or not. If cross traffic is deemed elastic then they use classic loss-based \gls{cc} and otherwise delay-based \gls{cc}. \subsection{Flow startup techniques} Besides the classical TCP slow start algorithm \citep{stevens_tcp_1997} some other proposals were made such as Quick Start \citep{jain_quick-start_2019}, which aims to speed up flow start by routers informing the end point, which rate they deem appropriate. \citep{jarvinen_congestion_2019} investigate the impact of \gls{aqm} and \gls{cc} during flow startup. They inspect a variety of different \gls{aqm} algorithms and also investigate \gls{fq}. \citep{kuhlewind_chirping_2010} propose ``chirping'' for flow startup to estimate the available bandwidth. This works by sending packets with different gaps between them to verify what the actual link speed is. \citep{mittal_recursively_2014} propose speeding up flow startup by using packets of different priority. The link is flooded with low-priority packets and in case the link is not fully utilized during startup, these low-priority packets are going to be transmitted, allowing the starting flow to achieve high throughput. If the link is already saturated, the low-priority packets are going to be discarded and no other flow suffers. \subsection{Detecting \gls{aqm} mechanisms} There are few publications that investigate methods to detect the presence of an \gls{aqm}. \citep{kargar_bideh_tada_2016} propose a method to detect and distinguish certain popular \gls{aqm} mechanisms. However, unlike our work, it doesn't consider \gls{fq}. \citep{baykal_detection_2017} propose a machine learning based approach to fingerprint \gls{aqm} algorithm. \gls{fq} is not considered, too. \subsection{Detecting the presence of a shared bottleneck} Several approaches have been proposed to detect whether in a set of flows, some of them share a common bottleneck \cite{hayes_practical_2014,ferlin_revisiting_2016,hayes_online_2020}. These approaches typically operate by comparing some statistics of flows to check whether they correlate between flows. For example, it can be checked if throughput correlates between two flows. If throughput correlates, it can mean that these flows share a common bottleneck link, and if additional flows join at the bottleneck link, all other flows' throughputs go down, which is the reason why they are correlated. While approaches to detect a shared bottleneck link appear to be similar to what this paper is aiming to do, there are differences: Two flows can share a common bottleneck link but the bottleneck link can have fair queuing. Thus the aims of shared bottleneck and fair queuing detection are different. \section{Concept} \label{sec:concept_fq} The overall concept is the following: \begin{enumerate} \item During flow startup, determine whether the bottleneck link deploys \gls{fq} or not. \item If \gls{fq} is used change to a delay-based \gls{cca} or revert to a loss-based \gls{cca} otherwise. \end{enumerate} \subsection{Algorithm to determine the presence of \gls{fq}} \begin{figure} \centering \subfloat[Sending rate]{\includegraphics[width=0.33\columnwidth]{{"figures/fq_illustration_throughput"}.pdf} \label{fig:throughput}} \subfloat[Receiving rate (no \gls{fq}).]{\includegraphics[width=0.33\columnwidth]{{"figures/fq_illustration_goodput_no_fq"}.pdf} \label{fig:goodput_no_fq}} \subfloat[Receiving rate (\gls{fq}).]{\includegraphics[width=0.33\columnwidth]{{"figures/fq_illustration_goodput_fq"}.pdf} \label{fig:goodput_fq}} \caption{An example illustrating our proposed flow startup mechanism. Figure \ref{fig:throughput} shows the sending rate, \ref{fig:goodput_no_fq} the receiving rate in case there's no \gls{fq} and \ref{fig:goodput_fq} the receiving rate if there is \gls{fq}.} \label{fig:illustration} \end{figure} The algorithm to determine the presence of \gls{fq} works as follows (seen from the sender's point of view): \begin{enumerate} \item Launch two concurrent flows, flow 1 and flow 2 from the same source host to the same destination host. Initialize flow 1 with some starting sending rate and flow 2 with two times that rate. \item After every \gls{rtt}, if no packet loss occurred, double the sending rate of both flows. \item If packet loss occurred in both flows in the previous \gls{rtt}, calculate the following metric: \begin{align} \textit{loss ratio} &= \frac{\left(\frac{\textit{receiving rate of flow 1}}{\textit{sending rate of flow 1}}\right)}{\left(\frac{\textit{receiving rate of flow 2}}{\textit{sending rate of flow 2}}\right)}\end{align} This loss ratio metric indicates if flow 2, which has a higher sending rate, achieves a higher receiving rate (goodput) than flow 1. If this is the case, there's no \gls{fq}, otherwise there is. It is necessary to wait for packet loss in both connections because only then it is certain that the link is saturated. Our algorithm assumes that the link is saturated. \item If \gls{fq} is used, the $\textit{loss ratio}$ is 2, otherwise it is 1. We choose 1.5 as the cutoff value. \item Since the presence or absence of \gls{fq} is now known the appropriate \gls{cca} can be launched. \end{enumerate} Figure~\ref{fig:throughput}, \ref{fig:goodput_no_fq} and \ref{fig:goodput_fq} schematically illustrate this mechanism. We assume a sender being connected to a receiver, with a bottleneck link between them. We also assume that all flows between the source and the destination follow the same route. On this bottleneck link, the queue is either managed by \gls{fq} or by a shared queue (no \gls{fq}). Figure~\ref{fig:throughput} shows how the sending rate (observed before the bottleneck link) is doubled after each \gls{rtt}. Furthermore, it shows that flow 2 has double the sending rate of flow 1. Figure~\ref{fig:goodput_no_fq} shows the receiving rate at the receiver after the bottleneck link, if this bottleneck link has a a shared queue without \gls{fq}. In the third \gls{rtt} the sending rate exceeds the link speed of the bottleneck and thus the receiving rate is smaller than the sending rate. Because no \gls{fq} is employed, flow 2 manages to have a receiving rate two times the one of flow 1. Figure~\ref{fig:goodput_fq} shows the receiving rate of the two flows measured after the bottleneck link in case \gls{fq} is deployed. In the third \gls{rtt}, flow 1 and flow 2 achieve the same receiving rate because of the \gls{fq}, which makes sure that each flow gets an equal share of the total capacity. \subsection{Simple delay-based \gls{cc}} If \gls{fq} is detected, a simple delay-based \gls{cc} is used from then on. Our algorithm is based on the two following simple rules: \begin{enumerate} \item If \textit{current rtt} $\leq$ \textit{smallest rtt ever measured on the connection} $+$ 5\textit{ms} then increase the sending rate by 1\%. We choose 5\,ms since a delay of 5\,ms is barely noticeable by humans. This design choice was first established in \citep{nichols_controlling_2012}. \item Otherwise (\textit{current rtt} $>$ \textit{smallest rtt ever measured on the connection} + 5\textit{ms}) decrease the sending rate by 5\%. \end{enumerate} This \gls{cca} is meant as a simple proof-of-concept to demonstrate the efficacy of our \gls{fq} detection mechanism but we do not claim it to be optimal in any way. \subsection{Fallback loss-based \gls{cc}} If the absence of \gls{fq} is detected, a loss based \gls{cc} is used as a fallback. We use the algorithm \textit{PCC} proposed by \citep{dong_pcc_2015}. In simplified terms, this \gls{cca} aims to maximize a utility function, which strives for high throughput and low packet loss. However, it is reasonably aggressive and does not starve when competing with other loss-based \glspl{cca} such as Cubic \citep{ha_cubic_2008}. \section{Implementation} We base our implementation on the code of \textit{PCC Vivace} \citep{dong_pcc_2018}, which in turn is an improved version of PCC. The PCC code is based on the \textit{UDT} library \citep{gu_udt_2007}, which is a library that provides a reliable transport protocol similar to TCP on top of UDP. This approach is similar to QUIC \citep{iyengar_quic_2018}. An advantage of implementing our approach on top of UDP as opposed to TCP is that it is easier to develop and modify since no kernel module needs to be created and that it is more secure since the code is isolated in a user space process and most attacks can only influence this process and not the entire kernel. \subsection{Deployment} Our approach of detecting \gls{fq} relies on using two concurrent flows between the sender and the receiver. During flow startup, user data is transmitted in two flows that the receiver must detect and reassemble. This may be a challenge for deployments since solutions that require cooperation of several instances are more difficult to deploy at a wide scale in the Internet. However, multipath TCP \citep{handley_tcp_2012} and QUIC, for which there are proposals to enable recombining data of several flows \citep{de_coninck_multipath_2017}, are becoming increasingly prevalent. We thus argue that the actual obstacles to deployment of our solution are constantly decreasing since QUIC (mostly Google traffic) already accounts for around $10\%$ of all Internet traffic \citep{ruth_first_2018} and is growing. Moreover, Apple's macOS and iOS support multipath TCP \citep{apple_about_2018} support. \section{Experiment setup} For the evaluation we use the network emulation library \texttt{py-virtnet}\footnote{\url{https://pypi.org/project/py-virtnet/}}. All experiments run on virtual hosts on one physical host, on which the necessary network components and virtual hosts are emulated using Linux network namespaces. The setup consists of two virtual hosts connected through a virtual switch. One virtual host acts as a server and one as a client and a bulk transfer is initiated from the client to the server. For the experiments with \gls{fq} we use the \texttt{fq} module for Linux. This module keeps one drop tail queue for each flow with a configurable maximum size of packets. However, the design of our \gls{fq} detection algorithm does not assume any particular queue management algorithm being used for the queue of each flow and thus is also compatible with more sophisticated \gls{aqm} mechanisms which were explicitly developed to be used in conjunction with \gls{fq} \citep{taht_flow_2018,hoiland-jorgensen_piece_2018,bachl_cocoa_2019,bachl_lfq_2020}. It only assumes that each flow gets the same share of bandwidth and that for a flow, whose queue is growing faster because more packets of this flow arrive at the bottleneck, packets are dropped faster than for a flow of which fewer packets appear at the bottleneck link. For the experiments with a shared queue we use \texttt{pfifo}, which is a simple drop tail queue which can contain up to a fixed number of packets. \section{Results} \subsection{Delay- vs.~loss-based \gls{cc}} \begin{figure}[h] \centering \subfloat[Throughput (receiving rate)]{% \includegraphics[width=0.48\columnwidth]{{"figures/plots/throughput_1_just_one_flow_cubic_tcp_port9010_fq_10_10_20_1600183264284.pcap"}.pdf}% \label{fig:just_one_flow_tcp_throughput} }\hfill \subfloat[\gls{rtt}]{% \includegraphics[width=0.48\columnwidth]{{"figures/plots/rtt_1_just_one_flow_cubic_tcp_port9010_fq_10_10_20_1600183264284.pcap"}.pdf}% \label{fig:just_one_flow_tcp_delay} } \caption{Throughput and delay of a flow controlled by the loss-based \gls{cca} Cubic on a link with a speed of 10\,Mbps, a delay of 10\,ms and a buffer size of 100 packets (\texttt{pfifo}'s default value).} \label{fig:just_one_flow_tcp} \end{figure} \begin{figure}[h] \centering \subfloat[Throughput (receiving rate)]{% \includegraphics[width=0.48\columnwidth]{{"figures/plots/throughput_1_just_one_flow_vegas_udp_port9000_fq_10_10_20_1600183241479.pcap"}.pdf}% }\hfill \subfloat[\gls{rtt}]{% \includegraphics[width=0.48\columnwidth]{{"figures/plots/rtt_1_just_one_flow_vegas_udp_port9000_fq_10_10_20_1600183241479.pcap"}.pdf}% } \caption{Throughput and delay of a flow controlled by our delay-based \gls{cca} on a link with a speed of 10\,Mbps, a delay of 10\,ms and a buffer size of 100 packets.} \label{fig:just_one_flow_udp} \end{figure} First, we demonstrate empirically that delay-based \gls{cc} actually has a benefit over loss-based one. On one side, \autoref{fig:just_one_flow_tcp} shows that the loss-based \gls{cc} achieves a throughput of almost 10\,Mbps on a 10\,Mbps link, which means full utilization and an \gls{rtt} that is higher than 100\,ms, which is not desirable. On the other side, \autoref{fig:just_one_flow_udp} shows an example flow using our simple delay-based \gls{cca} and a slow start algorithm similar to the one used by the classic TCP \gls{cca} \textit{New Reno} \citep{allman_tcp_1999}. While the delay-based flow also achieves very high utilization, delay rarely exceeds 20\,ms, meaning that it is more than 5 times lower than the one of the loss-based \gls{cca} of \autoref{fig:just_one_flow_tcp}. The initial peak in \autoref{fig:just_one_flow_udp} is caused by the exponential increase of the sending rate in the beginning, which is commonly used by transport protocols and called ``slow start'' \citep{stevens_tcp_1997}. Our delay-based \gls{cc} also uses a mechanism similar to slow start in the beginning. \subsection{Comparing flows with different Congestion Controls and AQM mechanisms} In this scenario, we show an example of a flow with our mechanism that shares a bottleneck link with a flow using a loss-based congestion control. \subsubsection{No \gls{fq}} The examples in \autoref{fig:pfifo_tcp} and in \autoref{fig:pfifo_udp} show the loss-based \gls{cca} Cubic compete against our delay-based \gls{cca} on a link without \gls{fq}. It is important to note that we do not use our \gls{fq} detection mechanism here but instead choose delay-based \gls{cc} from the beginning to demonstrate the starvation of delay-based flows that happens when they compete against loss-based ones without \gls{fq}. We start the loss-based flow before to make sure that it has sufficient time to fill up the link: The loss-based flow starts 5 seconds earlier and after 5 seconds, the delay-based flow joins. We choose these 5 seconds so that the first flow can enter its stable state because we want to show how how the flow, even though it had the advantage of the 5 seconds in which it could use the link all for itself, loses to the loss-based \gls{cc}: While the delay-based flow gains some share of the link during startup, it is pushed away by the loss-based flow later on and ``starves''. \begin{figure}[h] \centering \subfloat[Throughput (receiving rate)]{% \includegraphics[width=0.48\columnwidth]{{"figures/plots/throughput_1_competing_flow_pfifo_vegas_tcp_port9010_pfifo_10_50_20_1600182743408.pcap"}.pdf}% }\hfill \subfloat[\gls{rtt}]{% \includegraphics[width=0.48\columnwidth]{{"figures/plots/rtt_1_competing_flow_pfifo_vegas_tcp_port9010_pfifo_10_50_20_1600182743408.pcap"}.pdf}% } \caption{Throughput and delay of a flow controlled by the loss-based \gls{cca} Cubic on a link with a speed of 50\,Mbps, a delay of 10\,ms and a buffer size of 100 packets. The bottleneck is controlled by a shared queue (no \gls{fq}) and is shared with the flow of \autoref{fig:pfifo_udp}.} \label{fig:pfifo_tcp} \end{figure} \begin{figure}[h] \centering \subfloat[Throughput (receiving rate)]{% \includegraphics[width=0.48\columnwidth]{{"figures/plots/throughput_1_competing_flow_pfifo_vegas_udp_port9000_pfifo_10_50_20_1600182743408.pcap"}.pdf}% }\hfill \subfloat[\gls{rtt}]{% \includegraphics[width=0.48\columnwidth]{{"figures/plots/rtt_1_competing_flow_pfifo_vegas_udp_port9000_pfifo_10_50_20_1600182743408.pcap"}.pdf}% } \caption{Throughput and delay of a flow controlled by our delay-based \gls{cca} on a link with a speed of 50\,Mbps, a delay of 10\,ms and a buffer size of 100 packets. The bottleneck is controlled by a shared queue (no \gls{fq}) and is shared with the flow of \autoref{fig:pfifo_tcp}.} \label{fig:pfifo_udp} \end{figure} \subsubsection{\gls{fq}} \begin{figure}[h] \centering \subfloat[Throughput (receiving rate)]{% \includegraphics[width=0.48\columnwidth]{{"figures/plots/throughput_1_competing_flow_fq_tcp_port9010_fq_10_50_20_1600182657352.pcap"}.pdf}% }\hfill \subfloat[\gls{rtt}]{% \includegraphics[width=0.48\columnwidth]{{"figures/plots/rtt_1_competing_flow_fq_tcp_port9010_fq_10_50_20_1600182657352.pcap"}.pdf}% } \caption{Throughput and delay of a flow controlled by the loss-based \gls{cca} Cubic on a link with a speed of 50\,Mbps, a delay of 10\,ms and a buffer size of 100 packets. The bottleneck is controlled by \gls{fq} and is shared with the flow of \autoref{fig:fq_udp}.} \label{fig:fq_tcp} \end{figure} \begin{figure}[h] \centering \subfloat[Throughput (receiving rate)]{% \includegraphics[width=0.48\columnwidth]{{"figures/plots/throughput_1_competing_flow_fq_udp_port9000_fq_10_50_20_1600182657352.pcap"}.pdf}% }\hfill \subfloat[\gls{rtt}]{% \includegraphics[width=0.48\columnwidth]{{"figures/plots/rtt_1_competing_flow_fq_udp_port9000_fq_10_50_20_1600182657352.pcap"}.pdf}% } \caption{Throughput and delay of a flow controlled by our delay-based \gls{cca} on a link with a speed of 50\,Mbps, a delay of 10\,ms and a buffer size of 100 packets. The bottleneck is controlled by \gls{fq} and is shared with the flow of \autoref{fig:fq_tcp}.} \label{fig:fq_udp} \end{figure} For a link with fair queuing, the following example results show that throughput is identical for our flow (\autoref{fig:fq_udp}) and the Cubic flow (\autoref{fig:fq_tcp}), just that the Cubic flow's delay is more than two times higher than the delay-based one's. Thus, our mechanism detects that the bottleneck uses \gls{fq} and uses a delay-based congestion control because it is better suited in a scenario with \gls{fq}. \subsection{Accuracy of the \gls{fq} detection mechanism} To evaluate if our proposed mechanism correctly recognizes \gls{fq} in a systematic manner, we perform experiments using a wide range of network configurations: we vary bandwidth from 5 to 50\,Mbps, delay from 10 to 100\,ms and the buffer size from 1 to 100 packets, using a grid of these parameters. For each parameter, we take 5 values, evenly spaced. Thus, we run experiments with 125 different configurations. We run each configuration once with \gls{fq} and once without. Results show that for experiments without \gls{fq} (using a shared queue), in over 99\% of cases, the absence of \gls{fq} was correctly detected and in less than 1\% of cases, our algorithm detected \gls{fq} even though there was no \gls{fq}. For experiments, during which \gls{fq} was actually deployed on the bottleneck link, this was correctly detected in 97\% of cases and wrongly in 3\% of the time. The overall accuracy is thus 98\%, which we consider sufficient. To verify the behavior of our algorithm under the presence of cross traffic, we repeated the above experiments but with one bulk traffic flow using Cubic running at the same time, which we start 5 seconds before so that it has sufficient time to gain full bandwidth. Also under these circumstances we also achieve 98\% detection accuracy using our algorithm. We investigated the reason for the detection accuracy not being 100\% and found the following: The PCC code relies on packet scheduling using timers, which is very computationally expensive because it needs a timer for every packet and thus the program has to be put to sleep/woken up repeatedly by the operating system. Thus, if processor load is high, the timers fail and PCC can't send as many packets as it would want to. our algorithm relies on flow 1 sending half the rate of flow 2 but this cannot always be guaranteed if CPU load is high. We tried to minimize all tasks which run in the background and achieved the accuracy we got. When we ran the experiments while we was browsing the web, we got lower accuracy. Solutions to the problem are to not schedule packets using timers or to implement the algorithm not in user space but in kernel space. Then the computational cost of could decrease because fewer context switches between the PCC user space application and the kernel are necessary. \subsection{Systematic evaluation} Besides the examples we provided, we also conducted a more systematic comparison of the throughput and delay that our algorithm achieves: we use the same scenario as above and again vary bandwidth from 5 to 50\,Mbps, delay from 10 to 100\,ms and the buffer size from 1 to 100 packets. For each parameter, we take 5 values, evenly spaced, totaling 125 distinct scenarios. We use \gls{fq} at the bottleneck link. We run each scenario both using Cubic as well as our algorithm for 30 seconds each. We average the achieved throughputs and average delays from all experiments for both Cubic as well as our algorithm. For Cubic, the mean throughput is 21\,Mbit/s and the mean \gls{rtt} is 96\,ms while for our algorithm it is 26\,Mbit/s and 64\,ms. This shows that our algorithm can correctly determine that there is \gls{fq} and switch to the delay-based \gls{cc} and that our algorithm achieves significantly lower delay (loss-based Cubic's delay is 50\% higher) and -- surprisingly -- higher throughput. This is astonishing considering that loss-based \glspl{cca} such as Cubic should be more aggressive in filling the link. When analyzing the results we identified that Cubic performs very poorly in scenarios with small buffers because the multiplicative decrease of Cubic is 0.7, meaning that the bandwidth is reduced by 30\% after every packet loss while our algorithm only reduces it by only 5\%. Thus Cubic reduces bandwidth too much after packet loss which results in underutilization of the link. \section{Discussion} During the implementation of our algorithm we noticed peculiar behavior when not using \gls{fq}: During startup, we make flow 1 have half the sending rate of flow 2. We would expect the receiving rates to be the same: flow 1 achieving around half the rate of flow 2. However, we noticed that usually flow 1 would have a receiving rate of 0. After investigating the issue we noticed that the reason was pacing: PCC (and other \glspl{cca}) such as BBR send packets in regular intervals, for example every millisecond, because sending regularly keeps the queues shorter. This behavior is called pacing. However, when there are two flows where one flow's sending rate is a multiple of the other's, an interleaving effect occurs: flow 1 would always send each packet slightly after flow 2 sends a packet. Then, when the packets arrive at the bottleneck, flow 2's packet, which arrives a bit earlier, fills up the buffer and flow 1's packet is consequently always dropped. As a solution, we do not send packets at regular intervals during startup but always add a small random value: For example, if the sending interval were 1\,ms, we would send the packet randomly in the interval from 0.5 to 1.5\,ms. This solves the aforementioned problem. The insight we gained from this is that while pacing is generally supportive, it is actually harmful if several flows compete at a bottleneck without \gls{fq} and one flow's sending rate is a multiple of the other's. One problem of our proposed solution occurs when the bottleneck link changes while a flow is running. For example, the bottleneck link could be the home router in the beginning, while later the bottleneck link could be another router deeper in the core network. The problem occurs if the home router supports \gls{fq} and our algorithm detects this while the router in the core network, which becomes the bottleneck later on, doesn't support \gls{fq}. Then, our algorithm is going to use a delay-based \gls{cc} because that's what it determined to be correct in the beginning of the flow. However, later when the bottleneck changes, our algorithm is still using delay-based \gls{cc} even though the current bottleneck doesn't support \gls{fq} anymore. As a result, it might be possible that our algorithm uses the wrong \gls{cc}. One way to prevent this problem from occurring is to use periodic measurements. For example, our algorithm to determine \gls{fq} could be used every 5 or 10 seconds to measure again if the current bottleneck supports \gls{fq}. Another scenario that is worth noting is how our proposed solution deals with load balancing: In this research we assume that both of our flows, which we use during startup to determine the presence of \gls{fq} take the same path to the host on the other side. However, with load balancing it could happen that flow 1 takes a different path than flow 2. Fortunately, several load balancing algorithms have been proposed whose aim is to make sure that connections, which use multiple paths using Multipath TCP or QUIC, stay on the same path \citep{olivier_bonaventure_multipath_2018,olteanu_datacenter_2016,lienardy_towards_2016}. Since we envision our solution to be based on Multipath TCP or QUIC load balancing should not be a problem. \textit{Apple Music}, for example, successfully load balances multipath connections \citep{olivier_bonaventure_apple_2019}. An alternative to our algorithm could be that all routers inform the endpoints if they support \gls{fq} or not. Such a solution could, for example, use an IP or a TCP extension, which every router uses to indicate if they're capable of \gls{fq}. Then, if every device on a path supports \gls{fq}, the client would use a delay-based \gls{cca}. However, while this solutions would achieve good results, the problem is that solutions, which require participation of every device in the Internet generally suffer from insufficient deployment because not every hardware vendor and network operator can be forced to implement the proposed solution for informing about \gls{fq} capability. Concluding, we argue that our new flow startup method can help to increase the deployment of delay-based \gls{cc}. Especially for applications that are very delay-sensitive, such as video conferencing and cloud gaming, the adoption of delay-based \gls{cc} can result in a significant increase of \gls{qoe}. We demonstrated that our method works using a prototype implementation using PCC but we are also confident that a similar flow startup method can also be integrated with other \glspl{cca} such as BBR. \renewcommand*{\bibfont}{\small} \bibliographystyle{ieeetr}
{'timestamp': '2021-02-22T02:19:05', 'yymm': '2010', 'arxiv_id': '2010.08362', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08362'}
arxiv
\section{Introduction} \input{texts/introduction.tex} \section{Related work} \input{texts/relatedwork.tex} \section{Method} \input{texts/method.tex} \section{Experiments} \input{texts/experiments.tex} \section{Conclusions} \input{texts/conclusions.tex} \bibliographystyle{ieeetr} \subsection{Linear regression} In order to illustrate how the internal state $\phi$ and the prediction are changing during the adaptation process on a basic example, we devise a simple regression problem, where the goal is to predict values of a linear function based on a small amount of noisy observations $(x_i, \tilde{y}_i)$. In this setup, instead of taking state-action pairs $(s, a)$ and predicting future states $\hat{s}'$, the model receives $x$ as input and predicts the value of the function, $\hat{y}$. The changes in state and prediction distributions are shown in Figure~\ref{fig:linreg_indepth}. Figure~\ref{fig:linreg_d_s0} shows the prior state distribution over parameters. This distribution is learned during outer-loop optimization in the meta-learning phase and represents the prior over all dynamics conditions seen during training, which minimizes the expected prediction error over all samples, before any data is observed. This behaviour arises as a result of including the initial prediction error in the optimization objective (Eq.~\ref{eq:loss}). We sample values of the output $\hat{y}$ by sampling hidden state values $\phi$ from $\mathcal{_\phi, \Sigma_\phi}$ and passing the sampled hidden state values to the prediciton model. This has been shown in Figure~\ref{fig:linreg_d_y0}). The shaded area shows one standard deviation in state space projected onto the output domain. After two samples are obtained, the variance of the latent variable noticeably goes down (Figure~\ref{fig:linreg_d_s2}). Due to noise, the observed points do not exactly align with the true function, and the predicted line does not exactly go through the observed points; rather, it is still influenced by the prior (Figure~\ref{fig:linreg_d_y2}), as represented as the initial state belief. As more samples are observed, the state and prediction variance further goes down and the prediction is more accurate (Figures~\ref{fig:linreg_d_s10} and \ref{fig:linreg_d_y10}), despite the observations being very noisy. The impact of the prior is also reduced as more samples are observed. Due to non-zero value of $Q$, the prediction uncertainty will never go down to zero, allowing for lifelong adaptation to changing conditions. \begin{figure} \centering \begin{subfigure}{0.45\linewidth} \includegraphics[width=\linewidth]{images/new_lin_reg/0_state.pdf} \caption{} \label{fig:linreg_d_s0} \vspace{-2pt} \end{subfigure} \begin{subfigure}{0.45\linewidth} \includegraphics[width=\linewidth]{images/new_lin_reg/0_ylines.pdf} \caption{} \label{fig:linreg_d_y0} \vspace{-2pt} \end{subfigure} \begin{subfigure}{0.45\linewidth} \includegraphics[width=\linewidth]{images/new_lin_reg/2_state.pdf} \caption{} \label{fig:linreg_d_s2} \vspace{-2pt} \end{subfigure} \begin{subfigure}{0.45\linewidth} \includegraphics[width=\linewidth]{images/new_lin_reg/2_ylines.pdf} \caption{} \label{fig:linreg_d_y2} \vspace{-2pt} \end{subfigure} \begin{subfigure}{0.45\linewidth} \includegraphics[width=\linewidth]{images/new_lin_reg/30_state.pdf} \caption{} \label{fig:linreg_d_s10} \vspace{-2pt} \end{subfigure} \begin{subfigure}{0.45\linewidth} \includegraphics[width=\linewidth]{images/new_lin_reg/30_ylines.pdf} \caption{} \label{fig:linreg_d_y10} \vspace{-2pt} \end{subfigure} \vspace{-2pt} \caption{Analysis of adaptation mechanism, visualized on linear regression. The blue dots in (\subref{fig:linreg_d_y2}) and (\subref{fig:linreg_d_y10}) show the observed samples.} \label{fig:linreg_indepth} \vspace{-8pt} \end{figure} \subsection{FetchSlide} \begin{figure} \centering \begin{subfigure}{0.49\linewidth} \includegraphics[width=\linewidth]{images/fs/err_per_method.pdf} \vspace{-2pt} \end{subfigure} \begin{subfigure}{0.49\linewidth} \includegraphics[width=\linewidth]{images/fs/err_per_method_and_noise_noci_lowsamp.pdf} \vspace{-2pt} \end{subfigure} \caption{Domain adaptation results in FetchSlide} \label{fig:fs_res} \vspace{-8pt} \end{figure} \begin{figure} \centering \begin{subfigure}{0.49\linewidth} \includegraphics[width=\linewidth]{images/fs/pca_states_dyn_n0.00.png} \caption{} \label{fig:fs_pca_kal_dyn} \vspace{-2pt} \end{subfigure} \begin{subfigure}{0.49\linewidth} \includegraphics[width=\linewidth]{images/fs/pca_states_samples_n0.00.png} \caption{} \label{fig:fs_pca_kal_samples} \vspace{-2pt} \end{subfigure} \begin{subfigure}{0.49\linewidth} \includegraphics[width=\linewidth]{images/fs/pca_hc_dyn_noise0.00.png} \caption{} \label{fig:fs_pca_lstm_dyn} \vspace{-2pt} \end{subfigure} \begin{subfigure}{0.49\linewidth} \includegraphics[width=\linewidth]{images/fs/pca_hc_samples_noise0.00.png} \caption{} \label{fig:fs_pca_lstm_samples} \vspace{-2pt} \end{subfigure} \caption{PCA analysis of hidden states in FetchSlide for the proposed (\subref{fig:fs_pca_kal_dyn}, \subref{fig:fs_pca_kal_samples}) and LSTM-based (\subref{fig:fs_pca_lstm_dyn}, \subref{fig:fs_pca_lstm_samples}) model adaptation} \label{fig:fs_pca_res} \vspace{-8pt} \end{figure} \begin{table}[] \centering \begin{tabular}{c|c} Parameter & Distribution \\ \hline Linear friction & $\mathcal{U}(0.05, 0.7)$ \\ Torsional friction & $\mathcal{U}(10^{-4}, 10^{-2})$ \\ Rotational friction & $\mathcal{U}(5\cdot 10^{-5}, 10^{-3})$ \\ \end{tabular} \vspace{-2pt} \caption{FetchSlide randomization parameters} \label{tab:fs_params} \vspace{-8pt} \end{table} To verify that the method is suitable for domain adaptation in noisy conditions, we built an experimental setup based on the FetchSlide environment from OpenAI Gym~\cite{openaigym}. In this environment, the goal is to hit an object located at a random reachable location on the table such that it slides to a given target location. In addition to the robot joint position, both the start and target locations are known to the agent and included in the state vector. The robot is controlled via velocity commands given in Cartesian space. We used 16 dimensions for the measurement and dynamics representations $z$ and $\phi$. Following prior work on using generative models and latent space trajectory representations~\cite{ghadirzadeh2017deep,hamalainen2019affordance,arndt2019meta}, we use a variational autoencoder trained on a set of task-specific trajectories provided by human experts. This approach removes the time complexity from the problem and provides a straightforward way of collecting data for model adaptation---as the latent distribution is known to be a unit Gaussian, new trajectories can be generated by simply sampling latent vectors from that distribution and passing the latent values to the decoder. We trained the trajectory model on a set of 5.6 million trajectories which move the arm to a random point on the table and push the object away from the robot with a random angle and velocity. Using the trajectory model, we collected a set of 6.93 million hits under 28875 random friction conditions in simulation. The parameters used for friction distribution are presented in Table~\ref{tab:fs_params}. For both the baseline and the proposed method, we trained the final dynamics model on sequences of 100 samples. We used $\sigma_{s,max}^2= 0.3$. For each method, we trained four separate models with Adam~\cite{Kingma14Adam} and averaged the test results. The evaluation data was collected in the simulator under three scenarios---low, medium, and high friction. During evaluation, we additionally consider three scenarios---no observation noise, low noise ($\sigma^2=0.1$) and high noise ($\sigma^2=0.5$), where the high noise condition corresponds to larger noise variance than was seen in training. The results of this evaluation are shown in Figure~\ref{fig:fs_res}. We see that the proposed method outperforms the baseline most notably in the low-sample regime and high noise conditions. Improved ability to generalize to out-of-distribution tasks can be attributed to encoding optimization within the computation graph, similarly to how MAML improves generalization performance through embedding gradient descent~\cite{finn2018universality}. We additionally analysed the principal components (PCs) of the hidden states $\phi$ in both networks. The results are shown in Figure~\ref{fig:fs_pca_res}. The left subplots (\ref{fig:fs_pca_kal_dyn} and \ref{fig:fs_pca_lstm_dyn}) are color-coded by the evaluation domain (low, medium or high friction) and the right ones (\ref{fig:fs_pca_kal_samples} and \ref{fig:fs_pca_lstm_samples}) by the number of samples observed by the model. Looking at Figure~\ref{fig:fs_pca_kal_dyn}, we can observe that the dynamics lie in the order of decreasing friction, with high friction on the left, medium friction in the middle, and low friction much farther to the right. We also observe that the LSTM model encodes uncertainty, as expressed by the number of observed samples, in the hidden states. Additionally, it does not clearly separate the medium and high friction conditions; rather, the PCA projections span the same area even after observing 80 samples. The proposed Kalman filter-based architecture clearly splits the two domains already with less than 20 samples. \subsection{Hockey puck} \begin{figure} \centering \begin{subfigure}{0.23\linewidth} \includegraphics[width=\linewidth]{images/simulator.png} \caption{} \label{fig:setup_sim} \vspace{-4pt} \end{subfigure} \begin{subfigure}{0.37\linewidth} \includegraphics[width=\linewidth]{images/setup_big.jpg} \caption{} \label{fig:setup_robot} \vspace{-4pt} \end{subfigure} \begin{subfigure}{0.37\linewidth} \includegraphics[width=\linewidth]{images/pucksnsticks_big.jpg} \caption{} \label{fig:setup_pucks} \vspace{-4pt} \end{subfigure} \caption{The simulated~(\subref{fig:setup_sim}) and real~(\subref{fig:setup_robot}) experimental setups, with a close-up of tools used for the experiments (\subref{fig:setup_pucks})} \label{fig:setup} \vspace{-12pt} \end{figure} For the sim-to-real experiments, we used the same hockey puck setup as in~\cite{arndt2019meta}. This setup consists of a KUKA LBR4+ robot arm equipped with a floorball stick, a horizontally placed whiteboard, and a two hockey pucks with different masses and friction characteristics: an inline hockey puck and an ice hockey puck. The goal is to hit the hockey puck with the stick such that the puck stops at a given target location. Solving this problem requires the model to learn the friction parameters between the puck and the surface it is sliding on, as, after the puck is hit, friction is the main force causing it to stop. This setup is very similar to FetchSlide, with the additional challenge posed by some phenomena which occur in the physical world, but are not modelled in the simulator, such as hockey blade bending due to elasticity or the whiteboard surface not being perfectly flat and uniform. The experimental setup and the tools are presented in Figure~\ref{fig:setup}. The position of the hockeypuck is measured by a top-mounted Kinect camera. While the camera itself has quite small inaccuracy, we noticed that the system dynamics are not fully deterministic; executing the same trajectory with the same starting puck position (up to a margin of manual positioning error) may produce different results with the standard deviation in position around 5--10 cm, depending on the trajectory and the puck used. We use the same trajectory generation approach as in the FetchSlide experiments, with the trajectories being generated in joint space instead of Cartesian space. \subsubsection{Hockeypuck simulation experiments} The simulated setup was constructed in MuJoCo~\cite{Todorov2012MuJoCoAP}, based on the physical setup. In order to generate training data from a wide variety of conditions, we randomized the friction between the hockey puck and the whiteboard surface, as well as the mass of the puck. To account for slight misalignments between the physical and simulated setups, we additionally randomized the starting position of the puck. We added random noise in a similar fashion to FetchSlide, with noise variance sampled from $\sigma_s^2 \sim \mathcal{U}(0, 0.5)$. These randomizations make up for a much wider range of system dynamics than tested in FetchSlide, and match the configurations presented in~\cite{arndt2019meta}. We also compare the performance to model adaptation with MAML~\cite{finn2017maml}. Due to the gradient update rule in MAML being batched, as opposed to recurrent architectures, we test MAML models trained with different amounts of environment rollouts used per update step, where smaller batch sizes allow the model to adapt with fewer samples, but the updates are less accurate. The network used for MAML consists of 4 fully connected layers with 128 neurons each. We performed up to 3 adaptation steps with MAML during training, as more steps led to instability during training and adaptation. The gradient update step size $\alpha$ is learned during training. \begin{table}[] \centering \begin{tabular}{c|c} Parameter & Distribution \\ \hline Puck mass & $\mathcal{U}(0.01, 0.1)$ \\ Linear friction $\mu_x$ & $\mathcal{U}(0.15, 0.95)$ \\ Linear friction $\mu_y$ & $\mathcal{U}(0.7\mu_x, 1.3\mu_x)$ \\ Torsional friction & $\mathcal{U}(0.001, 0.05)$ \\ Rotational friction & $\mathcal{U}(0.01, 0.3)$ \\ Initial position error & $\mathcal{N}(0, 0.02)$ \\ \end{tabular} \caption{Randomization parameters} \label{tab:hp_params} \vspace{-12pt} \end{table} \begin{figure} \centering \begin{subfigure}{.35\linewidth} \includegraphics[width=\linewidth]{images/hockey/err_per_method_sim.pdf} \caption{} \label{fig:err_method_sim} \end{subfigure} \begin{subfigure}{.6\linewidth} \includegraphics[width=\linewidth]{images/hockey/err_per_interesting_conditions_noci_lowsamp_legout_sim.pdf} \caption{} \label{fig:err_per_cond_sim_ls_maml} \end{subfigure} \begin{subfigure}{\linewidth} \includegraphics[width=\linewidth]{images/hockey/err_per_method_and_noise_noci_legout_sim.pdf} \caption{} \label{fig:err_dynnoci_sim} \end{subfigure} \vspace{-2pt} \caption{Performance in HockeyPuck (simulation), averaged over all test conditions~(\subref{fig:err_method_sim}), shown separately for different simulated conditions~(\subref{fig:err_per_cond_sim_ls_maml}), and for each noise level (\subref{fig:err_dynnoci_sim})} \label{fig:err_hp_sim} \vspace{-18pt} \end{figure} The results of the evaluation in simulation, as expressed by distance between the predicted and true position in meters, are shown in Figure~\ref{fig:err_hp_sim}. We can see that, in a scenario where both models were trained and evaluated on data from simulation (which falls within the task distribution seen during training), there is no significant change in performance between the proposed architecture and LSTM; both methods perform the same with similar error margins (the shaded areas indicate the standard deviation of prediction errors). On this benchmark, both recurrent methods also outperform MAML~\cite{finn2017maml}, as shown in Figure~\ref{fig:err_hp_sim}. In Figure~\ref{fig:err_method_sim}, we observe that performing MAML updates with 1 sample per update achieves comparable performance improvements at first, but due to noise converges to a large average error of over 20~cm. Performing more "stable" MAML updates with 8 samples per update achieves comparable, but slightly worse, final performance, yet performs much worse when only a few samples are available. In Figure~\ref{fig:err_per_cond_sim_ls_maml}, we detail the adaptation error for a selection of different conditions: low, medium and high isotropic frictions in the low sample regime. We can observe that the adaptation error is the highest in the low friction case. Figure~\ref{fig:err_dynnoci_sim} shows the error for each method in various noise conditions. We again observe that both the LSTM and Kalman methods outperform MAML, with the Kalman approach providing slightly better performance. We also observe that, as expected, the difference between noisy and noiseless conditions for MAML is more pronounced when the update batch size is small. \subsubsection{Physical experiments} In order to test the suitability of our method for sim-to-real transfer, we generated random trajectories using the generative model, executed them on the physical setup, recorded the resulting puck positions, and evaluated each method on the resulting data. The results are shown in Figure~\ref{fig:err_hp_real}. In Figure~\ref{fig:err_method_real}, we observe that both recurrent methods outperform MAML in the low sample area. Analyzing the performance of various model-based MAML updates, we observe that, similarly to simulation, updating with one sample achieves the best performance at first, but converges to a fairly large error. With 4 samples per update, MAML is able to match the performance of recurrent after about 20 samples (around 3 times more). We can also observe that the Kalman filter-based method outperforms the blackbox LSTM architecture in the low-sample regime, as highlighted in Figure~\ref{fig:err_zoom_real}. We observe that the Kalman filter-based approach is able reach error below 14cm with 8 samples, while the LSTM approach requires 12 (50\% more). We believe that, due to inaccuracies between simulated and real conditions, the real-world data lies a bit out of the training distribution of the model, especially in terms of the noise distribution; thus, having the inference procedure embedded in the graph, can improve generalization to out-of-task distributions. In~\cite{finn2018universality}, it was observed that enforcing the inner-loop update to gradient descent improves generalization to classification tasks with data coming from outside the training domain, in comparison to learned update rules; this is because, even for out-of-domain data, gradient descent still constitutes a sensible update rule. In a similar fashion, based on our results, we can state that the Kalman filter update rules provide better handling of out-of-domain data distributions in comparison to learned update rules, as is the case with LSTM. In Figure~\ref{fig:err_dynnoci_real}, we show the estimation error for each method for the two hockeypucks we used for the evaluation, zoomed in to the low sample area. We observe that both recurrent methods outperform MAML, with the proposed Kalman filter-based approach outperforming LSTM for both pucks. We also compare our results to the results obtained in~\cite{arndt2019meta}, where a reinforcement learning policy was trained in simulation for the same setup and task. In that work, the average position error for the red puck was 14.4 cm after observing 16 real-world samples; with the model-based adaptation approach, we achieve a comparable error (14.2 cm) after observing only 7 samples. Similarly, for the blue puck the average error after observing 16 samples was 27.7 cm, while the proposed method achieves the same performance with only 3 samples, reaching the average prediction error of 13.3cm with 16 samples. After 64 observations, the average error in~\cite{arndt2019meta} was 13.8 cm; with the proposed method, we were able to reach this value with only 7 samples. Thus, our trained model could be used to find a much better policy (e.g. by backpropagating through the learned environment model or by training an inverse model) than the policy trained in~\cite{arndt2019meta}. \begin{figure} \centering \begin{subfigure}{.49\linewidth} \includegraphics[width=\linewidth]{images/hockey/real/err_per_method.pdf} \caption{} \label{fig:err_method_real} \vspace{-2pt} \end{subfigure} \begin{subfigure}{.49\linewidth} \includegraphics[width=\linewidth]{images/hockey/err_per_conditions_zoom_lowsamp.pdf} \caption{} \label{fig:err_zoom_real} \vspace{-2pt} \end{subfigure} \begin{subfigure}{\linewidth} \centering \includegraphics[width=.8\linewidth]{images/hockey/real/err_per_interesting_conditions_noci_lowsamp_legout.pdf} \caption{} \label{fig:err_dynnoci_real} \vspace{-4pt} \end{subfigure} \caption{Performance in real conditions averaged over two pucks~(\subref{fig:err_method_real}), zoomed in~(\subref{fig:err_zoom_real}), and detailed for each puck in~(\subref{fig:err_dynnoci_real})} \label{fig:err_hp_real} \vspace{-18pt} \end{figure} In Figure~\ref{fig:hp_pca}, we visualize the state space of the Kalman filter using PCA, similarly to previous FetchSlide analysis. We can also see that the real conditions we used for testing actually lie very close to each other, between medium and low friction, in the direction of anisotropic friction with lower value along $y$. Based on this, we can say that the randomization range used in the simulator for generating the training data was excessive. We also suspect that the shift towards anisotropic effects is a result of unmodeled phenomena, such as the hockey blade slightly bending during the hit. This analysis can be used to search for a range of randomization parameters that encapsulate the real conditions with a much smaller margin of error (by adjusting the parameters given in Table~\ref{tab:hp_params}) Similarly, comparing cluster sizes between real and simulated conditions with varying amounts of noise can provide a more accurate measure about the noise level in the real domain. Such an analysis would provide a more accurate state prior for the dynamics model and could be used to train a model which achieves even smaller error in the low sample regime with the same training method. We also observe that the hidden state space has learned friction representations which disentangle the magnitude and direction of friction---the low friction domain lies to the left, with the friction increasing along the first PC. Based on the position of the anisotropic friction domains, we can state that the second PC encodes the direction of friction---the domain with lower friction along $x$ lies above the isotropic medium friction domain, while the domain with lower $y$ friction lies below it. Thus, we observe that the method learns interpretable and useful dynamics representations. \begin{figure} \centering \begin{subfigure}{.49\linewidth} \includegraphics[width=\linewidth]{images/hockey/pca_states_dyn_medsmp_n0.00.png} \caption{} \label{fig:hp_pca_kal_dyn} \vspace{-4pt} \end{subfigure} \begin{subfigure}{.49\linewidth} \includegraphics[width=\linewidth]{images/hockey/pca_states_samples_n0.00.png} \caption{} \label{fig:hp_pca_kal_samples} \vspace{-4pt} \end{subfigure} \caption{PCA analysis of hidden states in Hockeypuck for Kalman filter-based adaptation, showing real and simulated domains. (\subref{fig:hp_pca_kal_dyn}) shows clusters after observing 20 samples.} \label{fig:hp_pca} \vspace{-12pt} \end{figure} \subsection{Problem formulation and solution overview} Given a state $s_i$ and an empty initial database $\mathcal{D}_0$ of state transitions $(s, a, s')$, we consider the problem of successively choosing one of $N$ actions. Each action $a_i$ leads to a new state $s_i'$. In addition, the state observation process may be disturbed by random noise, leading to noisy observation $\tilde{s}'$. Successively, we update the current database $\mathcal{D}_i = \mathcal{D}_{i-1} \cup \{(s_i, a_i, s_i')\}$ with the newly observed state action pair $(s_i, a_i, s_i')$. We assume that the dynamics of the considered sequential decision making problem can be modeled as a supervised learning problem: \begin{equation} \begin{pmatrix} s_{i}' &&\hspace{-10pt} \phi_i \end{pmatrix}^\top = f_\theta(s_i, a_i, \phi_{i-1}) \end{equation} using a function approximator $f_{\theta}(\cdot)$ where $\theta$ denotes its parameters and $\phi_{i-1}$ represents the hidden state which is governed by a function $g$ of previous action and noisy state observations: \begin{equation} \phi_{i-1} = g(\mathcal{D}_{i-1}) \end{equation} In the proposed method, the hidden state $\phi$ is a task-specific parameter vector, describing the unknown system dynamics. \begin{figure} \centering \includegraphics[width=\linewidth]{images/SchemUpdated.pdf} \caption{Method overview. The architecture consists of three main parts: measurement (green), state integration (yellow), and prediction (blue).} \label{fig:method_overview} \vspace{-12pt} \end{figure} In order to estimate this state from noisy measurements, we build a neural network, as shown in Figure~\ref{fig:method_overview}. The architecture consists of three main parts: measurement (which estimates the system dynamics based on a noisy observation of a state transition), state integration (which integrates the parameter estimations together), and prediction (which estimates the next state given the previous state and the action). \subsection{Measurement model} The measurement model, shown in green in Figure~\ref{fig:method_overview}, estimates the distribution of possible system states $\tilde{z}$ (representing the dynamics of the system) given the measurement: $\tilde{z}_i \sim f^m_\theta(s_{i}, a_{i-1}, \tilde{s}'_{i-1})$. To make the system robust to observation noise, we corrupt the state observations with Gaussian noise: $\tilde{s} = s + \epsilon$, where $\epsilon \sim \mathcal{N}(0, \Sigma_s)$. As we assume that we do not know the exact level of noise variance of the real environment, we incorporate $\Sigma_s$ into the task description, with $\Sigma_s$ being a diagonal matrix with values sampled from a uniform distribution: \begin{equation} \label{eq:sigma_s} diag(\Sigma_s) \sim \mathcal{U}(0, \sigma^2_{s,max}) \end{equation} The internal state representations are learned by the neural network in an unsupervised manner during training. The distribution described by $f^m$ is modeled as a Gaussian parametrized by mean and covariance: $\tilde{z} = \mathcal{N}(\mu_z, \Sigma_z)$. This procedure corresponds to step~\ref{alg2:measure} of Algorithm~\ref{alg:metatraining}. For many systems, it is impossible to uniquely determine the dynamic conditions based on a single measurement; i.e., the system can be seen as underdetermined from the parameter estimation perspective. Thus, in addition to uncertainty introduced by measurement noise, the measurement covariance matrix has to convey the uncertainty caused by the possible underdetermined nature of the system. We hence use heteroskedastic uncertainty, with covariance $\Sigma_z$ predicted for each measurement. The returned measurement can thus be interpreted as a probability distribution over all systems from which the observed state transition could originate. \subsection{Integration} The measurement distribution returned by the measurement model is passed to the recurrent part of the network, marked in yellow in Figure~\ref{fig:method_overview}, which is responsible for integrating the observations together. In our method, this is achieved by a deep Kalman filter~\cite{haarnoja2016backprop}---a Kalman filter embedded within a neural network, where the parameter matrices of the filter are trained with backpropagation together with the rest of the network. Such a network has the inference procedure built-in in the computation graph, which was shown to improve its ability to integrate information from individual samples and reason about uncertainty~\cite{haarnoja2016backprop}. \SetKwInput{KwData}{Input} \vspace{-4pt} \begin{algorithm} \SetAlgoLined \KwData{Dataset $\{(s, a, s')\}$ of state transitions} \KwResult{Network parameters $\theta$} randomly initialize network parameters $\theta$\; \While{not converged}{ Reset internal parameters ($\mu_\phi$ and $\Sigma_\phi$)\; Sample task $\tau$ (dynamics and noise variance,~Eq.~(\ref{eq:sigma_s}))\; \label{alg2:sample_task} Sample a sequence of $N$ state transitions $(s, a, s')$ from $\tau$\; \label{alg2:sample_trans} \For{each transition $(s, a, s')$ in the sequence} { Generate noise: $\tilde{s'} \sim \mathcal{N}(s', \Sigma_s)$\; \label{alg2:get_noise} Update state estimate (Eqs. \ref{eq:pred_mean} and \ref{eq:pred_cov})\; \label{alg2:preupdate} Estimate the dynamic conditions $\mu_z, \Sigma_z = f^m_\theta(s, a, \tilde{s}')$ \; \label{alg2:measure} Update $\mu_\phi$ and $\Sigma_\phi$ conditioned on $\mu_z$ and $\Sigma_z$ (Eqs. \ref{eq:kalmangain}, \ref{eq:mu_update}, \ref{eq:sigma_update})\; \label{alg2:update} Predict $\hat{s'} = f_{\theta}^p(s, a, \mu_\phi)$\; \label{alg2:predict} } Calculate loss over the sequence (Eq. \ref{eq:loss}) \; \label{alg2:loss} Calculate $\nabla_\theta \mathcal{L}$ and update $\theta$ using Adam \; \label{alg2:metaaupdate} \vspace{-4pt} } \caption{Training the dynamics model} \label{alg:metatraining} \end{algorithm} The first step of a Kalman filter performs a state prediction based on a learned model \begin{equation} \label{eq:pred_mean} \mu_{\phi}^{t+1|t} = A \mu_{\phi}^{t|t} + Bu, \end{equation} where $\mu_{\phi}^{t|t}$ represents the mean of the current belief about the state of the system, and $u$ represents external input. In our case, where the state actually represents a dynamic parameter vector, the action $u$ would correspond to an external action which directly impacts the dynamics. We assume that no such action takes place, and thus we set $B$ to zero. The state estimation is modeled as a Gaussian with the covariance \begin{equation} \label{eq:pred_cov} \Sigma_{\phi}^{t+1|t} = A^\top \Sigma_{\phi}^{t|t} A + Q . \end{equation} In the state dynamics prediction formulation, this update represents temporal change in dynamics. For a stationary system, $A$ is the identity matrix, and a small non-zero value of the covariance matrix $Q$ can be used to approximate unmodeled drift in dynamic conditions and prevent the estimation covariance from approaching zero in limit, enabling lifelong learning. This procedure corresponds to step~\ref{alg2:preupdate} of Algorithm~\ref{alg:metatraining}. The state prediction is updated in step~\ref{alg2:update} of Algorithm~\ref{alg:metatraining} by integrating information coming from a measurement, following the standard Kalman filter equations~\cite{haarnoja2016backprop}, and resulting in $\mu_{\phi}^{t+1|t+1}$ and $\Sigma_{\phi}^{t+1|t+1}$. First, the Kalman gain is calculated with \begin{equation} \label{eq:kalmangain} K_t = \Sigma_{\phi}^{t+1|t} C_z^\top (C_z \Sigma_{\phi}^{t+1|t} C^\top_z + \Sigma_z)^{-1} \end{equation} Then, the belief about the mean $\mu_\phi$ is updated with \begin{equation} \label{eq:mu_update} \mu_\phi^{t+1|t+1} = \mu_\phi^{t+1|t} + K_t (z_t - C_z \mu_\phi^{t+1|t}) \end{equation} Finally, the covariance of the state belief is updated by \begin{equation} \label{eq:sigma_update} \Sigma_{\phi}^{t+1|t+1} = (I - K_t C_z) \Sigma_{\phi}^{t+1|t} \end{equation} We use a standard linear Kalman filter, as the non-linear correspondence between the measurements and internal states is already addressed by the non-linear measurement system. The values of $C_z$ and the initial state distribution (parametrized by $\mu_\phi^0$ and $\Sigma_\phi^0$) are learned during outer-loop optimization. The use of Kalman filters allows us to introduce additional information in the prediction model---namely, we assume that the system is stationary (the transition matrix $A=I$), while allowing for some temporal drift to encourage the system to keep adapting over long periods of time and to improve numerical stability ($Q=\epsilon I$). \subsection{State prediction} Finally, the future state of the environment is predicted for the queried state-action pair by the \textit{prediction model} $\hat{s}'_i = f^p_\theta(s_i, a_i, \mu_\phi)$. This model, like the measurement model, is a neural network. The state prediction takes place in step~\ref{alg2:preupdate} of Algorithm~\ref{alg:metatraining}. During meta-training on data collected in a simulated environment, the optimization objective $\mathcal{L}$ is calculated as the mean-squared error between the predictions of the entire model at each timestep over the whole sequence, and the noiseless ground-truth observations $s_i'$: \begin{equation} \label{eq:loss} \mathcal{L} = \frac{1}{N} \sum_{i=1}^{N} (\hat{s_i}' - s_i')^2. \end{equation} The loss calculation and model optimization are performed, respectively, in steps~\ref{alg2:loss} and~\ref{alg2:metaaupdate} of Algorithm~\ref{alg:metatraining}. The model is trained as a whole in an end-to-end fashion. \subsection{Meta-learning} Many meta-learning approaches are based on a recurrent neural network architecture, which the hidden state is updated based on the observed learning data~\cite{hochreiter2001learning}. As the optimization procedure itself is learned together with the state representations, these methods are often referred to as \textit{blackbox meta-learning}. With the advancement of deep learning, another family of meta-learning methods---optimization-based meta-learning---was introduced by Finn~et~al. with the model-agnostic meta-learning algorithm (MAML)~\cite{finn2017maml}. Multiple extensions to the original algorithm were proposed later~\cite{flennerhag2019metalearning,stadie2018emaml}. These methods, however, rely only on the mean gradient direction calculated over multiple samples while discarding the variance, and do not encode the uncertainty information in any way. Various probabilistic extensions to MAML were introduced~\cite{finn2018platipus, yoon2018bmaml}; these approaches rely on ensemble models or Stein variational gradient descent to introduce sampling operations to the network during training, in order to encode uncertainty in the network output. Our approach to model-based meta adaptation is based on the idea of training Kalman filters via backpropagation, as proposed in~\cite{haarnoja2016backprop}. In that work, a Kalman filter is embedded inside a neural network and trained via backpropagation. The architecture proposed in~\cite{haarnoja2016backprop} is shown to improve performance on standard state estimation tasks with deep learning over other recurrent architectures. We propose to use a similar architecture for adaptation of dynamics models, rather than standard state estimation. Recently, some considerations on uncertainty-aware meta-learning were put forward by Gordon~et~al.~\cite{gordon2018metalearning}, where it is proposed to view meta learning as learning a distribution over task-specific parameters. Our method can be viewed as a special case of this generalized framework, where the parameters are modeled as Gaussian distributions and the inference is performed using standard Kalman filter update rules. \subsection{Sim-to-real transfer in robotics} The problem of sim-to-real transfer in robotics has been widely addressed in recent years, especially within the context of reinforcement learning. In the most basic approach, policies are trained in simulation and reused in the real world. This, however, requires tedious fine-tuning of simulation parameters, and sometimes requires extreme measures, such as disassembling the robot and measuring the individual components in order to fine-tune the simulation~\cite{tan2018sim}. Moreover, some physical phenomena such as backlash cannot be modeled in simulation, making the policies learned in simulation inefficient for real world. The view-invariant servoing approach presented in~\cite{sadeghi17sim2real} can be thought of as an example of blackbox memory-based meta-learning; the recurrent model is trained over a variety of different simulated conditions such that it can adapt to real world conditions, as more and more samples are collected during operation. This method, however, focuses on optimizing a task-specific policy, which requires that policy to be run on the physical setup before being exposed to any real world data. Additionally, the collected data cannot be reused for other tasks, and the method does not account for the uncertainty present in real-world data. Previous work on meta-learning for sim-to-real transfer focused on policy adaptation~\cite{Nagabandi2019learning,arndt2019meta,Song2020RapidlyAL}. With these approaches, the final policy is a direct result of an on-policy update performed on the policy used to collect the data, as in~\cite{finn2017maml}. As such, not only do the meta-policy parameters need to constitute a starting point for further adaptation, but also the meta-policy itself needs to explore the environment in a way which provides meaningful information for adaptation~\cite{stadie2018emaml}; there is, however, no straightforward and universal way of balancing between these two objectives~\cite{stadie2018emaml, gupta18metareinforcement, rothfuss2018promp}. Using our method, on the other hand, a dynamic model can be optimized using data collected from a policy which is known to be safe, and is capable of providing informative samples. Model adaptation with meta-learning has been previously utilized by Clavera~et~al.~\cite{clavera2018model} as a method of regularizing and stabilizing model-based reinforcement learning. This method, however, only considered minor discrepancies between models, and---like other gradient-based methods---discarded uncertainty information in the update rule. The method we propose in this paper, in contrast, aims at adapting to a wide variety of conditions and explicitly keeps track of the uncertainty (as expressed by the variance of the task-specific parameter vector).
{'timestamp': '2020-10-19T02:17:31', 'yymm': '2010', 'arxiv_id': '2010.08397', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08397'}
arxiv
\section{Introduction}\label{sec:introduction}} \else \section{Introduction} \label{sec:introduction} \fi \IEEEPARstart{T}{his} demo file is intended to serve as a ``starter file'' for IEEE Computer Society journal papers produced under \LaTeX\ using IEEEtran.cls version 1.8b and later. I wish you the best of success. \hfill mds \hfill August 26, 2015 \subsection{Subsection Heading Here} Subsection text here. \subsubsection{Subsubsection Heading Here} Subsubsection text here. \section{Conclusion} The conclusion goes here. \appendices \section{Proof of the First Zonklar Equation} Appendix one text goes here. \section{} Appendix two text goes here. \ifCLASSOPTIONcompsoc \section*{Acknowledgments} \else \section*{Acknowledgment} \fi The authors would like to thank... \ifCLASSOPTIONcaptionsoff \newpage \fi \section{Introduction}\label{sec:introduction}} \IEEEPARstart{T}{his} demo file is intended to serve as a ``starter file'' for IEEE Computer Society journal papers produced under \LaTeX\ using IEEEtran.cls version 1.8b and later. I wish you the best of success. \hfill mds \hfill August 26, 2015 \subsection{Subsection Heading Here} Subsection text here. \subsubsection{Subsubsection Heading Here} Subsubsection text here. \section{Conclusion} The conclusion goes here. \appendices \section{Proof of the First Zonklar Equation} Appendix one text goes here. \section{} Appendix two text goes here. \ifCLASSOPTIONcompsoc \section*{Acknowledgments} \else \section*{Acknowledgment} \fi The authors would like to thank... \ifCLASSOPTIONcaptionsoff \newpage \fi \section{Introduction}\label{sec:introduction}} \IEEEPARstart{T}{hree} dimensional (3-D) scene reconstruction from multiple views is one of the oldest fields of computer vision and photogrammetry, and it has diverse applications including autonomous vehicle navigation, historical conservation, and industrial tasks such as process inspection and quality assurance \cite{van_damme_computer_2015,yastikli_documentation_2007,khoshelham_accuracy_2012}. Stereo reconstruction is a process which calculates the position of an object feature in 3-D space by detecting it in two images. This can be summarized in the following steps: \begin{enumerate} \item Geometric calibration determines the intrinsic and extrinsic camera parameters. \item Correspondence matching identifies the pairs of pixels that view the same object. \item Triangulation calculates the 3-D position of the object using disparity in the image plane. \end{enumerate} Point clouds (and depth or disparity maps) are the most primitive 3-D data calculated from these processes. Every point in a point cloud has an x, y, z value in Euclidean space and a brightness (color or black and white). However, this 3-D information is meaningless if we have not characterized its associated uncertainty, reliability, reproducibility, and errors. The uncertainty in brightness is determined by radiometric factors such as the surface properties and illumination conditions \cite{sonka_image_2014,kamberova_sensor_1998}. The uncertainty in position is caused by errors at all three stages of stereo reconstruction, system geometry and image plane quantization. A lot of research has been carried out into the study of errors generated from calibration \cite{xu_error_2013, schreve_how_2014, di_leo_uncertainty_2011, yang_analysis_2017, shawash_real-time_2013} and correspondence matching \cite{ng_solving_2019, liu_3d_2015, ma_robust_2014, scharstein_taxonomy_2001, li_comparison_2011, marr_cooperative_1976}. There is also a disparate body of research that we summarize as geometrical constraints on error, which is concerned with the fundamental limitations on what a given system of cameras can measure. These factors include intrinsic camera properties, such as the sensor dimensions and focal length, and extrinsic camera properties, such as their baseline distance and angle of focal axis convergence \cite{kyto_method_2011, schreve_how_2014, yang_analysis_2017}. Another geometrical constraint is the quantization of the image plane into pixels by the camera sensor (such as a CCD or CMOS), which gives rise to errors in point position called quantization error \cite{fooladgar_geometrical_2013, wu_analysis_1998}. \subsection{Image Plane Quantization Error} Many 3-D from stereo algorithms use the disparity in the image planes to calculate 3-D position using triangulation \cite{hartley_triangulation_1997}. This assumes that two lines from the perspective center of each camera, $A$ and $B$ in figure \ref{fig_perspective}, intersect at the object position in space, denoted by $X$. These lines intersect with the image planes at $w_{A}$ and $w_{B}$, this is further discussed in section \ref{sec:pinhole}. By this stage of the calculation, errors in the object position on the image plane have been introduced, which may produce projection lines that do not intersect \cite{wenhardt_minimizing_2007}, motivating studies of how to minimize and adjust the errors in the image plane \cite{zhang_triangulation_2009, hartley_triangulation_1997}. Furthermore, the quantization of the camera sensor introduces limitations in the spatial resolution of the image plane, which is problematic because triangulation assumes pixels to be points rather than rectangles \cite{wu_analysis_1998}. \begin{figure}[!t] \centering \inputTikZ{1}{Figures_and_Plots/perspective.tikz} \caption{Perspective projection geometry for two coplanar cameras.} \label{fig_perspective} \end{figure} \begin{figure}[!t] \centering \includegraphics[scale=0.9,trim=0 40 70 0, clip]{pyramids_axes.pdf \caption{Perspective projection of pyramids to represent pixel views. The intersection of these pyramids is a polyhedron.} \label{fig_pyramids} \end{figure} If we model a pixel as a rectangle instead of a point, and its projection into space as a pyramid instead of a ray during triangulation, we can calculate the localization error caused by image plane quantization. The intersection of two pyramids gives a polyhedron of six or more sides, which represents an absolute uncertainty bound for the calculated object position, illustrated in fig. \ref{fig_pyramids}. This is referred to as an uncertainty region or error volume \cite{fooladgar_geometrical_2013,wu_analysis_1998}. Wu, Sharma and Huang pioneered this approach in 1998, and used the volume of the polyhedron as an error measurement \cite{wu_analysis_1998}. Limited by computational power at the time, rather than calculating the volume of the polyhedron, they fit the vertices to an ellipsoid using principle component analysis and worked with the ellipsoid volume instead. They also suggested that the ratio of major to minor axis and the direction and size of the major axis gives a quantitative measure of localization error due to quantization. The idea was picked up again by Fooladgar et al. in 2013, where they applied the idea to circular pixels, which makes the field of view a cone instead of a pyramid \cite{fooladgar_geometrical_2013}. The intersection of two cones is a non-trivial problem that can be solved using a Lagrangian method. They further proposed two analytic solutions that reduce the computational cost by assuming one pixel projection is a cone and the other is four planes, the faces of a pyramid. Due to computational limitations they took the took the maximum and minimum coordinate values of the polyhedron vertices to approximate this shape as a cuboid. Both the polyhedron volume and the cuboid volume have the same dimensions in $x$, $y$ and $z$, as shown in fig. \ref{fig_bounds}. The volume of the polyhedron (green) will always be less than the cuboid (blue), depending on the nature of the shape this can be a large or a small difference. The ellipsoid volume used in \cite{wu_analysis_1998} would be fitted to the vertices of the polyhedron. Both studies present methods to calculate ellipsoid or cuboid approximations of the polyhedral error volume, for one pixel combination at a time. In this paper, we present a method to calculate the true polyhedron volume for all pixel combinations in a stereo pair. Rather than calculating the complex polyhedral shape of each intersection by projecting pyramids or cones, our method generates a three-dimensional array of gridpoints in the scene and determines which gridpoints are within each intersection. This is the inverse problem of the previous approaches and the discretization of scene space is a technique used in occupancy grid mapping (see section \ref{sec:occupancy}) and volumetric scene reconstruction \ref{sec_Visual_Hull} . Given each camera we calculate which gridpoints are seen by each pixel and perform an intersection of these sets to obtain every uncertainty volume within that space. The method can be used for $n$ cameras with any rotation or translation between them (provided that their views overlap), but for this study we demonstrate the method using two coplanar camera views. In line with the earlier studies we investigate the effects of camera separation (baseline distance), focal length, pixel size and gridpoint position on the polyhedral and cuboid uncertainty volumes, and compared the latter results with \cite{fooladgar_geometrical_2013}. \subsection{Related Work} \subsubsection{Geometric Constraints on Localization Error} Modelling and predicting the accuracy of 3-D from stereo calculations has been a common goal of many studies over the last 40 years. Here we explore a subset of that research, concerning “geometrical constraints on error” as defined in section \ref{sec:introduction}. One study presents an empirically derived model for the total absolute error in the $x$, $y$, and $z$ coordinates (as defined in fig. \ref{fig_perspective}) of a measured point, whereby the error for each coordinate is a sum of systematic and random components \cite{sankowski_estimation_2017}. They predict a similar total absolute error for the $x$ and $y$ coordinates and an order of magnitude greater error for the $z$ coordinate, although by their own admission these estimates are "pessimistically high". Even if not using this method, stating the error in each Cartesian direction as a confidence interval (for example $z = 2 \pm 0.1 \, m$) is a typical approach. An equation of the following form has been used to define the total error of a point $\varepsilon$, \begin{equation}\label{eq:error} \varepsilon = \sqrt{\varepsilon_{x}^2 + \varepsilon_{y}^2 + \varepsilon_{z}^2} \end{equation} whereby $\varepsilon_{x}$ represents the variance of the $x$ coordinate \cite{schreve_how_2014} or $\varepsilon_{x}$ represents simulated absolute errors of the $x$ coordinate \cite{xu_error_2013, yang_analysis_2017, rodriguez-quinonez_improve_2017}. Physically this represents the magnitude of the vector connecting the true and measured location of the point. The magnitude of the three components can be very different (see section \ref{sec:discussion}) and this dimensionality information is lost when calculating this quantity, as this effectively this models the uncertainty volume as a sphere. A model by Yang et al. shows how baseline distance, focal length, and convergence angle separately affect $\varepsilon$, and also uses a transfer function to see how they work in combination \cite{yang_analysis_2017}. Kyt\"o et al. performed an experiment with a multi-level calibration target to examine the effect of baseline distance and focal length on just depth error $\varepsilon_{z}$ \cite{kyto_method_2011}. Similarly, Ortiz et al. only looked at depth error but varied the resolution setting of their camera \cite{ortiz_depth_2018}. \begin{figure}[!t] \centering \inputTikZ{1}{Figures_and_Plots/polyhedral_and_cuboid_volume.tikz} \caption{Quantization uncertainty bounds for a 3-D point (black). The green shape represents the polyhedral volume and the blue lines represent the cuboid volume.} \label{fig_bounds} \end{figure} In many papers, half the length of a pixel is assumed to be the quantization error for any point measured by the system \cite{schreve_how_2014, chang_quantization_1992, rodriguez_stochastic_1990}, and this was thought to be dependent on depth but independent of other geometric factors such as camera separation, focal length and position in the other two directions. Wu et al. and Fooladgar et al. demonstrated that quantization error is highly dependent on these factors by modelling the uncertainty volumes (see preceding section) rather than just the total magnitude in (\ref{eq:error}). Uncertainty volumes have also been used in other studies as a way to communicate the probabilistic nature of calculated 3-D point positions, for example De Cecco et al. generated uncertainty ellipsoids to take into account the uncertainties from calibration and stereo matching \cite{de_cecco_uncertainty_2009}. \subsubsection{Occupancy Grid Mapping}\label{sec:occupancy} In order to deal with sensor uncertainty, occupancy grid mapping represents the environment in a different way to a point cloud. The continuous space of the scene is discretized into a three-dimensional array and one calculates the probability that each gridpoint is occupied. This volumetric reconstruction method came about in the field of autonomous robot navigation with sonar in mind \cite{elfes_using_1989}, and starkly contrasted with surface reconstruction methods in robot perception. Occupancy grids can easily integrate noisy sensor data and different sensor modalities, such as LIDAR and photogrammetry, into a single environment map \cite{pirker_fast_2011}. In addition to modelling objects, the process also models free space and unseen space, which is ideal for applications like path planning and robotic arm manipulation. The accuracy of this technique is dependent on the degree of discretization of the scene space (the resolution of the grid) and the probability model. Although it has been used with stereo vision and triangulation \cite{moravec_robot_1996}, there has been more work on distance to sensor methods such as disparity maps \cite{lategahn_occupancy_2010, andert_drawing_2009} as these are more computationally efficient for a mobile robot \cite{perrollaz_visibility-based_2012}. \subsubsection{Volumetric Scene Representation} \label{sec_Visual_Hull} 2-D image data has however been used extensively for volumetric scene reconstruction within the field of computer vision. Early attempts focused on segmenting the scene into a foreground and background and intersecting the foreground silhouettes of multiple views. This represents the maximal space occupied by the object, known as the visual hull, and is represented by voxels \cite{martin_volumetric_1983, laurentini_visual_1994}. One approach to building the visual hull is voxel or space carving, whereby voxels determined to be outside the visual hull are progressively removed from the initial 3-dimensional grid \cite{eisert_automatic_2000, kutulakos_theory_1998, theobalt_combining_2004}. Another approach is to additively build the visual hull using constructive solid geometry intersections \cite{matusik_image-based_2000}. Conceptually some of these approaches are similar to the method presented in this paper. Lok describes the visual hull as "the 3-D intersection of all object pixel projection volumes" \cite{lok_online_2001}. The first authors to calculate the pixel viewing a given voxel are Fromhertz et al. in 1994, using the rotation and translation of the object on a rotating stage \cite{fromherz_shape_1994}. Quantization artifacts are a major drawback of volumetric scene reconstruction \cite{seitz_photorealistic_1999, matusik_image-based_2000}, consequently this framework is the ideal way to measure quantization uncertainty. Our method calculates the visual hull of every pixel combination in a system, and from this it would be possible to determine the visual hull of an object spanning multiple pixels in the images. \section{Background}\label{sec:background} \subsection{Pinhole Camera Model}\label{sec:pinhole} In keeping with earlier studies. we assume the pin-hole camera model for a low distortion system \cite{amat_selection_2002}. Light from a world point at $\vec{X}$, $(X, Y, Z)$ in world coordinates, passes through the aperture or optic center, and is projected to the image at $\vec{w}$, $(u, v)$ in image coordinates. In fig. \ref{fig_perspective}, the optic centers are at $A$ and $B$ and the image planes have been reflected with respect to the $XY$ plane at $z=0$ so that it does not produce a mirror image with negative coordinates, as is more commonly seen in pinhole camera diagrams \cite{sonka_image_2014}. The distance between the cameras or baseline is represented by $b$, with the origin of the world coordinates at the midpoint. For these coplanar cameras, the $x$ and $y$ axes correspond to the $u$ and $v$ directions in image coordinates respectively, and the $z$ axis is parallel to the optical axes, which corresponds to depth in the scene. $f$ is the distance from the optic center to the image plane, commonly referred to as the focal length because this refers to the same quantity in the context of lenses. The image plane is assumed to be the same as the sensor plane, and since the image plane is discretized into pixels, the projected world points will be at within $\pm \frac{1}{2}$ pixel length of the true point \cite{wu_analysis_1998}. \subsection{Perspective Projection Model} The transformation from three-dimensional world coordinates to two-dimensional image coordinates is called perspective projection \cite{cipolla_projection_2019}. Three components are required to model the imaging process from the world point $\vec{X}$ to the pixel $\vec{w}$. These are the pixel to image plane conversion, $\+C$, perspective projection, $\+P$, and a rigid body transformation, $\+R$. These are expressed by the following linear matrix operation in homogeneous coordinates: \begin{equation} \vec{w} = \+C \+P \+R \vec{X} \end{equation} \begin{equation} \left[\begin{IEEEeqnarraybox*}[][c]{c} \IEEEstrut su\\sv\\s% \IEEEstrut \end{IEEEeqnarraybox*}\right]\!=\! \left[\begin{IEEEeqnarraybox*}[][c]{c:c:c} \IEEEstrut k_u & 0 & u_0 \\ 0 & k_v & v_0 \\ 0 & 0 & 1% \IEEEstrut \end{IEEEeqnarraybox*}\right] \! \left[\begin{IEEEeqnarraybox*}[][c]{c/c/c/c} \IEEEstrut f & 0 & 0 & 0 \\ 0 & f & 0 & 0 \\ 0 & 0 & 1 & 0% \IEEEstrut \end{IEEEeqnarraybox*}\right]\! \left[\begin{IEEEeqnarraybox*}[][c]{c/c/c/c} \IEEEstrut r_{11} & r_{12} & r_{13} & T_x \\ r_{21} & r_{22} & r_{23} & T_y \\ r_{31} & r_{32} & r_{33} & T_z \\ 0 & 0 & 0 & 1% \IEEEstrut \end{IEEEeqnarraybox*}\right]\! \left[\begin{IEEEeqnarraybox*}[][c]{c} \IEEEstrut \lambda X \\ \lambda Y \\ \lambda Z \\ 1% \IEEEstrut \end{IEEEeqnarraybox*}\right]\\%\IEEEeqnarraynumspace\\ \end{equation} \begin{equation} \left[\begin{IEEEeqnarraybox*}[][c]{c} \IEEEstrut su \\ sv \\ s% \IEEEstrut \end{IEEEeqnarraybox*}\right] = \left[\begin{IEEEeqnarraybox*}[][c]{c:c:c} \IEEEstrut a_u & 0 & u_0 \\ 0 & a_v & v_0 \\ 0 & 0 & 1% \IEEEstrut \end{IEEEeqnarraybox*}\right] \left[\begin{IEEEeqnarraybox*}[][c]{c/c/c/c} \IEEEstrut r_{11} & r_{12} & r_{13} & T_x \\ r_{21} & r_{22} & r_{23} & T_y \\ r_{31} & r_{32} & r_{33} & T_z \\ 0 & 0 & 0 & 1% \IEEEstrut \end{IEEEeqnarraybox*}\right] \left[\begin{IEEEeqnarraybox*}[][c]{c} \IEEEstrut \lambda X \\ \lambda Y \\ \lambda Z \\ 1% \IEEEstrut \end{IEEEeqnarraybox*}\right] \end{equation} where $k$ represents the pixel size in either the $u$ or $v$ direction, $u_{0}$ and $v_{0}$ are the position of the optic axis in the image plane, $f$ is the focal length, $a_{u}=fk_{u}$ and $a_{v}=fk_{v}$ are the image scaling factors, and the ratio $a_{u}/a_{v}$ is the aspect ratio. In this paper, the optic axis is in the center of the imaging plane, therefore $a_{u}=a_{v}=1$, and we assume square pixels so $k_{u}=k_{v}$. Our pair of cameras are coplanar, meaning their optic axes are parallel so there is no rotational element between them. The world coordinate origin is at the baseline midpoint, therefore the translation $T$ in $x$ will be $T_{x}=-b/2$ for camera A and $T_{x}=b/2$ for camera B, with $T_{y}=T_{z}=0$. \section{Methodology} \begin{figure}[!t] \centering \inputTikZ{1}{Figures_and_Plots/pixel_angles.tikz} \caption{The angles subtended by each pixel, $k$, vary as a function of distance from the optic center (dotted line).} \label{fig_pixel_angles} \end{figure} In this section, we summarize how we calculate all the polyhedron uncertainty volumes within a region of space represented by an occupancy grid, which involves simple vector geometry. We then detail how the results can be visualized and queried, such as determining the volume for a specific pair of pixels obtained during correspondence matching. We also present the error metrics used to measure the accuracy of our results. \subsection{Computation of the Intersection Region} We start by defining our region of interest, this can be the entire volume where the two camera views intersect, or a smaller subset of that space. We generate regularly spaced gridpoints filling this volume with cartesian coordinates $(X, Y, Z)$. The origin of the coordinate system is at the baseline midpoint. The x-axis is parallel to the baseline, the z-axis is depth and the y-axis is perpendicular to these directions. These grid points can be thought of as the centroids or vertices of cube shaped voxels. The accuracy of this method is highly dependent on the spacing between grid points, so this should be chosen carefully. In section \ref{sec:gridpoints} we investigate how the grid point spacings affect the calculated volumes for the system we model and a suitable spacing is chosen for the following experiments. The following steps, summarized in algorithm 1, determine which gridpoints are in the view of each pixel in one camera. This process is repeated for every other camera or view in the system. We start by specifying the following parameters for the camera: \begin{itemize} \item Perspective center in world coordinates, $A$ and $B$ \item Angular field of view in horizontal and vertical directions, $FOV$ \item Focal length, $f$ \item Number of pixels, $n$ \item Pixel size, $k$ \end{itemize} In this study we assume square pixels and equal numbers of detectors in the rows and columns of the sensor. We assume each pixel subtends an angle bounded by planes passing through the camera perspective center, $A$, and each pixel border, as shown in fig. \ref{fig_pixel_angles} in 2-D. The pixel border angles, $\alpha$, are calculated using perspective projection, consequently the angle viewed by each pixel decreases with increasing distance from the optic axis. To calculate the $\alpha$ angles, we generate a vector containing the x coordinates of the edges of each pixel $\vec{x_{k}}$, defined by the following sequence $\langle x \rangle$: \begin{equation} \langle x \rangle = ki, \quad i \in \mathbb{Z}, \quad \frac{-n}{2} \leq i \leq \frac{n}{2} \end{equation} CCDs always have dimensions of powers of 2, so $n$ will always be even, $n=2x,x \in \mathbb{N}$. $\alpha$ is then the inverse tangent of $\langle x \rangle$ divided by the focal length. \begin{equation} \vec{\alpha}=\arctan\left(\frac{1}{f}.\vec{x_{k}}\right) \label{eq:alpha} \end{equation} Now that we have the horizontal angles for the pixel edges, we perform the same procedure to determine the vertical angles for the pixel edges, $\gamma$. In this work we simulate square pixels therefore $\gamma=\alpha$. Next we convert the Cartesian coordinates of each scene grid point, $P$, to spherical coordinates with an origin also at the camera center, using the following: \begin{figure}[!t] \centering \inputTikZ{1}{Figures_and_Plots/spherical_coordinates_axes.tikz} \caption{Spherical coordinates used to define the position of point P.} \label{fig_spherical} \end{figure} \begin{IEEEeqnarray}{rCl} \rho &=& \sqrt{x^{2}+y^{2}+z^{2}}\\ \phi &=& \arctan \left(y/z\right)\\ \theta &=& \arctan \left(x/z\right)% \end{IEEEeqnarray} whereby $x$, $y$ and $z$ are the cartesian coordinates, $\rho$ is the distance from the optic center to $P$, $\phi$ is the elevation, and $\theta$ is the azimuth relative to the optic axis, shown in fig. \ref{fig_spherical}. We then determine which pixel view each grid point appears in. The angles in $\alpha$ are ordered and increasing, therefore, we can determine where $\theta$ for each grid point fits in to $\alpha$ by performing a binary search. This returns the index of the element in $\alpha$ such that if $\theta$ were inserted into $\alpha$, the order of $\alpha$ would be preserved \cite{van_der_walt_numpy_2011}. This index is $u$ in the case of $\theta$ and $\alpha$, and $v$ in the case of $\phi$ and $\gamma$. These are the pixel ID, $(u,v)$, for the simulated camera, shown in fig. \ref{fig_perspective}. We now know for every grid point the cartesian coordinates, spherical coordinates, and pixel ID. These values are stored in a lookup table, $LUT$, with the pixel ID as the keys and coordinates as the values. This allows us to look up all the gridpoints seen by a particular pixel, but the keys and values can be readily inverted so that we can look up the pixel viewing each gridpoint. The algorithm is summarized in algorithm 1. We repeat this process for every other camera in the system, giving us a lookup table for each one, in our case $LUT_{A}$ and $LUT_{B}$. By performing an intersection of the gridpoint coordinates in these lookup tables (intersection used in terms of set theory rather than geometry) we obtain both pixel IDs for each gridpoint. This new lookup table, $LUT_{AB}$, has the pixel IDs of both cameras as the key, $[(u_A,v_A ),(u_B,v_B )]$, and all the gridpoints within that intersection as the values. The algorithm steps are described in algorithm 2. If there are three or more views in the system you repeat algorithm 2 with $LUT_{AB}$ and $LUT_{C}$ and so on. $LUT_{AB}$ contains all the information needed to determine which pixels in cameras $A$ and $B$ see any scene point, and conversely which scene points are in the uncertainty volume of any pixel combination. \algsetup{indent=2em} \noindent\rule{\linewidth}{1pt} \textbf{Algorithm 1:} Gridpoints in view of one camera \vspace{1mm}\hrule\vspace{1mm} \noindent\textbf{Input:} $R$ = region of interest, $s$ = gridpoint spacing, camera parameters$[A, f, n, k]$ \begin{algorithmic} \STATE $G$ = GenerateOccupancyGrid$(R, s)$ \STATE $A$ = new array of length $i$ \FOR{$x$ in $\langle x \rangle$, where $\langle x_{i} \rangle$ is defined in equation 5} \STATE compute $\alpha$ using equation \ref{eq:alpha} \STATE $A[i] = \alpha$ \ENDFOR \STATE $S$ = new 3-D array with dimensions $G$ \FOR{$x,y,z$ point in $G$} \STATE compute $\rho,\theta,\phi$ using equations 7, 8, and 9 \STATE $S[x, y, z] = \rho,\theta,\phi$ \ENDFOR \STATE $U$ = new 3-D array with dimensions $G$ \STATE $V$ = new 3-D array with dimensions $G$ \FOR{$\rho,\theta,\phi$ in $S$ with index $x, y, z$:} \STATE $U[x, y, z]$ = FindBinarySearch$(A,\theta)$ \STATE $V[x, y, z]$ = FindBinarySearch$(A,\phi)$ \ENDFOR \STATE $LUT$ = new lookup table \FOR{$x, y, z$ in $G$} \STATE $u = U[x, y, z]$ \STATE $v = V[x, y, z]$ \STATE add point $P(x, y, z)$ to current list in $R[u, v]$ \ENDFOR \end{algorithmic} \noindent\textbf{Output:} $LUT$ \noindent\rule{\linewidth}{1pt} \textbf{Algorithm 2:} Gridpoints in view of 2 or more cameras \vspace{1mm}\hrule\vspace{1mm} \noindent\textbf{Input:} $LUT_{A}$, $LUT_{B}$ \begin{algorithmic} \STATE $LUT_{AB}$ = new lookup table \FOR{$u_{A}$, $v_{A}$ in $LUT_{A}$:} \FOR{$u_{B}$, $v_{B}$ in $LUT_{B}$:} \STATE $points_{A} = LUT_{A}[u_{A}, v_{A}]$ \STATE $points_{B} = LUT_{B}[u_{B}, v_{B}]$ \STATE intersection = $points_{A} \cap points_{B}$ \IF {intersection:} \STATE intersections$[u_{A},v_{A},u_{B},v_{B}]$ = intersection \ENDIF \ENDFOR \ENDFOR \end{algorithmic} \noindent\textbf{Output:} $LUT_{AB}$\\ \rule{\linewidth}{0.4pt} \subsection{Uncertainty Region Representation} The lookup table made in algorithm 2 can be queried to characterize and plot the uncertainty volumes for cameras $A$ and $B$. The polyhedron volume is obtained by counting the number of points, $p$, in each intersection and converting this to a volume in meters cubed using the spacing between grid points, $g$: \begin{equation} V = g^{3}p \label{eq:volume} \end{equation} The cuboid uncertainty volume and its dimensions offer an approximate shape of this region as shown in fig. \ref{fig_bounds}. The cuboid volume is calculated by querying the minimum and maximum coordinate values in an intersection, calculating the $x$, $y$, and $z$ dimensions and multiplying these together. It is possible to examine how the three components contribute to the volume as we vary parameters such as distance from the camera, however the usefulness of this is limited by the degree to which the major and minor axes of the polyhedron align with the cartesian axes. \subsection{Error Metrics} To test the validity of our approach we compare our results with those of previous authors in terms of Root Mean Squared (RMS) error: \begin{equation} RMS = \sqrt{\frac{\sum_{n=1}^{N} (p-o)^{2}}{N}} \end{equation} where $p$ is the predicted value, $o$ is the observed value and $N$ is the number of measurements. For our calculations the predicted values are the cuboid volumes obtained by \cite{fooladgar_geometrical_2013} and the observed values are the cuboid volumes obtained using our method. We want to express the error as a percentage, so rather than use the Mean Absolute Percentage Error (MAPE) \cite{de_myttenaere_mean_2016}, which imposes a heavier penalty when $o<p$, we use a logarithm of the accuracy ratio, $p/o$. This outperforms MAPE when the error grows as a function of a variable \cite{tofallis_better_2014}, which is the case for all our observations. We calculate the Median Symmetric Accuracy (MSA) \cite{morley_measures_2018}, given by the following: \begin{equation} MSA = 100 ((e^{M|log_{e}(p/o)|})-1) \end{equation} where $M$ represents the median function of all values of $log_{e}(p/o)$. \section{Results} \begin{figure*}[!t] \centering \subfloat[]{\input{Figures_and_Plots/baseline.tex \label{fig_baseline}} \hfil \subfloat[]{\input{Figures_and_Plots/focal.tex \label{fig_focal}} \vfil \subfloat[]{\input{Figures_and_Plots/pixel.tex \label{fig_pixel}} \hfil \subfloat[]{\input{Figures_and_Plots/object_distance.tex \label{fig_object}} \caption{Volume of uncertainty region versus (a) baseline distance, (b) focal length, (c) pixel size, (d) object distance in the $z$ direction.} \label{fig_experiments} \end{figure*} We present a series of experiments to compare the uncertainty regions calculated using this method with those obtained by earlier studies \cite{fooladgar_geometrical_2013,wu_analysis_1998}. Fooladgar et al. showed that the pyramids intersection method used by Wu et al., produced error measures “almost equal” to their cone intersection method. We ran our simulation at “a sufficiently high resolution”, discussed in section \ref{sec:gridpoints}, and calculated the polyhedron error volumes and the cuboid error volumes. We present these two measures alongside those obtained by \cite{fooladgar_geometrical_2013}, and we compare our cuboid volumes with their cuboid volumes in terms of Root Mean Square Error (RMSE) and Median Symmetric Accuracy (MSA), shown in table \ref{table}. Point for point comparison was not possible as their original data was unavailable so the process of extracting it from the figures introduced a precision error in their results. Our cuboid volumes are consistently lower than theirs because we quantize our scene. For each experiment, unless the parameter is being varied, the baseline is 100 m, the focal length 15 mm, the pixel size 20 $\mu$m, as these were used in the earlier study \cite{fooladgar_geometrical_2013}. The uncertainty volume for an object 100 m away from the cameras was measured each time, except for the object distance experiment where this was increased up to 300 m. The vertical axes for fig \ref{fig_experiments} show the volume of the uncertainty region in meters cubed, and the horizontal axis the variable of each experiment: baseline, focal length, pixel size, object distance, $z$. The gridpoint spacing used to find the cuboid volume and polyhedron volume is $3$ per cm, this is further discussed in section \ref{sec:gridpoints}. \subsection{Error due to system parameters} Figure \ref{fig_baseline} shows the effect of baseline length, or camera separation, on uncertainty volume. The decrease in polyhedron volume with increasing baseline distance follows a power law of $V=0.2427b^{-1.008}$, where $V$ is the volume of the uncertainty region and $b$ is the baseline distance. Earlier authors reported a similar trend and the results of \cite{fooladgar_geometrical_2013} are plotted alongside ours for comparison. They attributed the decrease in uncertainty volume with increasing baseline distance to the viewing pixel being further from the sensor center. As the pixel viewing angles decrease the pyramid projections narrow, resulting in smaller intersection volumes, and our findings confirm this. For smaller baselines, the difference between polyhedron volume and cuboid volume is at its largest, and for larger baselines the difference is less marked. The cuboid volume calculation overestimates the localization error by almost two times at 5 m baseline, therefore for smaller baselines the polyhedron volume model would be more suitable. Figure \ref{fig_focal} shows the effect of focal length on error volume. The longer the focal length, the narrower the pyramid so the pyramid intersections are smaller in these cases. The decrease in polyhedron volume also follows a power law of $V=7.1298f^{-2.948}$, and the difference between the two models of error volume is greatest for smaller focal lengths. Figure \ref{fig_pixel} shows the effect of pixel size on error volume. The increase in polyhedron volume as a function of pixel size can be described with the following power law, $V=4\times10^{-7}k^{2.9253}$. The larger the pixel, the wider the pyramid cross section, so the uncertainty volume increases with increasing pixel size. \begin{table}[!t] \renewcommand{\arraystretch}{1.3} \caption{Root mean squared Error (RMSE) and median symmetric accuracy (MSA) of cuboid volumes obtained using our method compared with cuboid volumes obtained by Fooladgar et al.} \label{table} \centering \begin{IEEEeqnarraybox}[ \IEEEeqnarraystrutmode \IEEEeqnarraystrutsizeadd{3pt} {1pt} ]{.u/t/t/t/t.} \hline & Baseline & Focal Length & Pixel Size & Object Distance\\ \hline RMSE (m\textsuperscript{3}) & 0.001808 & 0.000196 & 0.00022 & 0.00343 \\ MSA (\%) & 7.58 & 3.07 & 10.47 & 2.30 \\ \hline \end{IEEEeqnarraybox} \end{table} \subsection{Error due to scene point position} Figure \ref{fig_object} shows the effect of object distance or increasing depth, $z$, on the error volume. The point to be imaged is 100 m away from the baseline midpoint (0, 0, 100), and the $z$ value is increased up to 300 m. The uncertainty volume increase with object distance follows a power law of $V=2 \times 10^{-11} z^{4.0321}$. The further away the object, the closer to the center of the sensor it is detected, and the wider the viewing pyramids, hence the larger the intersection volume. We now look beyond the $z$ axis to measure uncertainty volumes at different $x$ and $y$ positions within a plane perpendicular to this axis. Fig. \ref{fig_plane} shows the effect of the $x$ and $y$ coordinate on the cuboid error volume. At $z = 100$ m, a plane of scene points from -100 m to +100 m in $x$ and $y$ was generated, and the error volume for each point in this plane was calculated. In the $x$ direction the uncertainty volumes are lowest at the CCD center and increase as we move left or right in the plane. The cameras are situated at (50, 0, 0) and (-50, 0, 0) in m, and we observe a smaller increase in uncertainty volume for scene points beyond theses $x$ values. The error volume does not change with variation in the $y$ direction for points within $\pm 50$ m in $y$ position but it increases beyond these values. The extent of the same simulations in \cite{fooladgar_geometrical_2013} and \cite{wu_analysis_1998} was $\pm 50$ m in $x$ and $y$ rather than $\pm 100$ m. Our results closely match theirs for the same region and we show the trends in uncertainty volumes change beyond this region. We build on earlier studies by also examining how the uncertainty volumes change as a function of position in the other two perpendicular planes, $XZ$ and $YZ$. \begin{figure}[!t] \centering \includegraphics[width=3.5in, trim=120 25 70 60, clip]{plane_font \caption{Volume of cuboid uncertainty region versus object positions within the $XY$ plane at $z = 100\,m$.} \label{fig_plane} \end{figure} \begin{figure}[!t] \centering \input{Figures_and_Plots/cuboid_gridpoints.tex} \caption{Volume of cuboid uncertainty region versus baseline distance at different gridpoint spacings.} \label{fig_cuboid-gridpoints} \end{figure} Fig. 9 shows the cuboid and polyhedron uncertainty volumes as a function of scene point position within three perpendicular planes that meet at (0, 0, 100). The first of the three plots in fig \ref{fig_box-planes} shows the same data as fig. \ref{fig_plane}, displayed as a 2-D image. The uncertainty volumes of points within the other two perpendicular planes of the same dimensions are also shown, colorized to the same scale. The variations in uncertainty volumes within the $XY$ planes in fig. \ref{fig_plane} are dwarfed by changes in the $XZ$ and $YZ$ planes over the same distances. Fig 9b displays the same plots using the polyhedron volume instead of the box volume approximation. The colorbar shows that the scale of all these volumes is much smaller. The variation in the $XY$ plane the previous authors reported is only present when using the cuboid volume approximation. For the $XZ$ plane, both volumes increase with $Z$, and the polyhedron volume is a factor of 4 smaller than the cuboid volume. For the $YZ$ plane both models show an increase in uncertainty volume with $Z$ but there is an added $y$ component in cuboid volume approximation that is not apparent in the polyhedron model. \begin{figure*}[!t] \centering \subfloat[]{\inputTikZ{0.75}{Figures_and_Plots/cuboid.tex} \label{fig_box-planes}} \vfil \subfloat[]{\inputTikZ{0.75}{Figures_and_Plots/poly_3_planes_v.tex} \label{fig_real-planes} \caption{Volume of cuboid (a) and polyhedron (b) uncertainty region versus object positions within XY plane (left), XZ plane (middle), YZ plane (right)} \end{figure*} \subsection{Grid Point Spacing}\label{sec:gridpoints} The choice of how densely to generate the occupancy grid points strongly affects the calculated volume and the computation time. Here we perform the baseline experiment from the previous section with different grid point spacings ranging from 0.1 per cm to 3 per cm. Figure \ref{fig_cuboid-gridpoints} shows how as the number of scene points per cm is increased, the closer the results fit to the calculations by \cite{fooladgar_geometrical_2013} for the cuboid volume. The authors do not quantize their scene as we do in this method, so our cuboid volumes will never totally align but 3 points every cm at these baseline distances gives a visually close approximation and a total RMS error of uncertainty volumes of our cuboid model compared with the Fooladgar et al. model is 0.001808 $m^3$, shown in table 1. The comparison of our experiment results with theirs in terms of median symmetric accuracy shows that our inverse method produces similar results to their method. The same inverse method is used to calculate the polyhedron volume, so this suggests our polyhedron volumes are accurate. We use 3 grid points per cm for the experiments in this study unless stated otherwise. \section{Discussion}\label{sec:discussion} The cuboid volume always overestimates the localization error when compared to the polygon volume, which is unsurprising given the visual representation in figures \ref{fig_pyramids} and 3. In all four experiments, we show this difference increases at larger uncertainty volumes. In all cases, the volumes increase when the size of the pyramids projecting from each pixel increases. This happens at larger pixel sizes, because this increases the pyramid cross section, and smaller focal lengths, which affects the distance between the pyramid apex and the pixels. The volumes also increase in size when the detecting pixel is closer to the center of the image plane. Even though all pixels are the same size and regularly distributed, perspective projection means that the outer pixels subtend smaller angles than those in the center. Larger baselines and smaller distances from the camera give lower localization error because in coplanar stereo cameras the scene point will be detected by pixels further away from the image center. \begin{figure*}[!t] \centering \subfloat[]{\includegraphics[width=3.5in, trim=90 50 40 60, clip]{intersection_1 \label{fig_voxels_1}} \hfil \subfloat[]{\includegraphics[width=3.5in, trim=90 50 40 60, clip]{intersection_2 \label{fig_voxels_2}} \caption{Voxel plot of two intersections from fig. \ref{fig_plane}. Plot (a) shows an intersection from the center of the plane at $x=0$ m, $y=0$ m, Plot (b) shows an intersection from the corner at $x=-80$ m, $y=-80$ m. For visual clarity the gridpoints were generated at 1 per cm.} \label{fig_voxels} \end{figure*} We might conclude that in a real-world scenario when taking stereo images of an object to make an accurate 3-D model, that the cameras should be aimed to detect the object at the edges rather than the center of the image plane, in order to minimize quantization uncertainty. However, we should also consider that lens distortion is at its greatest at the edges of the image, and at its minimum at the image center. Lens distortion is more widely considered as a cause of localization error and has been studied extensively in this field. This quantization error model could be combined with lens distortion models in the future to yield more comprehensive localization error predictions for a system. Previous authors reported variations in uncertainty volume as a function of scene point distance in $x$, however, after recreating these results with the cuboid volume model (figure \ref{fig_box-planes}), we show that there is no such trend in the polyhedron model (figure \ref{fig_real-planes}). We conclude that this trend is an artefact caused by the cuboid approximation. Our results show that only depth, $z$, affects the volume of the uncertainty region. A demonstration of the limitations of the cuboid model is shown in fig. \ref{fig_voxels}, which shows voxel plots of two example intersections from the XY plane in fig. \ref{fig_plane}. The uncertainty volume in fig. \ref{fig_voxels_1}, from the center of the $XY$ plane, contains 2548 gridpoints, which is converted to a polyhedron volume of 0.002548 $m^{3}$ and a cuboid volume of 0.0042 $m^{3}$ using (\ref{eq:volume}). The uncertainty volume in fig.\ref{fig_voxels_2}, from a corner of the $XY$ plane, contains 2362 gridpoints, equal to a polyhedron volume of 0.002362 $m^{3}$ and a cuboid volume of 0.015 $m^{3}$. The nature of the two shapes means that despite having similar polyhedron volumes their cuboid volumes are different by an order of magnitude. Intersections at the center of the $XY$ plane are more closely aligned with the coordinate system axes and the further away from the center the intersections are, the more oblique they become. This means that calculating the cuboid volume from the maxima and minima in gridpoint coordinates can yield a poor fit and result in significant overestimation of uncertainty due to quantization. \section{Conclusion} Quantization error is not usually factored into error predictions alongside errors from stereo matching and calibration. Wu et al. and Fooladgar et al. modelled quantization error by projecting pyramids or cones into space to calculate the intersection region for a pair of pixels, approximated as an ellipsoid or cuboid. They showed that quantization can introduce significant uncertainties in object feature mapping, however, under the computational restrictions of the time, it was only possible to calculate it for one pair of matched pixels. Our method applies their principle in reverse by quantizing the scene and calculating which pixels see each scene point. This method has the advantage of yielding every possible quantization region for every potential correspondence in the system, for two or more camera views. Furthermore rather than calculating a cuboid approximation of the uncertainty volumes, we calculate the volume of the uncertainty polyhedron itself. We confirmed earlier author's models, and show the cuboid approximation to overestimate the uncertainty volume by at least a factor of two. We present our method as a way to make quantization errors more readily calculable and more precise as they do not need to be approximated. The advantage of this calculation is that it only needs to be performed once to determine all possible quantization errors for a camera system. Then for example, at the correspondence matching stage of 3-D from stereo, the polyhedral uncertainty volume or cuboid volume dimensions can be queried and saved for each set of matched pixels. Furthermore the triangulation stage is no longer necessary because the object point locations are already known for each pixel correspondence. This has potential applications in mobile robot navigation, as most occupancy grid mapping methods that use camera inputs need to generate disparity maps. Using our method, a robot with multiple cameras would only need to store and query a look up table to determine scene geometry. Our method also calculates the visual hull on a pixel by pixel basis, so could also be used to construct visual hulls of larger objects spanning. A limitation of this method is that it assumes a static camera system, such as a stereo pair of cameras on a robot. As soon as the spacings of the cameras change, such as a camera moving through a scene, a new look up table has to be calculated. Another application of precisely calculated error bounds is in visualization. If we choose to represent the scene as a point cloud rather than an occupancy grid, we can plot the intersection polygons instead of points. Rather than needing to quote a positional error figure for each point, the localization uncertainty is implicit in the shape, making this easier for a human to interpret. \ifCLASSOPTIONcaptionsoff \newpage \fi \bibliographystyle{IEEEtran}
{'timestamp': '2020-10-19T02:17:17', 'yymm': '2010', 'arxiv_id': '2010.08390', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08390'}
arxiv
\section{Introduction} The occurrence, or absence, of large flocks of birds is linked to factors such as population size, food abundance and food distribution and can therefore carry important information on the status of, and changes in, the environment \cite{Hemery1981_Thermographie,Moller2019_EcoEvol}. Mass concentrations of birds is also an important source of conflicts with humans. As an example, tens of millions of red-billed quelea \emph{Quelea quelea} are, due to their impact on farming, annually poisoned or blown up in Sub-Saharan Africa \cite{McWilliam2004_EnvCons}. Similarly, various blackbirds -- most notably the red-winged blackbird \emph{Agelaius phoeniceus} -- aggregate in huge flocks and are considered a major pest in North America \cite{Linz2017_Blackbirds}. The European starling \emph{Sturnus vulgaris}, one of only three bird species on the IUCN list of the world’s worst invasive species \cite{Lowe2000_IUCN}, is yet another interesting example. Starlings are considered a serious problem in many countries over several continents, causing, for example, damage on fruit and berry farming and spread of disease \cite{Feare1992_ProcVertPest,Homan2017_StarlingsUSA}. The bird species mentioned above are examples of birds that are reported to gather in millions. Such mass concentrations of birds are rare, and it is not more than around 50 of the worlds bird species that are reported to reach seven-digit numbers (see e.g. \citeA{Moller2019_EcoEvol}). As it is well known that counting large numbers of birds is extremely difficult, and since it matters if a bird count is 100 000 or 1 000 000 (a factor ten difference in potential crop damage or population size matters), it is well worth looking closer into how mass concentrations are counted and accounted for. This work takes a closer look at the brambling \emph{Fringilla montifringilla} and its mass appearances in Europe during beech mast years. The brambling is the species in Europe that appears in largest flocks and is thus an interesting case study for discussing number estimates. The work is the result of an attempt to put the mass concentration in southern Sweden during the 2019--2020 winter into an international and historical perspective. After a description of the 2019--2020 events, a literature review is presented and counting methods discussed. The focus is on number estimation and roost density. For other aspects of the fascinating phenomenon of communal roosting of bramblings, the reader is referred to the existing literature. There are numerous ambitious studies of the topic, covering everything from relation to food abundance and snow cover \cite{JenniNeuschultz1985_OrnitBeob,Jenni1987_OrnisScand}, origin of birds and ring recoveries \cite{Schifferli1953_OrnitBeob,Jenni1982_OrnitBeob,Kjellen1993_Anser,Browne2003_RingMigr}, roost microclimate and communal roosting aspects \cite{Jenni1991_OrnisScand,Jenni1993_Ibis,Khil2011_Limicola,Arizaga2012_RingMigr,Zabala2012_ActaOrni} and foraging patterns and energy needs \cite{Granvik1916_FaunaFlora,Hemery1975_CrAcadSc,Hemery1976_LeTerre,Francois1978_Falco,NardinBrauchle1979,Nardin1985_NosOiseaux,Jenni1987_Ardea,Kjellen1993_Anser,Khil2011_Limicola} to behaviour of raptors in the vicinity of roosts \cite{Jenni1993_Ibis,Khil2011_Limicola,Zuberogoitia2012_JRaptRes}. \section{Brambling ecology and behaviour} The brambling \emph{Fringilla montifringilla} is one of the most numerous birds in the world. It breeds dispersed in northern forests of Europe and Asia, with a breeding range stretching all the way from Norway to eastern Siberia. The global population, which seems to be under moderate decline, is estimated to 100--200 million pairs, while the European population is limited to around 15--25 million breeding pairs (Birdlife International 2020). The species is highly migratory, but irruptive (i.e. exhibiting significant variation in migration patterns, see e.g. \cite{Newton2006_IrruptiveMigr,Newton2012_JOrnit}). While it is said to mainly migrate during night \cite{Newton1972_Finches}, some 100 000 bramblings are annually counted in Falsterbo, while leaving Sweden in daylight (on average almost one million finches are counted, but chaffinch \emph{Fringilla coelebs} dominates and typically 5--25\% are bramblings, \citeA{Kjellen2019_FiSk2018} and Kjell\'{e}n 2020, personal communication). While few ornithologists appear to have heard bramblings during the night, data from lighthouse suggests that the brambling indeed is a nocturnal migrant. Between 1886 and 1939, in an impressive and persevering Danish study, 1 568 bramblings were killed by and collected at Danish lighthouses, to be compared with e.g. 532 chaffinches \emph{Fringilla coelebs} and 1 569 willow warblers \emph{Phylloscopus trochilus} \cite{Hansen1954_Fyrfall}. \citeA{Alerstam1993_BirdMigration} has also noted bramblings leaving Sweden, heading out over the Baltic sea, at dusk. In essence, the European bramblings moves towards the southwest until it finds satisfactory food resources \cite{Jenni1987_OrnisScand}. Many end up in the vast beech forests of Central Europe, but the migration patterns vary significantly from year to year. In Sweden, an often mentioned example is an individual ringed when wintering in Halland (Southwest Sweden) in January 1965, just two winters after to be recovered in Caucasus \cite{BRC2020,Kjellen1993_Anser}. Other ringing recovery examples include a bird ringed in Blekinge (Southeast Sweden) in January 1986, the year after wintering in southwest France where it was found dead, and a bird ringed in Sm{\aa}land (South Sweden) in January 1955 later being killed in Spain in November the same year \cite{BRC2020}. Swiss ring recoveries shows that central Europe is also reached by bramblings with origin east of the Urals \cite{Jenni1982_OrnitBeob}. This nomadic character is considered to be a reason why the species, despite its wide breeding range, is monotypic. When it comes to food, the brambling is an omnivore, although rather specialized. During breeding, bramblings have been found to rely on larvae of the Autumnal Moth (Epirrita autumnata), and its breeding success correlates with the strong cyclical fluctuations of this moth species \cite{Lindstrom2005_Oikos,Newton2007_MigrEcol}. During winters, a strong inclination for communal roosting (cf. \citeA{Beauchamp1999_BehavEcol} makes them responsible, albeit sporadically, for one of most spectacular mass concentrations of animals in Europe. Nuts of the European beech \emph{Fagus sylvatica} is their primary winter food and during beech mast years the abundance of food allows them to aggregate and form roosts of millions of birds (see e.g. \citeA{Jenni1987_OrnisScand}). The birds typically settle in coniferous forest sections in the vicinity of large beech forests. Interestingly, in a limited period of time 1960--1980, also corn fields in France played an important role, see \ref{subsec:corn_districts} and e.g. \citeA{Hemery1975_CrAcadSc} and \citeA{Dubois2008_BirdsFrance}. The same patches can be used for months if food supplies and snow coverage allow. The distribution of beech in Europe is shown in \ref{fig:BeechMap}, giving a rough indication of where European bramblings can be expected to winter in large numbers. \begin{figure} \centering \includegraphics[width=17cm]{FIG1_BeechMap.jpg} \caption{Distribution map of Beech \emph{Fagus sylvatica} in Europe, adapted from \protect\citeA{EUFORGEN2009}. As beech nuts is the primary winter food of bramblings, the map indicates where they can be expected to winter in large numbers. Winter roosts that has been described in detail, constituting the core of this study, are marked (cf. Table \ref{tab:roost_table}). Note that Oriental beech \emph{Fagus orientalis}, which can be found in e.g. Turkey and the Caucasus, is not included in this map.}\label{fig:BeechMap} \end{figure} Historically, the appearance of millions of bramblings was often seen as a bad omen, as sign war, starvation or pest \cite{Holmgren1866,Granvik1916_FaunaFlora,Haikos1950_OrnitBeob}. Today, it is more of an attraction for nature lovers. However, it is worth keeping in mind that species for which a significant part of the population accumulates in limited areas are very vulnerable to, for example, hunting and poisoning. A contemporary example of this kind of vulnerability is the dramatic decline of the yellow-breasted bunting \emph{Emberiza aureola}. Once superabundant, rampant trapping has brought the population of this species down to around 10\% what is was only a few decades ago \cite{Kamp2015_ConsBiol}. A single brambling requires some 25--30 kcal per day \cite{Hemery1975_CrAcadSc,Hemery1976_LeTerre,Kjellen1993_Anser}, corresponding to around 8 g of beech seeds (around 40 seeds, or around a fourth of their body weight). This is based on published energy values for tree-seeds: the nutritive material (seed excluding coat) of a seed carries 7 kcal per g dry weight and the dry weight of nutritive material per seed is around 0.12 g \cite{Grodzinski1970_TreeSeeds,Nilsson1979_Ibis}, resulting in around 0.84 kcal, or 3.5 kJ, per seed. Assuming 83\% energy utilization \cite{Kjellen1993_Anser}, this means that a single brambling requires some 40 seeds per day (27.5 kcal/day / (83\%$\cdot$0.84 kcal/seed) $\approx$ 40 seeds/day). Since the fresh weight of a whole seed is around 0.2 g, this corresponds to 8 g. These energy considerations indicate that one million bramblings consume on the order of 8 tons of beech seeds per day, summing up to around 1 000 tons for a four-month wintering stay. For a mast year, the beech nut production can be well above 1 ton/ha \cite{Kjellen1993_Anser,Oevergaard2007_FaktaSkog,Overgaard2010_PhDThesis}. Given than bramblings can fly up to at least 40 km from a winter roost \cite{Muehlethaler1952_OrnitBeob,Hemery1975a_CrAcadSc,Francois1978_Falco,Jenni1984_PhDThesis,Chalverat2003_SchwForst,Khil2011_Limicola}, the accessible area is around 500 000 ha. The fraction of beech forest in that area can thus even be relatively low (e.g. even below a 1\textperthousand level) and still support millions of bramblings for several months. An interesting aspect of mass roosting is the massive amount of faeces deposited in the roost area. Not only does it produce a nasty odour, it also affects the ecosystem \cite{Chalverat2003_SchwForst}. In 2000, as an example, a new species of fungi was found in the aftermath of a huge brambling roost and was named \emph{Pseudombrophila stercofringilla} after the bird excrements \cite{Dougoud2001_MycoHelv}. Still, the impact of brambling roosts on forest ecosystems should be small compared to the how the enormous passenger pigeon \emph{Ectopistes migratorius} population -- a species also specialised on tree-seeds such as beech mast affected forest ecology in North America (see e.g. \citeA{Bucher1992_CurrentOrn} and \citeA{Ellsworth2003_ConsBiol}). In general, the knowledge of ecological functions of birds is far from complete \cite{Sekercioglu2006_TrendsEcoEvol} and the role bramblings have played in European beech forests, if any, is not clear. \section{The mass concentration in Sweden 2019--2020}\label{sec:the_mass_conc_in_Sweden} After an extremely warm and dry summer 2018 and good conditions for beech flowering during 2019, the beech seed crop of 2019 turned out to be enormous. Although the quantitative beech mast counts, operated by Swedish University of Agricultural Sciences, unfortunately was discontinued a few years ago, there is no doubt that 2019 was an extreme mast year. Rough counting, by the author, indicated that a single large beech tree could carry on the order of 100 000 shells (cupule), corresponding to 200 000 seeds. Assuming that one hectare of beech forest is equivalent of 100 large trees, the seed production could be on the order of 20 million per hectare (i.e. around 4 tons/ha). As a comparison, highest local beech mast production during the beech mast counting 1989--2006 amounted to 14 million/ha \cite{Oevergaard2007_FaktaSkog,Oevergaard2007_Forestry,Overgaard2010_PhDThesis}. Furthermore, Prof. Sven Nilsson has conducted semi-quantitative monitoring of beech mast in Sweden since 1971, ranking the crop from 0 (no crop) to 5 (massive crop), and reports that there has not been a year in this series with as much beech mast as 2019 (Nilsson 2020, personal communication). Without standardized quantitative data, it is however difficult to know exactly how the 2019 mast year compares to other mast years. In addition to the rich beech crop, it is also interesting to note that the brambling seems to have had a good breeding season in Sweden. The LUVRE project (www.luvre.lu.se), monitoring birds in the northern birch forests since the 1960s, reports their highest number of ringed juvenile bramblings since the ringing start in 1983, and the third highest number in terms per juveniles per adult ({\AA}ke Lindstr\"{o}m 2020, personal communication). That masses of Bramblings this year ended their migration in southern Sweden, taking advantage of the food abundance, became clear in November--December. Large flocks were reported from various areas of Scania (Sk{\aa}ne). A massive afternoon movement over the city of B{\aa}stad on December 22, witnessed by the author and Stefan Svensson (cf. Fig. \ref{fig:Bastad_December}), involved millions of birds and indicated that a roost was to be found in the area. The roost was found by the author on January 4 \cite{Svensson2020_Anser} and was located on the south-facing slopes of the Hallands{\aa}s Horst, just north of lake R\"{o}ssj\"{o}n. Photos and moviews can be found at \url{https://www.flickr.com/photos/tomas_s/albums/72157712566702823}. The roost area was estimated to 5.6 ha, via night time sounds in combination with visual inspection of excrement layers and their boundaries (droppings) together with areal analysis using map tools supplied by Lantm{\"a}teriet (www.lantmateriet.se). The roost consisted of, respectively, approximately 2.6 ha of 31 year old and 3.0 ha of 39 year old plantations of European spruce \emph{Picea abies}. The younger parts were dense with only around 2 m between tress while the older parts where thinned out and had 4--5 m distance between trees. Tree height ranged from 15 to 25 meters. Fig. \ref{fig:EveningView} shows a view from the roost perimeter \begin{figure} \centering \includegraphics[width=17cm]{FIG2_Roost_EveningView.jpg} \caption{Evening at the roost at lake R\"{o}ssj\"{o}n, Sweden on 4 February 2020. View towards the northern side of the younger section.}\label{fig:EveningView} \end{figure} Employing a simple square grid model on these tree spacings, and reducing the count by 10\% to account for small opening and forest roads, this results in the following rough tree count estimate: \begin{equation}\label{eq:tree_estimate} N_{trees}=0.9\cdot(2.6\cdot(100/2)^2+3.0\cdot(100/4.5)^2 )\, \approx 7\,0 00\,\textrm{trees} \end{equation} A map of the roost area is shown in \ref{fig:Roost_area}. \begin{figure} \centering \includegraphics[width=17cm]{FIG3_Roost_area.png} \caption{Annotated map showing the 5.6 ha roost area that appeared to be used simultaneously in early January 2020 (from Google Maps). The area was demarcated based on droppings and evening sound.}\label{fig:Roost_area} \end{figure} On-site counting at the 2019--2020 site was very difficult, as it was impossible to get a good overview of the roost. Monitoring morning lifts or evening fly-in, was thus not easily done. The best number estimate is most likely that from B{\aa}stad on December 22, assuming that all of the birds passing there was headed for the same roost and that most of the roost had the same whereabouts this day. Despite being witnessed by rather experienced migration counters, the flow over B{\aa}stad was overwhelming. From analysis of photos, the front of Bramblings was over one kilometre wide at its peak intensity (determined via photographs). \begin{figure} \centering \includegraphics[width=17cm]{FIG4_8260ex_Bastad.jpg} \caption{Distant stream of bramblings when passing B{\aa}stad 22 December 2020. The photo was taken with a Canon EOS7D with EF100--400 mm f/4.5--5.6L IS II USM at its maximum focal length, giving a 3.23$^\circ$ horizontal field-of-view. From the size of the birds (0.15 m physically, and around 15 pixels on the 5427$\times$3648 pixel sensor), this stream is estimated to be around $0.15/\tan(15\textrm{px}/5427\textrm{px}\cdot3.23^\circ)\approx$ 1 km away. By tedious manual marking of the individual birds, it is known that the photo contains around 8260 birds. The camera field-of-view at 1 km is around 56 m. Radar measurements has shown that bramblings fly at 15 m/s \protect\cite{Alerstam2007_PLoS} and after accounting for around 2 m/s head wind (as reported by the closest wind station), the 8 260 birds should pass the field of view in around $56/13\approx 4.3$ s. This corresponds to an intensity of around 1 900 birds per second.}\label{fig:Bastad_December} \end{figure} Thousands of bramblings was in the binocular field of view and passed within a matter of seconds. A number estimate was thus reached only after analysis based on timing and photographs. Our field notes state that the movement occurred during around 5 minutes around 13:40, and then during 45 minutes from 14:55 to 15:40 (it was almost dark in the end, so the Bramblings seem to have been late this day -- the sunset was at 15:33). Analysis of photo of a distant streak (where birds are caught from the side, simplifying analysis) showed that 1 900 birds passed per second (1 900 s$^{-1}$, see Fig. \ref{fig:Bastad_December} and its caption for details). At the peak intensity we believe that the total intensity should be two to three times of that. An analysis of a photo taken at a time where we considered the migration as "dead", revealed an intensity of 300 s$^{-1}$ (see Fig. \ref{fig:Bastad_December2}). \begin{figure} \centering \includegraphics[width=17cm]{FIG5_Almost_dead.jpg} \caption{Photo taken at a time where the movement was considered to be nearly dead (B{\aa}stad 22 December 2020). The photo was taken 15:33, but the intensity increased again after this dip. The movement ended at around 15:40). Excluding a faint stream in the background, the photo contains around 1575 birds (manually marked) flying at a distance of around 1.2 km. The corresponding instantaneous intensity is around 300 birds per second.}\label{fig:Bastad_December2} \end{figure} The numbers are breath-taking. In Falsterbo, with its annual standardised migration counts, finches are typically counted in a few thousands per minute on a good day. We (the author and Stefan Svensson) judged that the most intense period lasted around 20 minutes, and that the total amount of birds could be calculated from 30 minutes with 1000 s$^{-1}$ and 20 minutes with 5 000 s$^{-1}$, resulting in 7.8 million birds. As a lower bound, and since field notes are imperfect and we did not take photos systematically throughout the Brambling passage, we propose to use 40 minutes as to total duration and restricting the intense period to 10 minutes and 4000 s$^{-1}$. This approximate lower bound amounts to 4.2 million birds. As an upper bound, maybe 30 minutes with 1500 s$^{-1}$ and 20 minutes with 6 000 s$^{-1}$ is reasonable, summing up to 9.9 million. A reasonable, albeit rough, range for the number of Bramblings involved in this movement is thus 4--10 million. As a comparison, when on-site on January 4th, the author together with Nils Kjell\'{e}n and Ola Ellestr\"om very roughly estimated that we witnessed, visible from our side of the roost area, a fly-in intensity of around 2000 s$^{-1}$ during 40 minutes, summing up to around 5 million birds. The sound and visual experience was stunning. Some efforts were also made to estimate the number of birds roosting per tree, but no firm conclusion could be reached. Infrared photographs indicate that ten birds easily can sit on a single twig during the night (see Fig. \ref{fig:IR_photo}), and observations and photographs taken at dusk indicate that on the order of 1 000 birds can fit in a single spruce tree. Still, the number of birds per tree during the night remains an open question and more efforts are needed to elucidate this matter. As movements seems occur after dark, and since the bramblings are disturbed when approached, installation of infrared cameras in the roost may be an interesting approach. \begin{figure} \centering \includegraphics[width=12cm]{FIG6_IR_photo.jpg} \caption{Thermal photograph taken with a hand-held FLIR Scout TS24 Pro. The photo was taken just outside the roost perimeter in the dark. It was impossible to walk further without causing chaos. The slightest sound or light increased the chattering and made many birds take off with the sound of storm winds.}\label{fig:IR_photo} \end{figure} Although bramblings winter in Sweden regularly, few Brambling winter roosts have been found. Prior to the roost described above, only three roosts have been located and described in detail \cite{Granvik1916_FaunaFlora,Mathiasson1960_SvNat,Kjellen1993_Anser}. One of these roosts was found 1993 very close to the location described above: just north of the neighboring lake V{\"a}stersj{\"o}n, on the same south-facing slopes \cite{Kjellen1993_Anser}. Another roost was found was found some 36 km south from these locations during the 1915--1916 winter \cite{Granvik1916_FaunaFlora}. This part of Scania has vast beech forests and is relatively sparsely populated. It is therefore likely that even rather large roost can be overlooked. As an example, during the research for this article, the author stumbled across a YouTube-video filmed by fishermen in February 2012 showing enormous flocks of bramblings flying over lake V\"astersj\"on \cite{Hafstrom2012_YouTube}. No roost was found this year. There are also years when ornithologists have reported million level flocks in various parts in southern Sweden, still without any roosts having been located. Given the climate change that is upon us, it can be expected that bramblings will winter in southern Sweden in increasing numbers. The winter 2019--2020 was in fact, according to standard meteorological definitions, not a winter season at all and the average temperature was four degrees above normal \cite{SMHI2020}. Scania is rarely covered in snow nowadays and the frequency of beech mast years have increased in recent years \cite{Oevergaard2007_Forestry}, although long-term variability also must be considered \cite{Drobyshev2014_AgriForMet}. \section{A review of mass concentration reports} It is sometimes argued that the brambling is the bird that gathers in the largest numbers of all (Newton 1998). A better guess is perhaps the red-billed quelea \emph{Quelea quelea} which is reported to occur in numbers up to 100 million \cite{Hancock2015_BirdsBotswana}. There are also several other bird species are potential “records holders” (see e.g. \citeA{Moller2019_EcoEvol}), but given the difficulties in bird counting, it appears very difficult to get such a question settled. If including extinct species, the passenger pigeon \emph{Ectopistes migratorius} will make settlement easier: the species has even been claimed to occur in billion level flocks (a sad but important reminder that what is common today may be go extinct more rapidly than we expect, cf. \citeA{Murray2017_Science}). Turning back to bramblings, gatherings of millions are far from being reported annually. This is expected, since very large roosts appear to form only during beech mast years. Throughout the years, however, numerous accounts of the phenomenon are available thanks to authors from several European countries. Unfortunately, many reports neither provide details on how numbers were estimated, nor details regarding roost area. Many authors express how difficult it was to count properly and there is in many cases massive disagreements regarding the actual number of birds involved. This review aims at elucidating this matter and the main focus is therefore on reports that gives details on number estimations and roost area. \subsection{Approaches for number estimation} Three different approaches to number estimation was encountered during this work: \begin{itemize} \item[A.] Stream intensity and time, $N = I\cdot T$ \item[B.] Flock volume and density, $N = B\cdot H\cdot L\cdot \rho = B\cdot H\cdot v\cdot T\cdot \rho$ \item[C.] Tree count and birds per tree, $N = N_{\textrm{trees}} * N_{\textrm{per\quad tree}}$ \end{itemize} In method A, the number of birds $N$ is reached by estimating the intensity of birds, $I$, passing an observer (birds/s) in combination with time duration $T$ of the passage of that intensity (since intensity will fluctuate, new estimates should ideally be done continuously). The intensity can either be estimated directly (instantaneously) by the observer, or it can be done afterwards via analysis of photographs. Method B, on the other hand, focusses on flock volume (width $W$, height $H$ and length $L$) and bird density $\rho$ (birds/m$^{3}$), where flock length is reached by assuming a certain ground speed $v$. Many works assume bramblings fly at 60 km/h $\approx$ 16.7 m/s, while radar measurements indicate that their ground speed is 15 m/s $=$ 54 km/h \cite{Alerstam2007_PLoS}. This inherent overestimation of 10\% should of course be avoided, even though it in most cases will be negligible compared to other uncertainties. Method C is very different: instead of counting flying birds, the focus is on roost parameters. The number is reached by multiplying the number of trees in the roost by the average number of birds per tree. Making any general statement on the accuracy of the different methods, and how they compare, is difficult since it depends on how the individual parameters are estimated. However, as various studies are discussed in subsequent sections, it will be argued that choosing to go via flock volume and density should be avoided. In many works, width and height in method B is set without proper motivation (keep in mind that difficulty of estimating distances by eye is widely recognised). In addition, there is far from any agreement on the average bird density in streams of bramblings. In fact, it should be expected that this varies significantly from roost to roost, and even from day to day at a single roost (depending on e.g. weather and foraging patterns). This means that method B is most likely far more error-prone than other methods. If width and height is estimated from photos (from size variations of birds in the picture, see Fig. \ref{fig:density} for an example), method B can become more accurate, albeit at the same time essentially turning into a complicated version of method A. In the future, new approaches may help in reaching better number estimates. Airborne thermography was proposed by already 40 years ago \cite{Hemery1981_Thermographie}, and with the increasing availability of infrared and thermal cameras (or even normal video cameras) roosts will likely be studied in more detail in the future. Approaches based on quantitative monitoring of sound or droppings is also conceivable. In addition, increasing availability of counting software, for example based on artificial intelligence, will simplify counting based on films or photographs. \subsection{Reports with details on number and roost area} Reports that provide details on number and roost areas are listed and briefly summarised and commented a in Table \ref{tab:roost_table} . The spread in reported numbers and roost areas are significant, and both number estimation and roost area definitions seem to vary greatly (cf. Fig. \ref{fig:scatterplot}). When disregarding works that seem to have a too wide definition of roost area, the roost density (birds per area) varies from some 0.3 million/ha all the way up to 7.5 million/ha. This corresponds to a factor 25 between lowest and highest estimate of bird per roost area, a spread that motivated further scrutiny. It turns out to be very difficult to condense this material into any simple rule of thumb, but based on careful reading of the material, I come to the conclusion that the number of birds per roost area is on the order of one million/ha. There are a few works where much larger roost densities are reported, but a closer look reveals the underlying numbers lack adequate motivation. There are also some reports where densities are much lower \cite{Fulin2017_Tichodroma,Kestenholz1993_OrnitBeob}, but this is likely related to overestimation of actual roost area used during the night (see comments in Table \ref{tab:roost_table} ). In the end, however, it should be expected that the density per roost area will vary significantly with, for example, age, size and density of trees, temperature, local variation of microclimate, total suitable area in relation to the number of bramblings accumulated during the winter etc. As an example, the large Slovenian roost in 2018--2019 comprised large, older trees (Miheli{\v{c}} 2020, personal communication) while the Swiss roost in 1946--1947 was situation in an area with young trees, most below 8 m in height \cite{Gueniat1948_OrnitBeob}. It should not be expected that the birds roost will have similar densities when the vegetation can differ that much. \pagebreak \begin{center} \singlespacing \begin{longtable}{p{2.5cm} p{1.5cm} p{1cm} p{6.7cm} p{3.1cm} } \caption{List of studies that provide estimates of both number of birds and roost area. It should be noted that it roost area is most likely defined and estimated in very different manners. Studies that include a roost map are marked with an asterix (*), and a second asterix is added if the work also explicitly states that this area was demarcated based on excrement layers. The spread in estimates of number of birds and roost area is visualized in Fig. \ref{fig:scatterplot}}\label{tab:roost_table} \\ \hline Location \newline Year & Roost area & Count method & Number estimate and remarks & Reference \\ \hline K{\aa}ger{\"o}d \newline Sk{\aa}ne \newline Sweden \newline 1915--1916 & 0.5--1 ha & ? & 5.4 million, based on 45 min fly-in at a presumed intensity of 2000 s$^{-1}$ (without further motivation). The roost area is stated to be \emph{n{\aa}got tunnland} in Swedish, i.e. around one barrel of land (0.5 ha). & Granvik, 1916 \\ Porrentruy \newline Ajoie \newline Switzerland \newline 1946--1947 & 10.5 ha** & B & 11--16 million, based on 45 min morning lift-off in a stream 100 m wide and 5--7 m high, a ground speed of 60 km/h and 0.512 birds/m$^3$ (corresponding to an average intensity of 4000--6000 s$^{-1}$ ). & Gu{\'e}niat, 1948 \\ H{\"u}nibach \newline Thun \newline Switzerland \newline 1950--1951 & 12.6 ha* \newline (2$\times$6.8) & B & 72 million, based on 45 min fly-in in a 200 m wide and 4 m high stream, a ground speed of 60 km/h and 1 bird/m$^3$, thereafter doubled since there were two similar adjacent roost areas (corresponding to an intensity of 13 300 s$^{-1}$ per roost). Other assessors propose far lower numbers \shortcite{JenniNeuschultz1985_OrnitBeob}. & M{\"u}hlethaler, 1952 \newline Schifferli, 1953\\ Pau \newline Pyr{\'e}n{\'e}es-Atl. \newline France \newline 1964--1965 & 10--13 ha & ? & 15 million stated without further details. & Alberny, 1965\\ Etobon \newline Haute-Sa\^{o}ne \newline France \newline 1977--1978 & 16.1 ha & B (A) & 121 or 12 million, based on two different calculations. The lower number is based on an analysis of a photo with 5 565 birds over a width of 32 m in combination with 70 min fly-in at 60km/h (i.e. 2 900 s$^{-1}$). The larger (unreasonable) number, which is the one stated in the conclusion, is reached after arguing that the stream was 250 m wide and 50 m high and contained 0.138 birds/m$^{3}$ (i.e. 29 000 s$^{-1}$). & Nardin, 1979 \\ Magden \newline Switzerland \newline 1990--1991 & 5 km$^2$ \newline (500 ha) & ? & 2--3 million, stated without any further detail. Compared to other roosts, the area appears to be unreasonably large. & Kestenholz, 1993 \\ Frick \newline Switzerland \newline 1992--1993 & 0.5 km$^2$ \newline (50 ha) & ? & 2--3 million, stated without any further detail. Compared to other roosts, the area appears to be unreasonably large. & Kestenholz, 1993 \\ V\"{a}stersj\"{o}n \newline Sk{\aa}ne \newline Sweden 1992--1993 & 7.5 ha & C & 2 million, stated as a minimum based on around 7 500 trees and 200--500 birds per tree. Large number of dead and dying birds at the site. A similar number was reached in a fly-in count \shortcite{Lithner1995_FaglarNV}. & Kjell{\'e}n, 1993 \\ Fontenais \newline Ajoie \newline Switzerland \newline 2001--2002 & 10 ha** & ? & 10--12 million. Not exactly clear how this span was inferred. The estimation was based on a 32 min fly-in of a stream estimated to be 50 m wide, 15 m high and moving at 60 km/h. An intensity of 5000 s$^{-1}$ is stated as a minimum. The given 10--12 million range would correspond to calculation on the stream estimate and using 0.4--0.5 birds/m$^3$. Area description and map not in perfect agreement. & Chalverat, 2003 \\ Gelnica \newline Slovakia \newline 2008--2009 & 25--30 ha & A & 1.5--3.5 million, based on photo analysis. Roost area not given in the article but from Fulin (2020) in personal communication. Compared to other roosts, this estimate seems unreasonably large (but Fulin also mentioned that the area included several hectares of lake). & Fulin, 2017 \newline Fulin, 2020 \\ L\"{o}dersdorf \newline Austria \newline 2008--2009 & 2.26 ha & A & 4--5 million, based on photo analysis on several locations around the roost. & Khil, 2011 \\ Barazar \newline Basque \newline Spain \newline 2010--2011 & 3--5 ha & ? & 0.9 million. Droppings very unevenly distributed in the 50 ha large area mention in the article. Actual roost much smaller, and limited to patches of Lawson cypress (\emph{Chamaecyparis lawsoniana}), but not discussed explicity. In personal communication, Zabala (2020) guessed that perhaps 3--5 ha may have been used for actual roosting and that the number may have been in the span 0.7--12 million birds. & Zabala, 2012 \newline Zabala, 2020 \\ Klenovec \newline Slovakia \newline 2016--2017 & 40 ha & A & 0.5 million, based on photo analysis. Compared to other roost, the area seems unreasonably large. & Fulin, 2017 \\ Velika Preska \newline Slovenia \newline 2018--2019 & 5 ha & A & 5 million, based on photo analysis. Series of photos were taken during morning lift-offs (ground speed estimated by measuring how long it took for birds to pass the camera field of view, done by following individual birds and marking start and stop times using a voice recording). In personal communication Miheli{\v{c}} (2020) states that the roost area may have been up to around 9 ha. & \shortciteNP{Tout2019_RareBirdAlert} \newline Miheli{\v{c}}, 2020 \\ Kliplev \newline Denmark \newline 2019--2020 & 1.3 ha** & ? & 0.2--1.2 millions. Various number estimates from several observers, typically based on estimates of volume and bird density of flocks flying over the roost area. Roost area well covered by excrements measured to 1.3 ha on February 2 (Hansen, DOF-basen 2020), and in the Facebook forum “Feltornitologen” there is a map showing marking a roost area comprising of 2--2.5 ha (Martinek 2020). & \shortciteNP{DOFbasen2020_Bergfink} \newline Feltornitologen, 2020 \\ R\"{o}ssj\"{o}n \newline Sk{\aa}ne \newline Sweden \newline 2019--2020 & 5.7 ha** & A & 4--10 million based on photo analysis from a fly-in around 20 km from the roost. More details in Section \ref{sec:the_mass_conc_in_Sweden}. & This study, 2020 \\ \hline \end{longtable} \end{center} \begin{figure} \centering \includegraphics[width=17cm]{FIG7_Scatterplot.png} \caption{Scatterplot in logarithmic scale showing the variability in the data from Table \ref{tab:roost_table}. The four datapoints with roost area above 20 ha (Gelnica, Klenovec, Frick and Magden) are, in the author's opinion, obivous cases where the roost area has been significantly overestimated. Similarly, the number estimates for the roosts in K{\aa}ger{\"o}d, Thun and Etobon lack solid motivation and is in the present work argued to be the result of overestimations.}\label{fig:scatterplot} \end{figure} \subsection{Regarding the alleged 70 million roost in Thun 1950--1951} The famous and frequently recited 72 million roost from Thun, Switzerland 1950--1951 \cite{Muehlethaler1952_OrnitBeob}, often recited as 70 million, deserves a closer look. The number comes from a doubling of an estimate of birds arriving to one of two adjacent roost areas separated by around 300 m. The stream of birds was estimated to be 200 m wide and 4 m high, and the duration of the fly-in was 45 min. Assuming a ground speed of 60 km/h, the length of the stream was estimated to 45 000 m. M\"{u}hlethaler believes that 1 bird/m$^3$ (1 m$^{-3}$) is a reasonable lower limit for the bird density and thus reach 200 m $\cdot$ 4 m $\cdot$ 45 000 $\cdot$ 1 birds/m$^3$ = 36 million birds. This corresponds to an average intensity of 13 000 birds per second, per roost. Along with some 30 million birds in other parts of Switzerland this winter, this roughly corresponds to the complete European post-breeding population. Although this number estimate received some support from \citeA{Schifferli1953_OrnitBeob}, it has been rejected by others. Lukas Jenni, most likely the ornithologist who has spent most time studying the winter habits of bramblings in Europe, argues that the estimate even may be more than a factor ten too high \cite{Jenni1984_PhDThesis,JenniNeuschultz1985_OrnitBeob}. The main objection is that the bird density is overestimated, and that it is very difficult to accurately determine width and height of a bird stream. While M\"{u}hlethaler suggested that a flock density of 1 m$^{-3}$ should be an underestimation, Jenni argues that 0.04--0.1 m$^{-3}$ is more reasonable which would bring down the number from 72 million to 2.8--7 million. Jenni refers to that stereo photography on brambling flocks during autumn migration exhibited density in the 0.05--0.7 m$^{-3}$ range, and that \citeA{NardinBrauchle1979} in their analysis of photographs estimated density to around 0.1 m$^{-3}$ in dense regions, and 0.04 m$^{-3}$ on average. The author of the present work, however, finds the analysis of Nardin \& Brauchle rather confusing and suspect that the range 0.04--0.1 m-3 underestimates how dense bramblings can fly at the roost. Jenni recites that measurements of density during autumn migration resulted in values up to 0.7 m$^{-3}$, and my personal experience is that the bramblings sometimes flew denser in connection to the winter roost than what the do, for example, during autumn migration in Falsterbo (Sweden). To evaluate this further, I evaluated two photos from occasions at the Swedish 2019--2020 roost where I found the bramblings to fly particularly dense. In these photos, the width of the stream was estimated from the variation in size (in pixels) of the photographed birds. The two photos were rather different in character (one photo of a smaller and well-defined flock, and one capturing part of a longer stream). The resulting density estimate was in both cases 1--3 m$^{-3}$ (details of this analysis, for one of the photos, is found in Fig. \ref{fig:density}). It is of course purely coincidental that the density estimates ended up this close together, but it still shows that bramblings can fly much denser that 0.04--0.1 m$^{-3}$. \citeA{Schifferli1953_OrnitBeob} made a similar exercise: he studied photos of a stream, taken from below, somewhat arbitrarily assumed a stream height of 4 m and counted 87 finches in 20 m$^2$. This results in a density of 1.1 m$^{-3}$. Having this said, based on observations at the Swedish roost, I would still say that bramblings not always fly this dense. \begin{figure} \centering \includegraphics[width=17cm]{FIG8_Bergfink_1217ex.jpg} \caption{Flock density analysis example. The photo contains around 1 217 bramblings (manually marked) and is taken with a 3.23$^\circ$ field-of-view lens (Canon EOS7D with EF100--400 mm f/4.5--5.6L IS II USM at its maximum focal length). Bramblings are around 15 cm long and occupy in the range of 68--80 pixels, which corresponds to a distance range of 182--214 m. Since we have neglected length variations, this range should serve as an upper limit of the flock width (assuming a 10\% size difference from the smallest to the largest bird, one could argue that the flock width could be as low as around 10--15 m). The stream is around 3 m high, and the length captured by the photo is around 11.2 m. An lower limit for the bird density $\rho$ is reached when using the upper width estimate: $\rho_{min}=1217 / (3\times32\times 11.2 \approx 1.1\,\textrm{m}^{-3})$. With size variations in mind, the density could be as high as 3 m$^{-3}$. While this shows that bramblings can fly much denser than e.g. 0.1 m$^{-3}$, it should be noted that they often flew much less dense than this. In fact, the photo shown was taken when the bramblings flew particularly dense (at the roost site, 14 January). For reference, the flock length captured here is around 11 m. Assuming that the birds fly at 15 m/s \protect\cite{Alerstam1993_BirdMigration}, this stream corresponds to an intensity of around 1 600 birds per second.}\label{fig:density} \end{figure} In general, I fully agree with Jenni that (i) number estimates via flock volume and density should be avoided, especially if these quantities are not carefully measured, and (ii) number estimates are much better done by estimating the intensity of birds passing an observer, preferably with the help of photographs. So, how many birds could there have been in Thun? Here it is worth mentioning that there are other assessors than Jenni that has proposed lower numbers than M\"{u}hlethaler. \citeA{Egli1951_VogelHeimat}, for example, states that it was impossible to make any proper count but that 5 million should not be an overestimation. Moreover, according to \citeA{JenniNeuschultz1985_OrnitBeob}, a certain Frutiger reached the number 1--2 million after analysis of photos. That numbers disagree is one thing -- they often seem to do in the context of large flocks -- but the question is who made the least inaccurate estimate. It should be noted that the lower numbers presented are also rather poorly founded. There is, however, yet another aspect to consider: the roost area. M{\"u}hlethaler specified the area to in total 13.6 ha, and that it comprised trees of Europan spruce \emph{Picea abies} and European silver fir \emph{Abies alba} at the age of 20--50 years. Compared to other roosts, many carefully studied, the resulting density of 5.3 million/ha appears surprisingly large. Although impossible to prove, I suspect that an overestimation has been caused by overestimation of both stream width and density. That the stream was 200 m wide and as dense as 1 m$^{-3}$ continuously for 45 min sounds rather extreme (around 13 000 bird per second, for each roost). \subsection{Regarding the claim of 120 million} As can be seen in Table \ref{tab:roost_table}, it is rather common with number estimates based on flock volume and density (method B). In fact, the 72 million in Thun is not the highest number reached in this manner. \citeA{NardinBrauchle1979} concluded that the roost in Etobon 1977--1978 comprised 100--120 million bramblings. Their analysis is somewhat difficult to follow, even for a physicist, but their argument behind setting the flock width and height to 250 m and 50 m, respectively, is not convincing. It is interesting to note that, along with this volume/density calculation (method B), they also present an intensity-analysis along the lines of method A. There, an analysis of a photo resulted in a total number of 12 million. 12 million seems reasonable for this 16 ha roost, and it can be noted that \citeA{Francois1978_Falco} in his description on this roost mentions, without any motivation however, the number 10 million. It can perhaps have been more birds than that, but based on the discussion above, I agree with \citeA{JenniNeuschultz1985_OrnitBeob} that the range 100--120 million is unrealistic. This may be an example of how previous overestimations drive new overestimations. In fact, \citeA{NardinBrauchle1979} explicitly states that they consider their analysis more restrained than \citeA{Muehlethaler1952_OrnitBeob}, arguing that if they would use his density of 1 birds/m$^3$ their estimate would increase to 875 million. While they may have been more careful in terms of bird density assumption, their values for the height of their stream, which they set to 50 m, is less conservative. Again, in my opinion, an example of how difficult it is to set flock dimensions correctly. \subsection{Annual mass concentrations in corn districts in France 1960--1980}\label{subsec:corn_districts} In previous sections it has been argued that the largest published values for brambling roosts should be regarded as overestimations. Clearly, it is not easy to answer the question of how many birds that the largest bramblings roosts has contained. The largest number mentioned in the review by \citeA{Jenni1987_OrnisScand} is 20 million from a roost in Pau, Pyr{\'e}n{\'e}es-Atlantiques in France. The roost in Pau is not just another large roost -- it represents fascinating brambling history. Corn production increased in France during the twentieth century and bramblings adapted to this new and abundant source of food . The roost in Pau was likely established in early 1960s and was occupied annually for several years \cite{Alberny1965_OiseauxDeFrance}. This is itself an interesting contrast to other very large roosts which are formed during beech mast years and therefore used in isolated years (never several years in a row). This interesting adaption to changes in human farming was studied H{\'e}mery and Le Toquin, focussing on the energy needs of bramblings and the supply offered by the losses in corn farming \cite{Hemery1975_CrAcadSc,Hemery1976_LeTerre}. Changes in corn farming around 1980 (early burial of stubble) deprived the bramblings of this abundant food resources \cite{Dubois2008_BirdsFrance}. Regarding the specific value of 20 million, the most common source for this value is an article on the energy expenditure of bramblings by Georges H{\'e}mery and Alain Le Toquin \cite{Hemery1975_CrAcadSc}. For example, the reference work \emph{Nouvel inventaire des oiseaux de France} by \citeA{Dubois2008_BirdsFrance} also refers to this work when stating 20 million as the peak of the roost numbers in Pau\footnote{Note that the reference given by \citeA{Dubois2008_BirdsFrance} is incorrect: the cited article is titled \emph{Determinisme energetique des concentrations de Pinsons du Nord\ldots}, not \emph{Determinisme des concentrations de Pinsons du Nord\ldots}. The missing word \emph{energetique} constitutes an unfortunate typo, as it indicates that the focus is on determining concentration rather than energy expenditure. The typo may simply come from the winter atlas of France, as this work contains the very same typo \cite{Hemery1991_WinterAtlas}}. Indeed, H{\'e}mery's article contain a datapoint in a scatterplot that corresponds to a roost number of 20 million. The value is, however, not commented further. According to \citeA{Hemery1976_LeTerre}, the number 20 million refers to the number in December 1967, but I have not found any work in which the number estimate is elaborated. Sadly, the ornithologist and brambling enthusiast Georges H{\'e}mery, passed away in 2013 \cite{Yesou2014_RevEcol} and could not give his view on these numbers. His colleauge Alain Le Toquin believes that the value 20 million comes from Jean-Claude Alberny (Le Toquin 2020, personal communication). However, Jean-Claude Alberny does not recall any other number than 15 million, a number he published in 1965 in an intriguing article describing the roost in Pau \cite{Alberny1965_OiseauxDeFrance}. The roost, in 1965 covering around 10--13 ha, was shared with starlings \emph{Sturnus vulgaris}. While most roosts has been located to conifers such as European spruce \emph{Picea abies}, European silver fir \emph{Abies alba} or Lawson cypresses \emph{Chamaecyparis lawsoniana}, birds here perched in Holly \emph{Ilex aquifolium}, an evergreen, and stunted oaks \emph{Quercus} with retained dead leaves (marcescence). The bramblings were popular among hunters (not only in Pau) and served as food, and ringing revealed that many bird were injured: \begin{quote} Le baguage a appris \'{e}galement l'important pourcentage d'oiseaux bless\'{e}s, pr\`{e}s de 5\% en janvier, chiffre diminuant par la suite. En effet les chasseurs appr\'{e}cient cette esp\`{e}ce, aussi bien dans les Landes, le Gers et les Basses-Pyr\'{e}n\'{e}es o\`{u} l'on peut trouver des brochettes enti\`{e}res de ces "ortolans". \end{quote} Alberny also reported that some birds suffered from some kind of disease. Regarding the number of birds Alberny suggests 15 million, as also stated in \ref{tab:roost_table}. This is, however, a rough estimate. Birds came from all directions and proper counting seemed impossible. Alberny, believing it to be an underestimation, writes: \begin{quote} Une é\'{e}valuation parait impossible, les oiseaux arrivant de tous c\^{ô}té\'{e}s à la fois. De plus la configuration du relief ne permet pas de voir le dortoir en entier. Les Pinsons sont de tr\`{e}s loin plus nombreux que les Etourneaux. On peut affirmer sans crainte qu'il y en a au moins 15 MILLIONS... Probablement plus... \end{quote} It seems unlikely that H{\'e}mery studied the numbers in Pau as early as 1967. In an ambitious article from 1981, he elaborates on the difficulties of counting large numbers of birds, and explores whether infrared thermography can be of assistance \cite{Hemery1981_Thermographie}. However, in this work H{\'e}mery writes that proper counting at a roost requires multiple competent observers and argues that uncertainties may be as high as 50\% when dealing with gatherings of birds on the order of ten millions. H{\'e}mery also presents the results of two visual counts made in Pau in February 1979: $2.3$ million $\pm 25\%$ on February 5 and later, when most birds had abandoned the roost, $450\,000 \pm 33\%$ on February 14. The work does not contain any comparison with earlier numbers from Pau, nor details on how and by whom the counting was conducted in 1967 when 20 million was reported. To conclude, it is difficult to confirm that there was as much as 20 million in a single roost in Pau. Given its large area (9--13 ha), the roost in Pau is without doubt one of the largest ever registered. As can be seen it Table \ref{tab:roost_table}, there are a few roost that has been of similar size. Which one of these that held the highest number of bramblings remains unknown. \subsection{The classic 1915--1916 roost in Sweden} Another interesting example is the internationally renowned winter roost in K{\aa}ger\"{o}d, Sweden 1915--1916, studied in detail by Hugo Granvik \cite{Granvik1916_FaunaFlora,Granvik1916_JOrnit,Nilsson1983_Anser}. In an otherwise detailed and careful study of a brambling roost, the number 5.4 million given by Granvik lacks detailed justification. Granvik states 5.4 million is reached if assuming that 2 000 birds per second arrive at the roost during the observed 45-minute fly-in duration. The number in itself is not sensational, given what we know today, but as the roost area appears to have been rather small the number appears surprisingly high. Granvik specifies that roost area to "n{\aa}got tunnland" in Swedish, literally meaning around one barrel of land, i.e. 0.5 ha. That the roost area was rather small is also supported by sketches made by \citeA{Nilsson1983_Anser}. It cannot, of course, be ruled out that the accumulation of bramblings at this site as the winter progressed -- in relation to available area -- made this roost extraordinary dense. In fact, \citeA{Granvik1916_FaunaFlora} writes that the bramblings utilized birch-trees in the border of the coniferous roost area. It is however not clear whether it was confirmed that these trees were populated also in the middle of the night. In the 2019--2020 roost in Sweden, I noted movements from beech trees into the actual roost also after dusk. \subsection{Counting trees and birds per tree} The study by \citeA{Kjellen1993_Anser} is, to the best of my knowledge, the only previous work that have conducted number estimation by estimating the number of trees and birds per tree (method C). The work concerns a roost in Sweden located in January 1993, comprising approximately 7.5 ha (500 m by 150 m) of plantations of European spruce of different ages and heights between 10 and 20 m. Furthermore, it was estimated that there on average was one tree per 10 m$^2$, resulting in a total tree count on 7 500. The authors estimated that at least 200 birds sat in each tree, and perhaps 500 in the larger ones, and conclude that the total number of bramblings at the very least should be 2 million. A fly-in count (method B, but without photos) by \citeA{Lithner1995_FaglarNV} also estimated the number of birds to at least 2 million. Since the stated roost area is rather large, the number may appear somewhat low. It is, however, worth noting that this particular roost seems to have suffered from some kind of deadly disease (large numbers of dead birds were found within the roost area). As described in Section \ref{sec:the_mass_conc_in_Sweden}, observations at the Swedish 2019--2020 roost suggest that a single tree can host on the order of 1000 finches. A similar number was suggested for larger trees in the well-studied roost in Switzerland 1916--1947 \cite{Gueniat1948_OrnitBeob}. More studies on how many birds that roost per tree would be enlightening. \subsection{High numbers from nowhere} Around 100 texts on bramblings were read as a part of this review and on a few occasions I came across very high numbers that I could not track: the cited articles did not, as far as I can see, contain the claimed information. Unless other researchers have better luck in finding support in original sources, these numbers should not be recited. To facilitate future works on the topic, I have decided to explicity mention these oddities in the vast literature on brambling mass concentrations. The perhaps most important case is a claim in the standard reference \emph{Finches} by \citeA{Newton1972_Finches}. Referring to \citeA{Gueniat1948_OrnitBeob} and \citeA{Sutter1948_OrnitBeob}, Newton writes that there was a roost of 50 million bramblings in Switzerland during the 1946--1947 winter. None of these articles contain such a number (perhaps a referral in \citeA{Gueniat1948_OrnitBeob} to an older roost and the number 5$\nicefrac{1}{2}$ million was misinterpreted as 51--52 million and rounded to 50 million?). Referring to Newtons text, this numbers is unfortunately recited in other important works. Another large number that lacks support is the 61 million that \citeA{Moller2019_EcoEvol} recites, referring to \citeA{Geroudet1952_NosOiseaux}. Finally, it should be noted that \citeA{Chalverat2003_SchwForst} incorrectly refers to the PhD thesis of Jenni \cite{Jenni1984_PhDThesis} when stating that the roost in R\"{o}serental 1977--1978 comprised 28 million birds. Instead, the thesis argues (p. 40--41) that the roost contained around 6 million birds (the range 2--9 million is also given). This estimation has also been published in journals \cite{JenniNeuschultz1985_OrnitBeob,Jenni1991_OrnisScand} \section{Conclusions and discussion} The literature review presented in this work suggest that there is support for bramblings roost involving up to around 15 million bramblings. In terms of areal density of birds, a roost may hold on the order of one million birds/ha. As large variations in roost density can be expected, this should be seen as an utterly rough estimate in need of further verification. As a comparison, the passenger pigeon with its tenfold mass has been estimated to roost in densitites of around 100 000 birds/ha \cite{Ellsworth2003_ConsBiol} and the red-billed quelea has been claimed to roost at densities of 2.5 million/ha \cite{Manikowski1988_TropicalPest}. Claims of higher numbers, or densitites, such as the 70 million bramblings from Switzerland 1951--1952, is based on questionable methods and does not fit well the overall picture that emerges from collection of reports on mass concentrations of bramblings that has been built up throughout the years. Unfortunately, despite that the number 70 million has been rejected earlier \cite{JenniNeuschultz1985_OrnitBeob}, it keeps being recited without reservations in new works on mass appearances of birds. A main reason for this is perhaps that important reference books, like \emph{Finches} by \citeA{Newton1972_Finches} and \emph{Bird Migration} by \citeA{Alerstam1993_BirdMigration}, presents these values without reservations or discussions of uncertainties (in later works such as \emph{Population Limitation in Birds}, however, \citeA{Newton1998_PopLim} adheres to Jenni’s more restrictive view that values above 20 million lack proper support). Given the difficulty in counting large numbers of birds, reports of very large numbers should always be used and recited with great care, regardless of whether it concerns bramblings, starlings, blackbirds, queleas or passenger pigeons. The large ecological and economical significance of large flocks of birds motivates further studies. Clearly, much can be done to improve our knowledge on the number in which flocks of our most abundant birds appear. This includes bramblings, despite all the efforts made so far. For example, there is no publication with a solid analysis and presentation of uncertainties in the number estimation conducted. In addition, roost areas are often not well investigated (demarcation in map missing). Just as for example vagrancy and taxonomy gets a lot of attention in ornithological journals, it would be very valuable to see also more work on accurate estimation of flock and roost sizes. From a critical point of view, \emph{millions} should only be interpreted as \emph{many} unless carefully motivated. While H{\'e}mery argued that, even with multiple competent observers, uncertainties may be 50\% when numbers are in the ten million range \cite{Hemery1981_Thermographie}, the discussion on the 70 million and 120 million numbers \cite{Muehlethaler1952_OrnitBeob,NardinBrauchle1979,JenniNeuschultz1985_OrnitBeob} indicates that uncertainties also can be a factor ten, depending on count method. \subsection{Roost characterization: a short checklist} \begin{itemize} \item \textbf{Counting.} Try to monitor morning lift or evening fly-in from a spot with good overview. Make careful notes on timing (start and end of movements) and estimate the intensity of birds streams preferably by taking systematic series of photographs (or film). Avoid estimating numbers from flock volumes (width, height and length) and bird densities (birds per m$^3$). \item \textbf{Roost area.} Determine roost boundaries via studies of excrement layers. Although zones around the roost, where birds gather before flying in, will show a lot of droppings, the actual roost area will be completely covered in excrements. Use the demarcation to estimate the roost area carefully using map tool (i.e. Google Maps). \item \textbf{Document trees.} Document trees in the roost (species, age, height and distance between trees) and try to estimate the total number of trees. \item \textbf{Birds per tree.} Try to estimate the number of birds per tree, preferably during the night using thermal cameras. \item \textbf{Roosting in bare trees.} If there are indications that bird sleeps also in non-conferious trees (e.g. in beech or other deciduous trees), confirm this with e.g. a thermal (infrared) camera in the middle of the night. The bramblings move also after dusk, and evidence of roosting in, for example, peripheral deciduous trees would be interesting (cf. \citeA{Granvik1916_FaunaFlora}). \end{itemize} \section{Acknowledgement} First of all, I would like to thank Hanna, Siri och Vera for letting our family include also bramblings for quite some months. There are also many that have contributed more directly to the work, for example by engaging in interesting discussions, supplying complementary information, assisting in my hunt for obscure references, lending me equipment or reviewing and providing feedback on the manuscript. In particular, I would like to acknowledge the help from Thomas Alerstam, Johnny J{\"o}nsson, Nils Kjell\'{e}n, {\AA}ke Lindstr\"{o}m, Cecilia Nilsson, Lars Rippe \& Roine Strandberg (Lunds Universitet), Sara Agrup, Roland \& Jean-Claude Alberny, Janne Dahl\'{e}n (Ecogain), Igor Drobyshev \& Rolf {\"O}vergaard (SLU), Miro Fulín, Mats Hellmark (Sveriges Natur), Nicole H{\'e}mery, Alain Le Touqin, Lukas Jenni \& Hans Schmidt (Schweizerische Vogelwarte, Schweiz), Toma\v{z} Miheli\v{c} (Birdlife Slovenia), Yves Muller (Ligue pour la protection des oiseaux, LPO, Frankrike), Karin Persson (Falsterbo F{\aa}gelstation), Jean-Marc Pons \& Jean-Pierre Siblet (Mus{\'e}um national d'Histoire naturelle, Paris), Fritz Rosen\"{o}rn (R\"{o}ssj\"{o}holms gods), Sissel Sj\"{o}berg (University of Copenhagen), my brother Stefan Svensson, Jean-Marc Thiollay, Raffael Winkler (Naturhistorisches Museum Basel, Schweiz), Hasti Yavari (Axis Communications), Pierre Y{\'e}sou and Jabi Zabala. \bibliographystyle{apacite}
{'timestamp': '2020-10-27T01:16:31', 'yymm': '2010', 'arxiv_id': '2010.08465', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08465'}
arxiv
\section{Introduction} \label{sec:introduction} More and more evidence indicates that global climate change has led to deforestation and extinction of species over the past decade. The incremental changes in temperature have not only caused extreme events such as floods, drought and gales, but inevitably affect landscapes and whole ecosystems. In such a situation, species may struggle to adapt to changes \cite{Ancienttreeguide}. Moreover, it is reported \cite{Germanyforests} that 110,000 hectares of forest have died in 2018, which is around the size as 150,000 football pitches or one nineteenth of Wales, due to extreme heat and storms. Certain species whose habitats were living woods have lost their habitats due to deforestation and dying trees. On the other hand, organism or creatures that take dead wood as habitats (for example: fungus, bacteria, predatory beetles, and parasitic wasps) increase their population. Pests such as bark beetles and cardinal beetle can nest in dead tree trunks, and then may move to healthy trees and kill them \cite{Germanyforests}. In addition, the dry, inflammable nature of dead wood makes fire disasters happen more frequently \cite{Californiafires}. In California, poor management of dead wood in forests has been identified as the major cause of wildfire. Both brought huge costs since the fire destroyed neighboring healthy trees and spread fast to villages nearby. Forest fires also trigger severe smog; for example, in 2015, wildfire smoke in Indonesia caused an estimated 100,000 premature deaths \cite{wildfiresmokeinIndonesia}. Because the of impacts on ecosystems, inhabitants and households mentioned above, technology to monitor forest areas has been developed rapidly in the past decades. Technologies such as remote airborne sensor or satellite imagery made forest monitoring less costly, and allows monitoring without human involvement. By using these technologies, forest experts and disaster specialists not only can monitor forests in real-time, but also adopt preventive measures for natural disasters. On the other hand, pest disaster, one of the natural disasters caused by climate change, has recently drawn experts' attention. The Canopy Health Monitoring (CanHeMon) \cite{canhemon} project aimed to eliminate the danger to forests from pine wood nematode (PWN), and so previous research has been done to detect dead trees within forests, to prevent them from becoming vectors for PWN. A MaxEnt-based iterative image analysis algorithm, applied to remote sensing data, as able to detect individual declining tree crowns with high accuracy \cite{canhemon}. The algorithm searches for the distribution with the maximum entropy for a given input set of occurrences and a set of constraining variables. As higher entropy indicates high disorder and abundance of information, the algorithm can filter out irrelevant variables, leaving the most useful variables highly correlated to dead trees. However, the results revealed that the rate of false positives increases as the sample size decreases. Moreover, eliminating small size samples (smaller than 2.5m$^2$) harmed the true positive detection rate, dropping from 80\% to 65\%. This may indicate that the algorithm is not suitable to detect small objects or that there were not enough samples of small trees in the training data. In addition, the CanHeMon project suggested that using deep learning algorithms may provide a more generalised image analysis model and allow us to identify pixel-wise shapes of trees in an image. To investigate this, the CanHeMon team also performed tests using a neural network model. The results showed that rate of false positives was lower than for the MaxEnt-based algorithm, but the behaviour of the loss function indicated more epochs and iterations were needed in training the model. Hence, in this research, we extend the deep learning methods applied by the previous team. In this study, we used a Mask Region with Convolutional Neural Networks (Mask-RCNN) algorithm, accompanied by transfer learning \cite{Transferlearning} to deal with the problem of pixel-wise object identification and to enhance the learning pattern, i.e. through additional training sessions, the overall score performance can be improved by using pre-trained weights produced in the previous session. Moreover, to cope with small datasets, and problems with unlabelled data, we use synthetic tools: randomly assigning instances into backgrounds, both extracted from raw data. At the same time, we output COCO format annotations \cite{COCO} to be used in inference. In general, manually annotating these masks is quite time-consuming, frustrating and commercially expensive \cite{semanticsegmentation}. However, we were inspired by Adam Kelly, the founder of Immersive Limit, and were able to automatically create thousands of synthetic images and their annotations with minimal manual effort. \cite{CreatingCOCODatasets} \newline The study makes four major contributions: (1) Use synthetic data to do Mask RCNN modeling and reach about 54\% on mean average precision score (mAP) . The results show that it is possible to use synthetic methods to mitigate data scarcity. (2) Mask prediction is limited by selected ROIs and can be found from high loss of RPN. Therefore, applying semantic segmentation may be a more practical way than instance segmentation to detect dead tree region.\autoref{subsec:lossofRPN} (3) Using two optimizers in training process caused loss converged faster than using one optimizer. \autoref{subsec:lossofRPN} In addition, \autoref{fig:research} provides our framework for forest analysis. More details will be in the following sections. \begin{figure} \centering \includegraphics[scale=0.48]{images/research} \caption{Structure of the Mask-RCNN model.} \label{fig:research} \end{figure} \section{Related work} \subsection{Satellite imaging for forest analysis} Although we did not use satellite images in our research, they have been used to monitor forest cover for a long time. Analysing the change of forest cover generally relies on visual interpretation of a dataset. Accompanied with groud measurements, scientists are able to calculate the loss of forest cover over time and doing assess properties from the satellite imagery, such as biophysical and biochemical properties of forest. \cite{groundmeasurements} In addition, in various studies\cite{Landsatstudy1}\cite{Landsatstudy2}\cite{Landsatstudy3}, Landsat imagery\cite{LandsatDataAccess}, a popular open database of satellite imagery, was sampled or trained to monitor forest cover changes. Landsat imagery resolution is between 15-60m with multiple bands. "Landsat is a joint effort of the U.S. Geological Survey (USGS) and the National Aeronautics and Space Administration (NASA)...The data are useful to a number of applications including forestry, agriculture, geology, regional planning, and education. "\cite{Landsatgov} \subsection{AI techniques in object detection} With the remarkable advancement in artificial intelligence techniques in the past decades, there are several object detection algorithms which are now generally used, for example R-CNN\cite{RCNN}, Fast-RCNN\cite{Fast}, Faster-RCNN\cite{Loss}, YOLO\cite{yolo}, SSD\cite{SSD}, and NAS-Net\cite{NASnet}. When performing object detection, we are interested in finding two things: where our target objects are located, and which categories they belong to\cite{Review}. Our goal is to draw bounding boxes around target objects in an image, and output a percentage indicating how certain we are that they belong to certain classes. Moreover, state of the art techniques allow real-time prediction of object localisation and classification, for example You Only Look Once (YOLO) and Single-Shot Detector (SSD). However, the cost of the fast inference time of such methods may be lower accuracy and low-resolution feature maps, due to a single network evaluation \cite{accuracycomparison}.. They use a single stage to complete both object localisation and classification, but in constrast, region based algorithms (RCNN, Fast-RCNN, Faster-RCNN and Mask-RCNN) separate the process into to two stages: first using a region proposal network (RPN) to propose a bounding box for a candidate object; then predicting the class and box offset, and outputting a binary mask for each region of interest’s ROI \cite{MaskRCNN}. That means we calculate both the classification scores and bounding box regression in second stage to decide which ROIs have the highest probability to contain target objects, and simultaneously perform instance segmentation on selected ROIs. Here, instance segmentation \cite{MaskRCNN} means to differentiate each target object and cut them apart even when they are labeled in the same class. It is often compared to semantic segmentation, labeling on each pixel with the class of its enclosing object or region (see \autoref{fig:segmentation}). Note that we only took segmentation into account because it was more precise to cut off dead tree regions in pixel-wise manner than simply output bounding boxes; for example, some boxes may contain a big proportion of living trees. \subsection{CNN and FCN in pixel-wise dead forest mapping} Recent studies \cite{Mappingdeadforest1}\cite{Mappingdeadforest2}\cite{Mappingdeadforest3}\cite{Mappingdeadforest4}showed CNN and FCN were used in sementic segmentation on forest mapping. In \cite{Mappingdeadforest1} a VGG neural network (an architecture of CNN) was proposed to classify pixels with a sliding window technique. One notable approach called ensemble learning was introduced to aggregate different predictions generated by the same model. This produced determistic estimates and reduced uncertainties caused by weight initialization settings. The resulting global accuracy predicting health status of two tree species was around 80\% to 85\%. However, dead trees were misclassified (defined as "omission error") at a rate of 35\% to 40\%. Another study suggested sliding windows \cite{disadvantagesofslidingwindows} cause high computational cost because neighbour pixel information, which contains the same information as centre pixels, is used to classify centre/target pixel. An algorithm such as FCN is developed to prevent duplicate computation by predicting many pixels at once. In addition, FCN can take various input sizes and output a dense prediction. A DenseNet (an architecture of FCN) proposed in \cite{Mappingdeadforest2} has outstanding results for classifying dead trees and standing dead trees. The resulting recalls and precisions are mainly within 90 to 100\% although a recall of a subset was 67.8\%. The author also encouraged that instance level prediction can be done to improve future research. \subsection{Transfer learning} In the field of image processing, there have been many studies using transfer learning. The technique uses an existing trained network to improve the training accuracy for a new model. Since an outstanding trained network such as COCO or ImageNet has been trained using many images with a big number of labels, it seems sensible to reuse fundamental parts of the pre-trained net as low-level feature extractors, i.e. to recognize edges, colours and textures - whether detecting complex and subtle objects such as a human fact or simple objects such as rectangles, early layers in neural networks always detect the same basic shapes and edges. To be more specific, the COCO dataset\cite{COCO} is a large-scale object detection, segmentation, and captioning dataset. It has over 200\,000 labeled images with over 80 labels, while the ImageNet dataset has tens of millions of images with thousands of labels. \cite{Alexnet} \cite{Transferlearning} So to train a model on a custom dataset, all we need to do is replace the classification and bounding box predictors with customised ones which are able to predict our labels. First, we take a pre-trained net without its FC part, since Fully Connected layers are used only for the old model's classification. Next, a new FC containing customized label classifiers replaces the old. Then, a convolution base which is initially close to the old classifier needs to be frozen since it contains high level features (for example cat ears, dog eyes, or a more representative feature) related to classification in the old model which may not be useful for our own customized classification problem. \begin{figure} \centering \includegraphics[scale=0.5]{images/image1} \caption{Semantic segmentation (left) versus instance segmentation (right). Image from \cite{MaskRCNN}.} \label{fig:segmentation} \end{figure} \subsection{Transfer learning in forest aerial imagery} We used a COCO or Imagenet pre-trained net and retrained the "head" parts for our model in the first session, i.e. we kept the COCO or Imagenet backbone but retrained the RPN, classifier and mask heads of the network. \cite{stepbystepprediction} In the first training session, we only trained the head since we want to leverage the advantage from COCO and ImageNet, that is, use the weights that have been trained from many images. However, we found that merely training the head was not sufficient to get higher accuracy. Because of that, in the second and third sessions, we train all layers twice. Therefore, we denote the deeper model as “head + all + all”. Then in the second training session, we used the last weight produced in the first session to continue training. This gave us faster training times, and allowed us to use a well-trained model even when we had scarce data. Related studies on detecting objects in satellite imagery of urban landscapes\cite{CNNsatellite} show that by using an ImageNet pre-trained net, accuracy was increased by around 5\% for a fixed length of training time. However, the study also showed a less satisfying performance even after using transfer learning because the model is trained to predict objects from another dataset which has different domain features, which may not be similar to our own training data. Therefore, problems such as how transferable features in deep neural networks are, and how to effectively reuse pre-trained nets when most features of the target objects are different from those of the training data, have been discussed in \cite{DDT}. A Selective Learning Algorithm (SLA) has been proposed in this case, which learns useful features from unlabelled data and introduces an intermediate domain to close the gap between target objects and training data. \section{Preliminary on CNN and Mask RCNN} \subsection{CNN} \label{sec:CNN} \subsubsection{What is a convolutional neural network?} A convolutional neuron network (covnet, or CNN) is a class of deep neural network that has proved very powerful for image classification. In 2012, Alex Krizhevsky used CNN to win the ImageNet competition which made neural nets come to prominence in the field of computer vision. \cite{Alexnet} \subsubsection{Why use a convolutional operation?} We can view an image as having 3D inputs with (height, weight, channel) so the input features have dimension H$\times$W$\times$C. For deeper layers, the channel value is usually increased in order to learn more features. A channel value is also the number of filters which contain special features we want to detect. In addition, given pre-defined filters, we can obtain corresponding feature maps by applying convolutional operation on input images. The operation not only shrinks the input dimension but preserve the spatial relationship between pixels; therefore a series of features are as well preserved. \autoref{fig:featuremaps} shows different feature maps produced by applying filters to the same raw images. Usually, a typical Convnet looks like \autoref{fig:covnet}. \begin{figure} \centering \includegraphics[scale=0.4]{images/image4} \caption{Different feature maps produced by applying various filters to the same raw image. From \cite{featuremap}.} \label{fig:featuremaps} \end{figure} \begin{figure}[h] \centering \includegraphics[scale=0.3]{images/image5} \caption{Structure of a convolutional neural network. From \cite{ImageProcessing}.} \label{fig:covnet} \end{figure} \subsubsection{Why can’t we use a simple CNN to predict object location?} \begin{itemize} \item The number of target objects and their coordinates in the raw picture is unknown before detection, so output nodes can’t be specified. In CNN, however, a fixed number of nodes is predefined for the output layer. Normally, outputs in CNN are fixed, predefined classes. Therefore, additional layers are needed to locate their coordinates. \item To classify if an object is a target or not, a number of fixed-sized input images are fed to CNN. However, in the object detection problem, input objects may have different sizes. In this case, a ROI pooling layer in RCNN is added to scale all objects in fixed size before passing them to the classification process. \end{itemize} \subsection{Mask RCNN structure} \label{sec:maskrcnn} In this section, we will first introduce Faster RCNN, the predecessor to Mask RCNN; then we will discuss Mask RCNN. This will give a broad picture of how Mask RCNN developed and the structure of the algorithm (see \autoref{fig:fasterrcnn}). \subsubsection{Faster RCNN} Faster RCNN begins with a standard convolution neural network (CNN) for feature extraction, which produces feature maps. A feature map is the output activation for a given filter in each layer. When a filter matches certain features on an image, the convolution operation \cite{convolutionarithmetic} returns high activation values and reveal those features in the feature maps. A feature map is also a mapping of where a certain kind of feature is found in the image \cite{featuremap}. Then, it uses a Region Proposal Network (RPN) to extract Regions of Interest (ROIs) and resize the ROIs to a fixed size using ROI pooling. (Note: In section \autoref{sec: backbone generates feature maps} , we will talk about how RPN generates ROIs.) \begin{figure}[h] \centering \includegraphics[scale=0.43]{images/image7} \caption{Structure of a Mask RCNN model. From \cite{MaskRCNN}.} \label{fig:fasterrcnn} \end{figure} \begin{figure}[h] \centering \includegraphics[scale=0.6]{images/pooling} \caption{How a max pooling layer works} \label{fig:pooling} \end{figure} A pooling layer then reduces the dimension of the ROIs and the number of parameters in order to save training time and combat overfitting \cite{ImageProcessing}. It divides an ROI into a number of sections by pre-defined output size (Note: it is not necessary that ROI is perfectly divisible by the section number.) Next, a maximum value is found for each section and we replace all other pixel values in the section with this value. \cite{Loss} See \autoref{fig:pooling}. Finally, the ROIs after max-pooling are flatten and fed to two fully connected layers (FCs). The flatten process makes pooled ROIs turn into vectors which store non-spatial features for later calculate the multilinear relationship between input neurons (in each ROI) and classes, and between neurons and bounding box size. One FC layer calculates a bounding box regressor to refine the bounding box size, i.e. make each box covers the regions over its target object. Coordinates information will be sent to bounding box loss caculation. In next iteration, to minimize lost, bounding box coordinates will be updated therefore produce more accurate bounding box; and the other FC layer predicts a vector of probabilites over output classes using a softmax function. The probabilies will be used in calculation of cross-entropy loss which we adjusts probability information to minimize the cost in every iteration. \subsubsection{Mask-RCNN} Mask-RCNN can be thought of as a combination of a Faster RCNN that does object detection (class + bounding box) and a Fully Convolutional Network (FCN), a semantic segmentation method producing a pixel-wise mask. (See \autoref{fig:maskrcnnstructure}) In addition, the author of Mask RCNN \cite{MaskRCNN} did some fine-tuning of Faster RCNN and FCN. First, since the ROI pooling layer in Faster RCNN can lead to the location of target objects in the feature map being misaligned from their location in the original image, this is dealt with by refining the mask with an ROI Align layer. ROI Align is a quantization-free layer, preserving exact spatial locations by replacing quantization with bilinear interpolation \cite{MaskRCNN}. Bilinear interpolation is used for computing the floating-point location values in the input \cite{DDT}. Then FCN, a semantic segmentation method, is applied to each ROI in order to predict a pixel-wise, binary mask (see \autoref{fig:fcn}). Unlike the original setting of FCN, here the activation function in FCN was changed from softmax to sigmoid which was shown to significantly increase Average Precision (AP) \cite{MaskRCNN}. The reason is that FCN only calculates per-pixel sigmoid values and an average binary cross-entropy loss for a single, wholly classified object each time, rather than calculating per-pixel softmax and a multinomial loss for all pixels. Because of this, label prediction is decoupled with mask generation which avoids competition among classes. \begin{figure} \centering \includegraphics[scale=0.68]{images/maskrcnn} \caption{Structure of the Mask-RCNN model. Image from \href{https://www.youtube.com/watch?v=FHytoCvj90w}{[link]}.} \label{fig:maskrcnnstructure} \end{figure} \begin{figure} \centering \includegraphics[scale=0.6]{images/fcn} \caption{FCN predicts a pixel-wise binary mask. Image from \href{https://ccsearch.creativecommons.org/photos/68cf9fb6-26a9-4a9a-a30c-923900617fed}{[link]}.} \label{fig:fcn} \end{figure} \subsubsection{Backbone of Mask-RCNN} Mask-RCNN uses Resnet-FPN as its default backbone and is a type of CNN which produces feature maps; the structure of Feature pyramid networks (FPN) allows us to build high-level semantic feature maps at different scales. When images are fed into FPN, first they go into the bottom-up process: the process functions the same as classic covnet extracts features, four feature maps (C2, C3, C4, C5) are produced and get reduced size (1/2 the size of the previous map) as the level goes up. At the same time, more features are extracted on the upper level but have lower resolution because of the convolution operation process. In addition to the loss of resolution introduced by this, high resolution feature maps from lower level are not used for detection because of the lack of sufficient information (for example, it is possible that only some edges are detected). These two disadvantages make detection of small objects very difficult. In the FPN paper \cite{FPN}, however, the author added a top-down pathway (see \autoref{fig:resnetfpn}) to reconstruct a high resolution from a semantic rich layer by an upsampling method. The method doubles the map size (twice the size of the previous map) as the level goes down, with the resulting feature maps denoted as (P2, P3, P4, P5). A bottom-up feature map which goes through a lateral connection is then merged with a top-down feature map accordingly. The connection simply applies a 1$\times$1 convolution filter on each bottom-up feature map; therefore, it retains map sizes but reduces channel depths. In addition, to deal with spatial aliasing (the resulting location of objects may be different from their locations in the raw image because of repeatedly downsampling and upsampling) in the merged maps, a 3$\times$3 covolution filter is used to generate feature maps with the highest resolution and accurate spatial information; therefore we can use them to do final predictions. \section{Our Framework for Forest analysis} In this section, we explain how we applied Mask-RCNN to predict the location of dead trees in forests. The framework structure can be referred to \autoref{fig:research}. All experiments are conducted using Tensorflow-GPU docker on a Mac Air with eight NVIDIA Tesla V100 GPUs in Amazon Web Services (AWS). \subsection{Dataset collection and pre-processing} The dataset was collected by aerial photography on May 15th 2019, from the Wood of Cree in Scotland, and was stored in a 10 GB merged tiff file. As the file was too large for much of our software to process, we divided it into 40$\times$10 patches, each of 800$\times$800 pixels, using the Gridsplitter plugin for the QGIS software. We then created our synthetic dataset from the raw data: we extracted over 300 images of dead trees as foreground objects and randomly resized, rotated and changed the lightness before they were placed into 63 candidate backgrounds, also extracted from the raw data. Next we produced a mask by filling random colours over the dead trees and black for the background. We then retrieved $x$ and $y$ coordinates of the target objects and stored them in a COCO format annotation file. Eventually, the dataset was extended from 225 patches to 5000 patches and produced 5000 annotations in only a few hours. \begin{figure}[h] \centering \includegraphics[scale=0.6]{images/resnetfpn} \caption{Structure of Resnet-FPN, with the bottom-up pathway on the left, the top-down pathway on the right. \cite{FPN}. Image from \href{https://search.creativecommons.org/photos/95dc30f2-9394-4c28-96ab-ad2dc0bf57c0}{[link]}} \label{fig:resnetfpn} \end{figure} \begin{figure} \centering \includegraphics[scale=0.28]{images/raw+featuremap} \caption{A raw image, and the four corresponding feature maps. The lighter-coloured ``hot zones'' indicate the locations of the features we're interested in: shapes and colours of dead trees.} \label{fig:forestfeaturemaps} \end{figure} \subsection{How the backbone generates feature maps} \label{sec: backbone generates feature maps} Once the dataset is fed to our convolutional backbone, it produces four feature maps for each picture in the dataset (see \autoref{fig:forestfeaturemaps}). The feature maps are then scanned by RPN in a sliding-window fashion, finding anchors (pre-defined bounding boxes with fixed height and width) of high objectness score, i.e.\ the probability that an anchor contains an object or a non-object. Postive anchors have high objectness scores when they contain an object. Next, they are measured by value of 0.7 or more for the "Intersection over Union" (IoU) score. IoU is calculated as the ratio of the area of the overlap (intersection) between the pre-defined bounding box and the ground truthbox with the total area covered by both (union). Note that because positive anchors do not always include the whole boundary of their target object, they are examined by a regressor to refine the anchor location. However, if several positive anchors overlap too much, we keep the one with the highest objectness score and discard the rest. This method is referred to as Non-max Suppression. \autoref{fig:anchorbox} shows the steps to merge the anchor boxes. Before the region proposals are sent to the second stage, the algorithm scans and cuts out regions of interest (ROIs) from feature maps, as suggested by region proposals. ROIs are then scaled to a pre-defined, reduced dimension through the ROI pooling layer. (see \autoref{fig:pooling} ) Simultaneously, the selected ROIs are moved to the spatial locations corresponding to the original picture in the ROI alignment layer, and then are individually sent for pixel-wise classification in the FCN layer, resulting in a prediction result as in \autoref{fig:maskresult}. \begin{figure} [h] \includegraphics[width=0.3\linewidth]{images/P-anchors-before-refine} \hfill \includegraphics[width=0.3\linewidth]{images/Classified-ROIs} \hfill \includegraphics[ width=0.3\linewidth]{images/after-trimming} \caption{Step by step detection from finding postive anchor boxes to trim down low confidence objects.} \label{fig:anchorbox} \end{figure} \begin{figure} [h] \centering \includegraphics[trim=155 120 150 165, clip,width=0.45\linewidth]{images/maskresult} \caption{Mask-RCNN prediction result.} \label{fig:maskresult} \end{figure} \subsection{Model fine-tuning} To make our training sessions faster and to more precisely predict target objects, we made some modifications to the Mask-RCNN model. First, we adopted a deeper model, i.e.\ training a ‘head + all + all’ model instead of a single-head model, and we redefined the learning rate for each training session. We set different learning rates based on optimizers, as in \cite{learningrate}. Our choices of parameters are summarised in \autoref{tab:finetunesettings}. Column with bold type shows the a new, fine-tune value is assigned, compared to its last model. Models are seperated to 4 groups with more similarity within group and are allowed to be compared. \begin{table}[h] \resizebox{\columnwidth}{!}{% \begin{tabular}{|l||l|l|l|l|l|l|} \hline Model & \begin{tabular}[c]{@{}l@{}}Pre-\\ trained \\ net\end{tabular} & \begin{tabular}[c]{@{}l@{}}Acti-\\ vation\\ func-\\ tion\end{tabular} & \begin{tabular}[c]{@{}l@{}}Learn-\\ ing \\ rate\end{tabular} & \begin{tabular}[c]{@{}l@{}}Opti-\\ mizer\end{tabular} & \begin{tabular}[c]{@{}l@{}}Drop-\\ out\end{tabular} & \begin{tabular}[c]{@{}l@{}}Data-\\ set\end{tabular} \\ \hline\hline \begin{tabular}[c]{@{}l@{}}Fine-\\ tune-1\end{tabular} & \begin{tabular}[c]{@{}l@{}}Image-\\ Net\end{tabular} & Relu & \begin{tabular}[c]{@{}l@{}}$10^{-4}$,\\$10^{-5}$,\\ $10^{-6}$\end{tabular} & Adam & Yes & 2300 \\ \hline \begin{tabular}[c]{@{}l@{}}Fine-\\ tune-2\end{tabular} & \begin{tabular}[c]{@{}l@{}}Image-\\ Net\end{tabular} & \begin{tabular}[c]{@{}l@{}} \textbf{Leaky}\\ \textbf{ Relu}\end{tabular} & \begin{tabular}[c]{@{}l@{}}$10^{-4}$,\\$10^{-5}$,\\ $10^{-6}$\end{tabular} & Adam & Yes & 2300 \\ \hline\hline \begin{tabular}[c]{@{}l@{}}Fine-\\ tune-3\end{tabular} & \begin{tabular}[c]{@{}l@{}}Image-\\ Net\end{tabular} & \begin{tabular}[c]{@{}l@{}}Leaky\\ Relu\end{tabular} & \begin{tabular}[c]{@{}l@{}}$10^{-4}$,\\$10^{-5}$,\\ $10^{-6}$\end{tabular} & Adam & Yes & \textbf{3600} \\ \hline \begin{tabular}[c]{@{}l@{}}Fine-\\ tune-4\end{tabular} & \begin{tabular}[c]{@{}l@{}}Image-\\ Net\end{tabular} & \textbf{Relu} & \begin{tabular}[c]{@{}l@{}}$10^{-4}$,\\$10^{-5}$,\\ $10^{-6}$\end{tabular} & Adam & Yes & 3600 \\ \hline\hline \begin{tabular}[c]{@{}l@{}}Fine-\\ tune-5\end{tabular} &\textbf{COCO} & Relu &\begin{tabular}[c]{@{}l@{}}$10^{-4}$,\\$10^{-5}$,\\ $10^{-6}$\end{tabular} &\textbf{SDG} & Yes & 3600 \\ \hline \begin{tabular}[c]{@{}l@{}}Fine-\\ tune-6\end{tabular} & COCO & Relu & \begin{tabular}[c]{@{}l@{}}$10^{-4}$,\\$10^{-5}$,\\ $10^{-6}$\end{tabular} & SDG &\textbf{No} & 3600 \\ \hline \begin{tabular}[c]{@{}l@{}}Fine-\\ tune-7\end{tabular} & COCO & Relu & \begin{tabular}[c]{@{}l@{}}$\mathbf{10^{-3}}$,\\$\mathbf{10^{-3}}$,\\ $\mathbf{10^{-3}}$\end{tabular} & SDG & No & 3600 \\ \hline\hline \begin{tabular}[c]{@{}l@{}}Fine-\\ tune-8\end{tabular} & \begin{tabular}[c]{@{}l@{}}\textbf{Image-}\\ \textbf{Net}\end{tabular} & Relu & \begin{tabular}[c]{@{}l@{}}$10^{-4}$,\\$10^{-5}$,\\ $10^{-6}$\end{tabular} & SDG & No & \textbf{4000} \\ \hline \end{tabular}% } \caption{Comparison of settings for our fine-tuning of Mask-RCNN.Column with bold type shows the a new, fine-tune value is assigned, compared to its last model. Models are seperated to four groups with more similarity within group. } \label{tab:finetunesettings} \end{table} Secondly, to avoid overfitting, we used data augmentation, i.e. the algorithm accepts the original dataset, randomly transforms it and returns only the new, transformed data \cite{Augmentation}\cite{rotate}. We applied rotation by 0, 90, 180, and 270 degrees, tuned brightness and contrast between 0.9 to 1.1, applied horizontal flipping and clipped corners. Thirdly, to make the loss function converge faster, we changed our activation function from Relu to Leaky Relu. The latter avoids the problem with “dying neurons” which Relu activation functions suffer from: when a neuron “dies”, whichever input it receives, its output will be equal to 0; in that case a neuron loses prediction power and stops learning. Leaky Relu, however, has a small but non-zero gradient for inputs below 0. Fourthly, we applied a dropout function in the FPN layer to randomly drop out input nodes before doing classification and predicting bounding boxes. This decreases random correlations within neurons. It serves a similar purpose as data augmentation, i.e. to prevent overfitting \cite{dropout}. Fifthly, we changed the optimizer from stochastic gradient descent (SGD) to Adaptive Moment Estimation (Adam)\cite{Adam}. An optimizer aims to update parameters $\theta$ in the negative gradient direction to minimize the loss. Studies show that Adam has less generalization error compared to SGD as well as being able to tolerate a noisy or sparse gradient. The algorithm is denoted \begin{align*} m_t &= \beta_1 m_{t-1} + (1 - \beta_1) g_t \\ v_t &= \beta_2 v_{t-1} + (1 - \beta_2) g_t^2 \end{align*} where $m_t$ and $v_t$ are the decaying averages of the past gradient and past square gradient respectively, and the default value of each of the two $\beta$s is close to 1. We then update the estimates of both to deal with the bias caused by the initial averages $v=0$ and $m=0$: \begin{align*} \hat m_t &= \frac {m_t} {1 - \beta^t_1} \\ \hat v_t &= \frac {v_t} {1 - \beta^t_2}. \end{align*} Because we initialize averages with zeros, the estimators are biased towards zero. However, the author of Adam optimizer used the above formulas to correct the estimators. \cite{Adam} Then, using the updated parameters, the Adam update rule is: \[ \theta_{t+1} = \theta_t - \frac{\eta}{\sqrt{\hat v_t} + \epsilon}\hat m_t, \] where $\eta$ is the learning rate, and we choose (as part of our tuning of the model) $\epsilon = 10^{-8}$. Finally, we compare prediction results from fine-tune experiments (ex, activation function, dropout function, optimizer) to model without fine tune by visualizing loss history against epoch and a table reveals mean average precison (mAP) \cite{mAP}. \subsection{Loss function of Mask-RCNN} Loss functions are used to evaluate how well a model performs \cite{Loss} - in our case we aim to minimise a loss function by optimising weights for three different tasks: classification, bounding box prediction and mask prediction. We use a loss function which is the sum of a loss function for each of these tasks: \[ L = L_{\mathrm{cls}} + L_{\mathrm{box}} + L_{\mathrm{mask}} \] where $L_{\text{cls}}$ is the same as in Faster RCNN: \[ L_{\mathrm{cls}}( P_i, P^*_i ) = - \frac{1}{N_{\mathrm{cls}}}\left[P^*_i \log( P_i ) + (1 - P^*_i) \log( 1 - P_i )\right] \] where $P_i$ is the \emph{predicted} probability that the $i$th anchor is a target object. In Matterport Mask RCNN, the total number of anchors is 256 (positive and negative). The $i$th anchor above ``$i$th'' means a random number from 1 to 256. If an anchor contains target objects, the \emph{ground truth label} $P^*_i$ is equal to 1, and otherwise it is equal to 0. In addition, the function is normalised by $N_{\mathrm{cls}}$, i.e.\ the mini-batch size. A batch is the number of training samples in a given iteration. Overall, the classification loss $L_{\mathrm{cls}}$ is a log-loss over two classes (i.e.\ target object and not target object) which can be thought of as a binary classification loss (cross-entropy loss). In addition, $L_{\mathrm{box}}$ is also as in Faster RCNN: \[ L_{\mathrm{box}} = \frac{\lambda}{N_{\mathrm{cls}}} P_i \, R( (t_i - t^*_i )_{i \in \{ \mathrm{x,y,w,h} \})} \] where $R$ is a robust $L_1$ loss: \[ R(\mathbf{t}^u - \mathbf{v}) = \sum_{i \in \{ x,y,w,h \}} \mathrm{smooth}_{L_1} ( t^u_i - v_i ) \] and $t_i^{u}$ for $i \in \{ x,y,w,h \}$ are the position and dimension parameters of the predicted bounding box, $v_i$ the parameters of the ground truth box, $\lambda$ is a balancing parameter which is set to be around 10 in the paper (so that both losses $L_{\mathrm{cls}}$ and $L_{\mathrm{box}}$ are roughly equally weighted), and \[ \mathrm{smooth}_{L_1}( s ) = \left\{ \begin{matrix} 0.5 s^2 & \text{ if } |s| < 1, \\ |s| - 0.5 & \text{ otherwise.} \end{matrix} \right. \] We also have parameterised coordinates $t_i$ and $t^*_i$, \begin{align*} (t_i) &= ( t_x, t_y, t_w, t_h )\\ (t^*_i) &= (t^*_x, t^*_y, t^*_w, t^*_h) \end{align*} where each individual parameterised coordinate is calculated given the predicted bounding box, ground truth box and anchor box coordinates as \[ \begin{matrix} t_x = (x - x_\mathrm{a})/w_\mathrm{a}, & t_y = (y - y_\mathrm{a})/h_\mathrm{a},\\ \vspace{0.2cm} t_w = \log( w/w_\mathrm{a} ), & t_h = \log(h/h_\mathrm{a})\\ t_x^* = (x^* - x_\mathrm{a})/w_\mathrm{a}, & t_y^* = (y^* - y_\mathrm{a})/h_\mathrm{a}, \\ t_w^* = \log( w^*/w_\mathrm{a} ), & t_h^* = \log(h^*/h_\mathrm{a}), \end{matrix} \] where $(x_\mathrm{a}, y_\mathrm{a}, w_\mathrm{a}, h_\mathrm{a})$ are the coordinates of the anchor box. Finally, $L_{\mathrm{mask}}$ is the average binary cross-entropy loss which is calculated when the $k$th mask is the associated ground truth mask: \[ L_{\mathrm{mask}} = - \frac{1}{m^2} \sum_{1 \leq i,j \leq m} \left[ y_{ij} \log y_{ij}^k + (1 - y_{ij}) \log (1 - y_{ij}^k) \right] \] where $m \times m$ is the mask dimension for each ROI in each class, $y_{ij}$ is the ground truth label (0 or 1) in cell $(i, j)$ , while $y^k_{ij}$ is the predicted probability that the same cell belongs to the $k$th class \cite{Loss}. \section{Experiments} \subsection{Implement on Cloud Server with GPUs} A cloud server provides a virtual environment to perform computation which can be accessed remotely via internet. The major benefit is to overcome hardware limitation, for example, lack of disk space to store data or computing power to train models. In this study, in order to deal with the enormous amount of data and complicated algorithms, a cloud server(AWS) is chosen to provide the environment needed for the AI program (Mask RCNN). Once an AWS computing instance has been registered, a private key file is given access to cloud server. Then, a Tensorflow-GPU docker file is used to activate eight GPUs as well as giving the user a temporary environment with numerous pre-installed python libraries. After the training session is done, the post-trained files are transfered back to cloud server before closing docker environment and retrieve files to local computer. The training process takes about 4-6 hours for a dataset of 2000 to 4000 images. \subsection{Evaluation of prediction performance} As well as the loss function, we use COCO mean average precision (COCO mAP) to evaluate prediction performance \cite{mAP}. This indicator is widely used in evaluating models for object detection. Firstly, after IoU decides the ROIs, we calculate @mAP based on the prediction performance of those ROIs (ignoring objects with an IoU score lower than 50\%). Then we calculate the mean precision, recall and F1. Then the AP is calculated as the area under the precision-recall curve: the so-called Area Under Curve (AUC). The curve shows the trade-off relationship between precision and recall. When the area is larger, the predicted results are more accurate (numbers of false positives and false negatives are lower) and more positive cases are detected (number of false nagative is lower). In addition, in COCO AP, the AP averaged over IoU thresholds is calculated, i.e. AP50, AP75 and AP95. In COCO mAP, an average for a 101-point interpolated AP is calculated. This means recalls are divided into 101 points and their maximized precisions are averaged: \begin{align*} \mathrm{AP} &= \frac{1}{101} \sum_{r \in \{ 0,0,\cdots, 1,0 \}} \mathrm{AP}_r \\ &= \frac{1}{101} \sum_{r \in \{ 0,0,\cdots, 1,0 \}} P_{\mathrm{interp}}(r). \end{align*} To make an even more direct indicator, we also calculate the ROI number of two types of target objects (\autoref{fig:twotypes}) which will be revealed in the experimental results. \subsection{Experimental results and analysis} \label{sec:results} Because CNN can easily suffer from overfitting, we started training our model with a dataset of 2\,000 images and a validation set of 300 images, to which we applied many transformations. We then looked to increase the size of the dataset gradually to find the training set which gives us the most general model. We trained each model with 100 epochs with different hyperparameter settings. For the first pair of model, Fine-tune-1 and Fine-tune-2, the results showed that for the two types of targets (types A and B, see \autoref{fig:twotypes}) present in the data, ROI detection did not perform well for predicting type B objects (round shape) in the model ``Fine-tune-1''. However, the results also showed the opposite trend in model ``Fine-tune-2'', i.e. type B objects were detected reliably but few type A objects were. To resolve this, we decided to include more data in the next trial. \begin{figure}[h] \centering \includegraphics[width=0.2\textwidth]{images/typea} \includegraphics[width=0.2\textwidth]{images/typeb} \caption{The model ``Fine-tune-1'' can reveal the type A pattern (left) but not type B (right), and ``Fine-tune-2'' can reveal the type B pattern but not type A.} \label{fig:twotypes} \end{figure} \noindent For the next models, we reveal the evaluation statistics in \autoref {tab:performances}. Note that we make an abbreviation of "fine-tune" to "FT", for example, ``FT3'' is the model ``Fine-tune-3''. In addition, we indicate the best three performances for each measurement in bold: \begin{table} \resizebox{\columnwidth}{!}{% \begin{tabular}{|l||l|l|l|l|l|l|} \hline Model & FT3 & FT4 & FT5 & FT6 & FT7 & FT8 \\ \hline \hline AP50 & 0.39 & \textbf{0.57} & 0.43 & \textbf{0.54} & \textbf{0.60} & 0.38 \\ \hline AP75 & 0.14 & \textbf{0.53} & 0.13 & \textbf{0.48} & \textbf{0.56} & 0.10 \\ \hline mPrecision & 0.62 & \textbf{0.78}& 0.62 & \textbf{0.76}& \textbf{0.82} & 0.74\\ \hline mRecall & 0.35 & \textbf{0.39} & 0.35 & \textbf{0.40} & \textbf{0.41} & 0.34 \\ \hline mF1 & 0.29 & \textbf{0.32} & 0.28 & \textbf{0.33} & \textbf{0.34} & 0.28 \\ \hline Type A (star) & 40 & \textbf{59} & 33 & \textbf{69} & 32 & \textbf{53} \\ \hline Type B (round) & \textbf{71} & 24 & \textbf{64} & \textbf{74} & 24 & \textbf{64} \\ \hline \end{tabular}% } \caption{Comparison of the performance of the models. The best three performances for each measurement are in bold. The final two rows show bounding box numbers for the two types of target objects.} \label{tab:performances} \end{table} The table shows that results of FT6 are the best among all of the fine-tuned models. In addition, in \autoref{fig:all-loss} we plotted the loss results to see if FT6 had the lowest training and validation loss. \begin{figure}[h] \centering \includegraphics[width=0.23\textwidth]{images/model-train-loss} \includegraphics[width=0.237\textwidth]{images/model-val-loss} \caption{Training and validation loss for all models.} \label{fig:all-loss} \end{figure} Because FT7 has the lowest training loss and FT6 has lowest validation loss in \autoref{fig:all-loss}, we compared FT6 with FT7. \begin{figure} \centering \includegraphics[width=0.236\textwidth]{images/FT6loss} \includegraphics[width=0.235\textwidth]{images/FT7loss} \caption{Total loss for the models FT6 and FT7.} \label{fig:total-loss-ft6-7} \end{figure} FT7 had a constant higher learning rate of $10^{-3}$ which is the closest of all our models to Matterport's Mask RCNN default settings \cite{stepbystepprediction}, while FT6 followed the fast-medium-slow learning rate of $10^{-4}$-$10^{-5}$-$10^{-6}$. The results in \autoref{fig:total-loss-ft6-7} show that FT7 suffered from both fluctuating loss and overfitting. Overfitting happens when the training loss is less than the validation loss which means the algorithm learns local features appearing in the training set but not the validation set. This indicates that a fast and fixed learning rate in FT7 has no advantage over a learning rate which follows a convex pattern. In addition, there were two major trends in \autoref{fig:all-loss}: a big shift in the training loss, and two peaks in the validation loss. Because all models had different settings, especially in the different groups, we assumed that the enlarged data set helped decrease the training loss. In addition, for the validation loss, two peaks were made by FT1 and FT4, and so we believe that this may be because of their model setting (Relu + Adam + Dropout). The distributions of precision, recall and F1 from the model FT6 are shown below in \autoref{fig:distribution}. The diagrams show that FT6 has very high precision but a rather low recall. This means number of false negatives is higher than the number of false postive. \begin{figure}[h] \centering \includegraphics[width=0.5\textwidth]{images/FT6-3-scores} \caption{ Distributions of precision, recall and F1 score for FT6 (respectively). The x-axis counts the number of predicted bounding boxes while the y-axis records the precision, recall and F1 scores respectively. } \label{fig:distribution} \end{figure} \section{Discussion} \subsection{Advantages and disadvantages} \label{sec: Advantage} \label{sec: Disadvantage} \textbf{Advantages of our method} \begin{enumerate}[leftmargin=13pt] \item Efficently produces images and annotations: The synthetic method was designed by Adam Kelly to avoid a time-consuming image collection and annotation process. In Adam's experiment \cite{CreatingCOCODatasets}, he created 2000 images containing cigarette butts and their annotations in 20 minutes from only 25 samples. Because we had small numbers of data and no longer collected dead tree images when we started to train our algorithm, we chose the synthetic method rather than trying to find more remote sensor data. \item Less complex to apply compared to MaxEnt algorithm in CanHeMon project: According to the image pre-processing section of the CanHeMon project, there are 14 potential predictor variables related to texture layer, containing significant image information. Then, after a series of background and AUC setting, the MaxEnt algorithm and principal component analysis are applied to reduce the number of superfluous variables. However, when applying CNN based algorithm, the variables used as inputs and ouputs are rather simple: raw images and their labels. There is no manual elimination process for the variables/features but the algorithm automatically adjusts feature weights after backpropagation in each iteration. \item False positive cases are rare: The CanHeMon project suffered from a high rate of false positives, which does not occur in our Mask RCNN-based model. In the CanHeMon experiment, researchers manually removed false postive cases and fed the data back to the training session. However, the mask results from our model rarely showed false postive cases, although there were still many areas of dead trees which were not detected. We found that a decrease in the IoU threshold can help detect more dead trees, and therefore decrease the number of false negatives. Changing a hyperparameter in this way requires less manual effort than manually dropping FP cases. \end{enumerate} \noindent\textbf{Disadvantages of our method} \begin{enumerate}[leftmargin=13pt] \item Data scarcity: We gathered all of the images of dead trees we could from both online resources and our partner company 2Excel. However, we did not generate enough data to overcome the problems caused by data scarcity, as dead trees are an uncommon object, whereas most image datasets collect everyday objects (cars, people, etc.). The main problem was that there were several shapes of dead tree in our raw data (see the two types in \autoref{fig:twotypes}) but we could not generate a sufficient number of images to deal with this variety. \item The process of producing COCO format annotations did not give clear boundaries in synthetic images: \label{item:synthetic-borders} The synthetic method we used sometimes led to target objects being divided into more than one piece by another object overlapping them. For example, see the red region in \autoref{fig:divided-region}. We had to manually drop the label when this happened, which is time consuming, reducing the benefit in time savings we gained from using the synthetic method. The overlapping type B dead trees give us inaccurate bounding box predictions. \begin{figure} \centering \includegraphics[width=0.2\textwidth]{images/broken-process02} \includegraphics[width=0.2\textwidth]{images/broken-process01} \caption{A target object in this synthetic image is divided in two by another object placed on top of it.} \label{fig:divided-region} \end{figure} \item Predicted bounding boxes failing to accurately cover a whole region of dead wood Our synthetic method can make target objects overlap, and if they belong to type A (star shaped) then the algorithm will fail to distinguish the objects from each other, as in \autoref{fig:box-failure}. At best, they are bound to a larger group and given a single label. \begin{figure} \centering \includegraphics{images/bbox-didnotaccurately} \caption{Several target objects of type A being assigned to a single bounding box.} \label{fig:box-failure} \end{figure} \item Reliability of mAP and other statistics The mAP scores in our results were still not as reliable as the ones produced and evaluated using a raw (not synthetic) validation set. The synthetic validation set was necessary because of the scarce data, but it would be ideal to use only raw images for validation if possible. \end{enumerate} \subsection{Suggestions for future research} In this research, we only trained our model with the company's aerial dataset instead of the Landsat dataset; however, we welcome to reseachers apply Mask RCNN to the Landset datset to make comparison with our results. In addition, we did not take into account other variables such as the forest phenology in our model, because the aerial dataset was collected in summer time (May 15th 2019) when living trees are easily distinguished from dead trees. However, we cannot exclude the possibility that Mask RCNN detects and labels as ``dead'' rare species of trees who naturally have white leaves. Because of that, we encourage researchers to apply other possible features in their models rather than only relying on an image processing algorithm. Secondly, to mitigate the disadvantage of data scarcity, we enlarged our dataset and produced labels automatically using a synthetic method. However, we pointed out some issues with this method in \autoref{sec: Disadvantage}, although recent updates to the code we were using have dealt with some of the issues we saw in \autoref{item:synthetic-borders} of the disadvantages in \autoref{sec: Disadvantage}. As Adam Kelly suggested \cite{CreatingCOCODatasets}, it is still necessary to evaluate the advantages and disadvantages of using synthetic data to train a model. The issue with bounding box inaccuracy is the major contributor to the high loss in RPN. \label{subsec:lossofRPN} A possible solution is using a single FCN to classify each pixel if the instance-level segmentation is not necessary. Then, we could change the loss function from bbox + mask to FCN loss, decreasing the probability of high loss and enabling a more flexible and accurate prediction because mask prediction is not limited by the selected ROIs' areas. One other notable issue we experienced was how to increase the reliability of statistics (accuracy, mAP, mRecall and mF1) which were produced using the synthetic validations set to be consistent with the model's predictive power on raw images. However, if we were able to collect a sufficiently large, manually annotated dataset, the statistics would be much more reliable. In addition, if the synthetic training set is replaced by manually-annotated raw data, it could increase the predictive power since the synthetic data may not include features which are present in the raw data. In the conventional training process, a single optimizer is used in a model. However, to take advantage of the merits of different optimizers, the author in \cite{ImprovingGeneralization01} used ADAM first, and when the loss stopped decreasing, replaced ADAM with SGD. The results obtained by doing this were better than those obtained using either optimizer on its own. After reading this, we performed the same experiment with our model. As \autoref{fig:two-classifier-experiment} shows, replacing SGD with ADAM at the 30th epoch led to a sudden drop in the loss function. As it is hard to compare directly with the other models we tested, we did not include this model in \autoref{tab:finetunesettings}, but the results of our experiment are encouraging, so we would suggest that future research should look into using multiple optimizers for training.\\ \begin{figure}[h] \centering \includegraphics[width=0.236\textwidth]{images/mix} \caption{The loss functions obtained by using an SGD optimiser until epoch 30, and then using ADAM.} \label{fig:two-classifier-experiment} \end{figure} \autoref{fig:extra-examples} shows more of our test results. Mostly the detection framework works well on these images while the training process was carried out on the same dataset. However, there is yet a gap between the expected detection accuracy and the performance of our deep learning framework, and further improvement is needed to extend our framework to practical applications. \begin{figure} \centering \includegraphics[width=0.150\textwidth]{images/mask-vis/05} \includegraphics[width=0.150\textwidth]{images/mask-vis/06} \includegraphics[width=0.150\textwidth]{images/mask-vis/07} \includegraphics[width=0.150\textwidth]{images/mask-vis/08} \includegraphics[width=0.150\textwidth]{images/mask-vis/19} \includegraphics[width=0.150\textwidth]{images/mask-vis/25} \includegraphics[width=0.150\textwidth]{images/mask-vis/27} \includegraphics[width=0.150\textwidth]{images/mask-vis/32} \includegraphics[width=0.150\textwidth]{images/mask-vis/33} \includegraphics[width=0.150\textwidth]{images/mask-vis/34} \includegraphics[width=0.150\textwidth]{images/mask-vis/39} \includegraphics[width=0.150\textwidth]{images/mask-vis/46} \includegraphics[width=0.150\textwidth]{images/mask-vis/47} \includegraphics[width=0.150\textwidth]{images/mask-vis/50} \includegraphics[width=0.150\textwidth]{images/mask-vis/58} \includegraphics[width=0.150\textwidth]{images/mask-vis/62} \includegraphics[width=0.150\textwidth]{images/mask-vis/63} \includegraphics[width=0.150\textwidth]{images/mask-vis/67} \includegraphics[width=0.150\textwidth]{images/mask-vis/68} \includegraphics[width=0.150\textwidth]{images/mask-vis/69} \includegraphics[width=0.150\textwidth]{images/mask-vis/71} \includegraphics[width=0.150\textwidth]{images/mask-vis/72} \includegraphics[width=0.150\textwidth]{images/mask-vis/74} \includegraphics[width=0.150\textwidth]{images/mask-vis/75} \caption{More test results on aerial images.} \label{fig:extra-examples} \end{figure} The limits can be ascribed to two aspects. First, deep neural networks has been reported not robust to noises and other similar perturbations (adversary attacks)\cite{jiang2019access01}, while DNNs are somehow lack of explicit explanability unlike typical statistic approaches that model the data space explicitly \cite{jiang2017pr}\cite{jiang2010tifs}\cite{jiang2010tbme}\cite{jiang2010tsmc}. Secondly, DNNs are date-driven and heavily rely on training datasets \cite{lecun2015nature}\cite{jiang2017htl}\cite{jiang2019access02}\cite{jiang2019access03}. In our experiments, we have a limited amount of data samples. A typical remedy to this issue can be based on the neural network models of Generative Adversarial Networks (GANs)\cite{GANs}, which can generate more similar images similar to real ones to improve the training process. Targeting at dead wood detection, our work is based on the assumption that the dead tree dataset collected in the spring-summer period have different colors in leaves. However, this may vary according to tree species and some rare specious of trees may naturally have white leaves during four seasons. A future work can include forest phenology and classify the species of trees before the dead wood detection. \section{Conclusion} In conclusion, we present a new framework for automated dead tree detection from aerial images using a re-trained Mask RCNN approach, with a transfer learning scheme. We apply our framework to our aerial imagery datasets, and compare eight fine-tuned models. The mean average precision score (mAP) for the best of these models reaches 54\%. We also are able to automatically produce mask visualizations to label the dead trees in an image, so that the number of dead trees in a region can be automatically counted. Such aerial image-based forest analysis can give an early diagnosis of the conditions of forests and identify potential risk factors, and provide an potential solution to avoid of climate change caused disasters such as the recent forest fires in the California and Australia. \section*{Acknowledgements} This work was supported in part by the EPSRC grant (EP/P009727/1). \bibliographystyle{IEEEtran}
{'timestamp': '2020-10-19T02:19:15', 'yymm': '2010', 'arxiv_id': '2010.08437', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08437'}
arxiv
\section{Introduction}\label{sec:intro} Persistent homology is a central tool in Topological Data Analysis that allows to efficiently infer relevant topological features of complex data in a descriptor called persistence diagram. It found many applications in Machine Learning (ML) where it initially played the role of a feature engineering tool through the direct use of persistence diagrams, or through dedicated ML architectures to handle them---see, e.g., \cite{hofer2017deep,umeda2017time, carriere2020perslay,dindin2020topological, kim2020efficient}. For the last few years, a growing number of works have been successfully using persistence theory in different ways in order to, for instance, better understand, design and improve neural network architectures---see, e.g., \cite{rieck2018neural,moor2019topological,carlsson2020topological,gabrielsson2019exposition}---or design regularization and loss functions incorporating topological terms and penalties for various ML tasks---see, e.g., \cite{chen2019topological, hofer2019connectivity, clough2020topological}. These new use cases of persistence generally involve minimizing functions that depend on persistence diagrams. Such functions are in general highly non-convex and not differentiable, and thus their theoretical and practical minimization can be difficult. In some specific cases, persistence-based functions can be designed to be differentiable and/or some effort have to be made to compute their gradient, so that standard gradient descent techniques can be used to minimize them---see e.g., \cite{wangtopogan,poulenard2018topological, bruel2020topology}. In the general case, recent attempts have been made to better understand their differential structures~\cite{leygonie2019framework}. Moreover, building on powerful tools provided by software libraries such as PyTorch or TensorFlow, practical methods allowing to encode and optimize a large family of persistence-based functions have been proposed and experimented~\cite{gabrielsson2020topology, solomon2020fast}. However, in all these cases, the algorithms used to minimize these functions do not come with theoretical guarantees of convergence to a global or local minimum. \paragraph{Contributions and organization of the article.} The aim of this article is to provide a general framework that includes almost all persistence-based functions from the literature, and for which stochastic subgradient descent algorithms are easy to implement and come with convergence guarantees. More precisely, we first observe that the persistence map, converting a filtration over a given simplicial complex \footnote{The presentation is restricted to simplicial complexes for simplicity, but this generalizes to other complexes as well. We present an example with cubical complexes in Appendix.} into a persistence diagram, can be thought of as a map between Euclidean spaces (\cref{sec:filt}). This observation allows us to prove that the persistence map is semi-algebraic and, using classical arguments from o-minimal geometry, to study the differentiability of the persistence of parametrized families of filtrations (\cref{sec:ominim}). Then, building on the recent work \cite{subgradient}, we consider the minimization problem of persistence-based functions and show that under mild assumptions, stochastic subgradient descent algorithms applied to such functions converge almost surely to a critical point (\cref{sec:funcs}). We also provide a simple corresponding Python implementation\footnote{\url{https://github.com/MathieuCarriere/difftda.git}} for minimizing functions of persistence, and we illustrate it with several examples from the literature (\cref{sec:implementation}). \section{Filtrations and persistence diagrams} \label{sec:filt} In this section, we show that the persistence map is nothing but a permutation of the coordinates of a vector containing the filtration values. \subsection{Simplicial complexes and filtrations} Recall that given a set $V$, a (finite) \emph{simplicial complex} $K$ is a collection of finite subsets of $V$ that satisfies (1) $\{v \} \in K$ for any $v \in V$, and (2) if $\sigma \in K$ and $\tau \subseteq \sigma$ then $\tau \in K$. An element $\sigma \in K$ with $|\sigma|=k+1$ is called a $k$-simplex. Given a simplicial complex $K$ and a subset $R$ of $\ensuremath{\mathbb{R}}$, a \emph{filtration} of $K$ is an increasing sequence $(K_r)_{r \in R}$ of subcomplexes of $K$ with respect to the inclusion, i.e., $K_r \subseteq K_s$ for any $r \leq s$, and such that $\bigcup_{r \in R} K_r = K$. To each simplex $\sigma \in K$, one can associate its \emph{filtering index} $\Phi_\sigma = \inf \{ r \in R: \sigma \in K_r \}$. Thus, when $K$ is finite, a filtration of $K$ can be conveniently represented as a filtering function $\Phi \colon K \to \ensuremath{\mathbb{R}}$. Equivalently, it can be represented as a $|K|$-dimensional vector $\Phi = (\Phi_\sigma)_{\sigma \in K}$ in $\mathbb{R}^{|K|}$ whose coordinates are the indices of the simplices of $K$ and that satisfies the following condition: if $\sigma, \tau \in K$ and $\tau \subseteq \sigma$, then $\Phi_\tau \le \Phi_\sigma$. As a consequence, if the vectorized filtration $\Phi$ depends on a parameter, the corresponding family of filtrations can be represented as a map from the space of parameters to $\ensuremath{\mathbb{R}}^{|K|}$ in the following way. \begin{definition} \label{def:parametrized_filtrations} Let $K$ be a simplicial complex and $A$ a set. A map $\Phi \colon A \to \ensuremath{\mathbb{R}}^{|K|}$ is said to be a \emph{parametrized family of filtrations} if for any $x \in A$ and $\sigma, \tau \in K$ with $\tau \subseteq \sigma$, one has $\Phi_\tau(x) \le \Phi_\sigma(x)$. \end{definition} \subsection{Persistence computation from filtrations} \label{compute-pers} We briefly recall how the computation of the persistence diagram of a filtered simplicial complex decomposes into: (i)~a purely combinatorial part only relying on the order on the simplices induced by the filtration, and (ii)~a part relying on the filtration values. A detailed introduction to persistent homology and its computation can be found in, e.g., \cite{edelsbrunner2010computational,boissonnat2018geometric}. Let $K$ be a simplicial complex endowed with a filtration and corresponding filtering function $\Phi \in \ensuremath{\mathbb{R}}^{|K|}$, where $|K|$ is the number of non-empty simplices of $K$. \paragraph{First part: combinatorial part (persistence pairs).} The filtering function $\Phi$ induces a total preorder on the elements of $K$ as follows: $\tau \preceq \sigma$ if $\Phi_\tau \leq \Phi_\sigma$. This preorder can be refined into a total order by breaking ties in some fairly arbitrary way, as long as it is consistent with the face relation, i.e., if $\tau\subseteq\sigma$, then $\tau \preceq \sigma$. One way to break ties is to sort simplices that have the same filtration value by dimension, and then order the ones that are still equivalent according to some arbitrary indexing of the simplices. A different way is to index the vertices, represent simplices by their decreasing list of vertices, and sort equivalent simplices using the lexicographic order on those lists. In the following, we will assume that the total order is a function of the preorder, in particular it is deterministic and does not depend on the exact values of $\Phi$. Note that while different orders may yield different pairings, they all translate to the same persistence diagram in the second part. The basic algorithm to compute persistence iterates over the ordered set of simplices $\sigma_1 \preceq \dots \preceq \sigma_{|K|}$ according to \cref{alg:persistent-pairs} below---see Section~11.5.2 in \cite{boissonnat2018geometric} for a detailed description of the algorithm. \begin{algorithm}[ht] \caption{Persistence pairs computation (sketch)} \label{alg:persistent-pairs} \begin{algorithmic} \STATE{\bf Input:} Ordered sequence of simplices $\sigma_1 \preceq \dots \preceq \sigma_{|K|}$ \STATE $K_0 = \emptyset$ \STATE $\mathrm{Pairs}_0 = \mathrm{Pairs}_1 = \dots = \mathrm{Pairs}_{d-1} = \emptyset$ \FOR{$j=1$ to $|K|$} \STATE $k = \dim \sigma_j$ \STATE $K_j = K_{j-1} \cup \sigma_j$ \IF{$\sigma_j$ does not create a new $k$-dimensional homology class in $K_j$} \STATE a $(k-1)$-dimensional homology class created in $K_{l(j)}$ by $\sigma_{l(j)}$ for some $l(j) < j$ becomes homologous to $0$ in $K_j$. \STATE $\mathrm{Pairs}_{k-1} \gets \mathrm{Pairs}_{k-1} \cup \{ (\sigma_{l(j)}, \sigma_j) \}$; \ENDIF \ENDFOR \STATE{\bf Output:} Persistence pairs in each dimension $\mathrm{Pairs}_0, \mathrm{Pairs}_1, \dots, \mathrm{Pairs}_{d-1}$ \end{algorithmic} \end{algorithm} Note that for each dimension $k$, some $k$-dimensional simplices may remain unpaired at the end of the algorithm; their number is equal to the $k$-dimensional Betti number of $K$. \paragraph{Second part: associated filtration values.} The persistence diagram of the filter function $\Phi$ is now obtained by associating to each persistent pair $(\sigma_{l(j)}, \sigma_j)$ the point $(\Phi_{\sigma_{l(j)}}, \Phi_{\sigma_j})$. Moreover, to each unpaired simplex $\sigma_l$ is associated the point $(\Phi_{\sigma_l},+\infty)$. If $p$ is the number of persistence pairs and $q$ is the number of unpaired simplices, then $|K|=2p+q$ and the persistence diagram $D(\Phi)$ of the filtration $\Phi$ of $K$ is made of $p$ points in $\ensuremath{\mathbb{R}}^2$ (counted with multiplicity) and $q$ points (also counted with multiplicity) with infinite second coordinate. Choosing the lexicographical order on $\ensuremath{\mathbb{R}} \times (\ensuremath{\mathbb{R}} \cup \{+\infty \})$, the persistence diagram $D(\Phi)$ can be represented as a vector in $\ensuremath{\mathbb{R}}^{|K|}$ and the output of the persistence algorithm can be simply seen as a permutation of the coordinates of the input vector $\Phi$. Moreover, this permutation only depends on the order on the simplices of $K$ induced by $\Phi$. \begin{definition}\label{def:regess} The subset of points of a persistence diagram $D$ with finite coordinates (resp.\ infinite second coordinate) is called the \emph{regular part} (resp.\ \emph{essential part}) of $D$ and denoted by $D_{\mathrm{reg}}$ (resp.\ $D_{\mathrm{ess}}$). \end{definition} With the notations defined above, $D_{\mathrm{reg}}$ and $D_{\mathrm{ess}}$ can be represented as vectors in $\ensuremath{\mathbb{R}}^{2p}$ and $\ensuremath{\mathbb{R}}^q$, respectively. Note that, in practice, the above construction is usually done dimension by dimension to get a persistence diagram for each dimension in homology, by restricting to the subset of simplices of dimension $k$ and $k+1$. Without loss of generality, and to avoid unnecessary heavy notation, in the following we consider the whole persistence diagram, made of the union of the persistence diagrams in all dimensions~$k$. \begin{comment} \begin{remark} Note that, in practice, the above construction is usually done dimension by dimension, leading to a single persistence diagram for each dimension in homology. Indeed, in order to obtain a persistence diagram in dimension $k$, it suffices to restrict to the subset of simplices of dimension $k$ and $k+1$. Without loss of generality, and to avoid unnecessary heavy notation, in the remaining of this article, we consider the whole persistence diagram, made of the union of the persistence diagrams in all dimensions~$k$. \end{remark} \end{comment} \section{Differentiability of functions of persistence}\label{sec:ominim} o-minimal geometry provides a well-suited setting to describe the parametrized families of filtrations encountered in practice and to exhibit interesting differentiability properties of their composition with the persistence map. \subsection{Background on o-minimal geometry} In this section, we recall some elements of o-minimal geometry, which are needed in the next sections---see, e.g., \cite{coste2000introduction} for a more detailed introduction. \begin{definition}[o-minimal structure] An \emph{o-minimal structure} on the field of real numbers $\mathbb{R}$ is a collection $(S_n)_{n \in \mathbb{N}}$, where each $S_n$ is a set of subsets of $\mathbb{R}^n$ such that: \begin{enumerate} \itemsep -0.1cm \item $S_1$ is exactly the collection of finite unions of points and intervals; \item all algebraic subsets\footnote{Recall that an algebraic set is the $0$-level set of a polynomial.} of $\mathbb{R}^n$ are in $S_n$; \item $S_n$ is a Boolean subalgebra of $\ensuremath{\mathbb{R}}^n$ for any $n \in \mathbb{N}$; \item if $A \in S_n$ and $B \in S_m$, then $A \times B \in S_{n+m}$; \item if $\pi \colon \ensuremath{\mathbb{R}}^{n+1} \to \ensuremath{\mathbb{R}}^n$ is the linear projection onto the first $n$ coordinates and $A \in S_{n+1}$, then $\pi(A) \in S_n$. \end{enumerate} \end{definition} An element $A \in S_n$ for some $n \in \mathbb{N}$ is called a \emph{definable set} in the o-minimal structure. For a definable set $A \subseteq \ensuremath{\mathbb{R}}^n$, a map $f \colon A \to \ensuremath{\mathbb{R}}^m$ is said to be \emph{definable} if its graph is a definable set in $\ensuremath{\mathbb{R}}^{n+m}$. Definable sets are stable under various geometric operations. The complement, closure and interior of a definable set are definable sets. The finite unions and intersections of definable sets are definable. The image of a definable set by a definable map is itself definable. Sums and products of definable functions as well as compositions of definable functions are definable---see Section~1.3 in \cite{coste2000introduction}. In particular, the $\max$ and $\min$ of finite sets of real-valued definable functions are also definable. An important property of definable sets and definable maps is that they admit a finite Whitney stratification. This implies that (i)~any definable set $A \subseteq \ensuremath{\mathbb{R}}^n$ can be decomposed into a finite disjoint union of smooth submanifolds of $\ensuremath{\mathbb{R}}^n$ and (ii)~for any definable map $\Phi \colon A \to \ensuremath{\mathbb{R}}^m$, $A$ can also be decomposed into a finite union of smooth manifolds such that the restriction of $\Phi$ on each of these manifolds is a differentiable function. The simplest example of o-minimal structures is given by the family of semi-algebraic subsets\footnote{It is the family of all finite unions and intersections of level sets and sublevel sets of polynomials \cite{benedetti1991real}.} of $\ensuremath{\mathbb{R}}^n \ (n \in \mathbb{N})$. Although most of the classical parametrized families of filtrations are semi-algebraic, the o-minimal framework actually allows to consider larger families. In particular, the result of \cite{wilkie1996model} says that the family of images of the sublevel sets of functions in $\ensuremath{\mathbb{R}}[x_1,\dots,x_N,\exp(x_1),\dots,\exp(x_N)]$ for some $N \in \mathbb N$ under linear projections is an o-minimal structure, which allows us to mix exponential functions with semi-algebraic functions. \subsection{Persistence diagrams of definable parametrized families of filtrations}\label{sec:pers} Let $K$ be a simplicial complex and $\Phi \colon A \to \ensuremath{\mathbb{R}}^{|K|}$ be a parametrized family of filtrations that is definable in a given o-minimal structure. If for any $x, x' \in A$, the preorders induced by $\Phi(x)$ and $\Phi(x')$ on the simplices of $K$ are the same, i.e., for any $\sigma_1, \sigma_2 \in K$, $ \Phi_{\sigma_1}(x) \leq \Phi_{\sigma_2}(x)$ if and only if $\Phi_{\sigma_1}(x') \leq \Phi_{\sigma_2}(x')$, then the pairs of simplices $(\sigma_{i_1},\sigma_{j_1}), \dots , (\sigma_{i_p},\sigma_{j_p})$, and the unpaired simplices $\sigma_{i_{p+1}},\dots, \sigma_{i_{p+q}}$ that are computed by the persistence \cref{alg:persistent-pairs} are independent of $x$. As a consequence, the persistence diagram $D = D(\Phi(x))$ of $\Phi(x)$ is \begin{align} \label{eq:diff_dgm} D = \bigcup_{k=1}^p (\Phi_{\sigma_{i_k}}(x),\Phi_{\sigma_{j_k}}(x)) \cup \bigcup_{k=1}^q (\Phi_{\sigma_{i_{p+k}}}(x),+\infty), \end{align} where $|K|=2p+q$. Given the lexicographic order on $\ensuremath{\mathbb{R}} \times (\ensuremath{\mathbb{R}} \cup \{+\infty \})$, the points of any finite multi-set $D \subseteq \ensuremath{\mathbb{R}} \times (\ensuremath{\mathbb{R}} \cup \{+\infty \})$ with $p$ points in $\ensuremath{\mathbb{R}}^2$ and $q$ points in $\ensuremath{\mathbb{R}} \times \{ +\infty \}$ can be ordered in non-decreasing order, and $D$ can be represented as a vector in $\ensuremath{\mathbb{R}}^{2p+q}$. As a consequence, denoting by $\mathrm{Filt}_K$ the set of vectors in $\ensuremath{\mathbb{R}}^{|K|}$ defining a filtration on $K$, the persistence map $\mathrm{Pers} \colon \mathrm{Filt}_K \to \ensuremath{\mathbb{R}}^{|K|}$ that assigns to each filtration of $K$ its persistence diagram consists in a permutation of the coordinates of $\ensuremath{\mathbb{R}}^{|K|}$. This permutation is constant on the set of filtrations that define the same preorder on the simplices of $K$. This leads to the following statement. \begin{proposition} \label{lemma:semi-alg-persistence} Given a simplicial complex $K$, the map $\mathrm{Pers} \colon \mathrm{Filt}_K \subseteq \ensuremath{\mathbb{R}}^{|K|} \to \ensuremath{\mathbb{R}}^{|K|}$ is semi-algebraic, and thus definable in any o-minimal structure. Moreover, there exists a semi-algebraic partition of $\mathrm{Filt}_K$ such that the restriction of $\mathrm{Pers}$ to each element of this partition is a Lipschitz map. \end{proposition} \begin{proof} See Appendix. \end{proof} Since there exists a finite semi-algebraic partition of $\mathrm{Filt}_K$ on which $\mathrm{Pers}$ is a locally constant permutation, the subdifferential (see \cref{sec:funcs} for the definition) of $\mathrm{Pers}$ is well-defined and obvious to compute: each coordinate in the output (i.e., the persistence diagram) is a copy of a coordinate in the input (i.e., the filtration values of the simplices). This implies that every partial derivative is either 1 or 0. The output can be seen as a reindexing of the input, and this is indeed how we implement it in our code, so that automatic differentiation frameworks (PyTorch, TensorFlow, etc.) can process the function $\mathrm{Pers}$ directly and do not need explicit gradient formulas---see \cref{sec:implementation}. Note that the subdifferential depends on the arbitrary refinement of the preorder in \cref{compute-pers}. \begin{corollary} Let $K$ be a simplicial complex and $\Phi \colon A \to \ensuremath{\mathbb{R}}^{|K|}$ be a definable (in a given o-minimal structure) parametrized family of filtrations. The map $\mathrm{Pers} \circ \Phi \colon A \to \ensuremath{\mathbb{R}}^{|K|}$ is definable. \end{corollary} Note that according to the remark following \cref{lemma:semi-alg-persistence}, if $\Phi$ is differentiable, the subdifferential of $\mathrm{Pers} \circ \Phi$ can be easily computed in terms of the partial derivatives of $\Phi$ using, for example, \cref{eq:diff_dgm}. It also follows from standard finiteness and stratifiability properties of definable sets and maps that $\mathrm{Pers} \circ \Phi$ is differentiable almost everywhere. More precisely: \begin{proposition} \label{thm:diff_semialg} Let $K$ be a simplicial complex and $\Phi \colon A \to \ensuremath{\mathbb{R}}^{|K|}$ a definable parametrized family of filtrations, where $\dim A = m$. Then there exists a finite definable partition of $A$, $A = S \sqcup O_1 \sqcup \dots \sqcup O_k$ such that $\dim S < \dim A := m$ and, for any $i=1,\dots,k$, $O_i$ is a definable manifold of dimension $m$ and $\mathrm{Pers} \circ \Phi \colon O_i \to \ensuremath{\mathcal{D}}$ is differentiable. \end{proposition} \begin{comment} \begin{proposition} \label{thm:diff_semialg} Let $K$ be a simplicial complex and $\Phi \colon A \to \ensuremath{\mathbb{R}}^{|K|}$ a definable parametrized family of filtrations. Then there exists a finite definable partition of $A$, $A = S \sqcup O_1 \sqcup \dots \sqcup O_k$ such that \begin{enumerate} \item $\dim S < \dim A := m$; \item for any $i=1,\dots,k$, $O_i$ is a definable manifold of dimension $m$ and $\mathrm{Pers} \circ \Phi \colon O_i \to \ensuremath{\mathcal{D}}$ is differentiable. \end{enumerate} \end{proposition} \end{comment} \subsection{Examples of definable families of filtrations}\label{sec:exs} \paragraph{Vietoris-Rips filtrations.} The family of Vietoris-Rips filtrations built on top of sets of $n$ points $x_1, \dots, x_n \in \ensuremath{\mathbb{R}}^d$ is the semi-algebraic parametrized family of filtrations \begin{align} \Phi \colon A = (\ensuremath{\mathbb{R}}^d)^n \to \ensuremath{\mathbb{R}}^{|\Delta_n|} = \ensuremath{\mathbb{R}}^{2^n-1}, \end{align} where $\Delta_n$ is the simplicial complex made of all the faces of the $(n-1)$-dimensional simplex, defined, for any $x=(x_1, \dots, x_n) \in A$ and any simplex $\sigma \subseteq \{1, \dots, n\}$, by \begin{align} \Phi_\sigma(x) = \max_{i,j \in \sigma} \| x_i - x_j \|. \end{align} One easily checks that the permutation induced by $\mathrm{Pers}$ is constant on the connected components of the complement of the union of the subspaces $S_{i,j,k,l} = \{(x_1, \dots, x_n) : \| x_i - x_j \| = \| x_k - x_l \| \}$ over all the $4$-tuples $(i,j,k,l)$ such that at least $3$ of the $4$ indices $i,j,k,l$ are distinct. This example naturally extends to Vietoris-Rips-like filtrations in the following way. Let $A \subset \ensuremath{\mathcal{M}}_n(\ensuremath{\mathbb{R}})$ be the set of $n \times n$ symmetric matrices with non-negative entries and $0$ on the diagonal. This is a semi-algebraic subset of the space of $n$-by-$n$ matrices $\ensuremath{\mathcal{M}}_n(\ensuremath{\mathbb{R}}) \simeq \ensuremath{\mathbb{R}}^{n^2}$, of dimension $m = (n-1)(n-2)/2$. The map $\Phi \colon A \to \ensuremath{\mathbb{R}}^{|\Delta_n|} = \ensuremath{\mathbb{R}}^{2^n}$ defined by $\Phi_\sigma(M) = \max_{i,j \in \sigma} m_{i,j}$ for any $M = (m_{i,j})_{1 \leq i,j \leq n} \in A$, is a semi-algebraic family of filtrations. Note that the set $S$ of \cref{thm:diff_semialg} can be chosen to be the set of matrices with at least $2$ entries that are equal. \paragraph{Weighted Rips filtrations.} Given a function $f \colon \ensuremath{\mathbb{R}}^d \to \ensuremath{\mathbb{R}}$, the family of weighted Rips filtrations $\Phi \colon A = (\ensuremath{\mathbb{R}}^d)^n \to \ensuremath{\mathbb{R}}^{|\Delta_n|} = \ensuremath{\mathbb{R}}^{2^n}$ associated to $f$ is defined, for any $x=(x_1, \dots, x_n) \in A$ and any simplex $\sigma \subseteq \{1, \dots, n \}$, by \begin{itemize} \item $\Phi_\sigma(x) = 2 f(x_j)$ if $\sigma = [j]$; \item $\Phi_\sigma(x) = \max(2 f(x_i), 2 f(x_j), \| x_i - x_j \| + f(x_i) + f(x_j))$, if $\sigma = [i,j]$, $i \not = j$; \item $\Phi_\sigma(x) = \max( \Phi_{[i,j]}(x), i,j \in \sigma)$ if $|\sigma| \geq 3$. \end{itemize} Since Euclidean distances and $\max$ function are semi-algebraic, this family of filtrations is definable as soon as the weight function $f$ is definable. This example easily extends to the case where the weight function depends on the set of points $x = ( x_1, \dots, x_n )$: the weight at vertex $y$ is defined by $f(x,y)$ with $f \colon (\ensuremath{\mathbb{R}}^d)^n \times \ensuremath{\mathbb{R}}^d \to \ensuremath{\mathbb{R}}$. A particular example of such a family is given by the so-called DTM filtration \cite{anai2020dtm}, where $f(x,y)$ is the average distance from $y$ to its $k$-nearest neighbors in $x$. In this case, $f$ is semi-algebraic, and the family of DTM filtrations is semi-algebraic. The o-minimal framework also allows us to consider weight functions involving exponential functions \cite{wilkie1996model}, such as, for instance, kernel-based density estimates with Gaussian kernels. \paragraph{Sublevel sets filtrations.} Let $K$ be a simplicial complex with $n$ vertices $v_1, \dots, v_n$. Any real-valued function $f$ defined on the vertices of $K$ can be represented as a vector $(f(v_1), \dots, f(v_n)) \in \ensuremath{\mathbb{R}}^n$. The family of sublevel sets filtrations $\Phi \colon A=\ensuremath{\mathbb{R}}^n \to \ensuremath{\mathbb{R}}^{|K|}$ of functions on the vertices of $K$ is defined by $\Phi_\sigma(f) = \max_{i \in \sigma} f_i$ for any $f = (f_1, \dots, f_n) \in A$ and any simplex $\sigma \subseteq \{1, \dots, n\}$. This filtration is also known as the \emph{lower-star filtration} of $f$. The function $\Phi$ is obviously semi-algebraic, and for \cref{thm:diff_semialg} it is sufficient to choose $S = \bigcup_{1 \leq i < j \leq n} \{ f = (f_1, \dots, f_n) \in A: f_i = f_j \}$. \section{Minimization of functions of persistence}\label{sec:funcs} Using the same notation as in the previous section, recall that the space of persistence diagrams associated to a filtration of $K$ is identified with $\ensuremath{\mathbb{R}}^{|K|} = (\ensuremath{\mathbb{R}}^2)^p \times \ensuremath{\mathbb{R}}^q$, where each point in the $p$ copies of $\ensuremath{\mathbb{R}}^2$ is a point with finite coordinates in the persistence diagram and each coordinate in $\ensuremath{\mathbb{R}}^q$ is the $x$-coordinate of a point with infinite persistence. \begin{definition} \label{def:fn-pers} A function $E \colon \ensuremath{\mathbb{R}}^{|K|} = (\ensuremath{\mathbb{R}}^2)^p \times \ensuremath{\mathbb{R}}^q \to \ensuremath{\mathbb{R}}$ is said to be a \emph{function of persistence} if it is invariant to permutations of the points of the persistence diagram: for any $(p_1, \dots, p_p, e_1, \dots, e_q) \in (\ensuremath{\mathbb{R}}^2)^p \times \ensuremath{\mathbb{R}}^q$ and any permutations $\alpha, \beta$ of the sets $\{ 1, \dots, p \}$ and $\{ 1, \dots, q \}$, respectively, one has $$E(p_{\alpha(1)},\dots, p_{\alpha(p)}, e_{\beta(1)}, \dots, e_{\beta(q)}) = E(p_1,\dots, p_p, e_1, \dots, e_q).$$ \end{definition} It follows from this permutation invariance and \cref{lemma:semi-alg-persistence} that if a function of persistence $E \colon \ensuremath{\mathbb{R}}^{2p+q} = \ensuremath{\mathbb{R}}^{|K|} \to \ensuremath{\mathbb{R}}$ is locally Lipschitz, then the composition $E \circ \mathrm{Pers}$ is also locally Lipschitz. Moreover, if $E$ is definable in an o-minimal structure, then for any definable parametrized family of filtrations $\Phi \colon A \subseteq \ensuremath{\mathbb{R}}^d \to \ensuremath{\mathbb{R}}^{|K|}$, the composition $\mathcal{L} = E \circ \mathrm{Pers} \circ \Phi \colon A \to \ensuremath{\mathbb{R}}$ is also definable. As a consequence, $\mathcal{L}$ has a well-defined Clarke subdifferential $\partial \mathcal{L}(z):=\mathrm{Conv} \{ \lim_{z_i \to z} \nabla \mathcal{L}(z_i) \; : \; \text{$\mathcal{L}$ is differentiable at $z_i$} \}$, since it is differentiable almost everywhere thanks to \cref{thm:diff_semialg}. \subsection{Stochastic gradient descent} To minimize $\mathcal{L}$, we consider the differential inclusion \begin{align} \frac{dz}{dt} \in - \partial\mathcal{L}(z(t)) \quad \text{\rm for almost every $t$}, \end{align} whose solutions $z(t)$ are the trajectories of the subgradient of $\mathcal{L}$. They can be approximated by the standard stochastic subgradient algorithm given by the iterations of \begin{equation} \label{eq:stochastic_gradient} x_{k+1} = x_k - \alpha_k ( y_k + \zeta_k),\ y_k \in \partial \mathcal{L}(x_k), \end{equation} where the sequence $(\alpha_k)_k$ is the learning rate and $(\zeta_k)_k$ is a sequence of random variables. In \cite{subgradient}, the authors prove that under mild technical conditions on these two sequences, the stochastic subgradient algorithm converges almost surely to a critical point of $\mathcal{L}$ as soon as $\mathcal{L}$ is locally Lipschitz. More precisely, consider the following assumptions, which correspond to Assumption~C in \cite{subgradient}: \begin{enumerate} \itemsep -0.1cm \item for any $k$, $\alpha_k \geq 0$, $\sum_{k=1}^\infty \alpha_k = +\infty$ and, $\sum_{k=1}^\infty \alpha_k^2 < +\infty$; \item $\sup_k \| x_k \| < +\infty$, almost surely; \item denoting by $\mathcal{F}_k$ the increasing sequence of $\sigma$-algebras $\mathcal{F}_k = \sigma(x_j,y_j,\zeta_j, j < k)$, there exists a function $p \colon \ensuremath{\mathbb{R}}^d \to \ensuremath{\mathbb{R}}$ which is bounded on bounded sets such that almost surely, for any $k$, \begin{align} \mathbb{E}[\zeta_k|\mathcal{F}_k] = 0 \ \ \mbox{\rm and} \ \ \mathbb{E}[\| \zeta_k \|^2 |\mathcal{F}_k] < p(x_k). \end{align} \end{enumerate} These assumptions are standard and not very restrictive. Assumption~1 depends on the choice of the learning rate by the user and is easily satisfied, e.g., taking $\alpha_k = 1/k$. Assumption~2 is usually easy to check for most of the functions $\mathcal{L}$ encountered in practice. Assumption~3 is a standard condition, which states that, conditioned upon the past, the variables $\zeta_k$ have zero mean and controlled moments; e.g., this can be achieved by taking a sequence of independent and centered variables with bounded variance that are also independent of the $x_k$'s and $y_k$'s. Under these assumptions, the following result is an immediate consequence of Corollary~5.9 in \cite{subgradient}. \begin{theorem} \label{thm:convergence_guarantees} Let $K$ be a simplicial complex, $A \subseteq \ensuremath{\mathbb{R}}^d$, and $\Phi \colon A \to \ensuremath{\mathbb{R}}^{|K|}$ a parametrized family of filtrations of $K$ that is definable in an o-minimal structure. Let $E \colon \ensuremath{\mathbb{R}}^{|K|} \to \ensuremath{\mathbb{R}}$ be a definable function of persistence such that $\mathcal{L} = E \circ \mathrm{Pers} \circ \Phi$ is locally Lipschitz. Then, under the above assumptions~1, 2, and 3, almost surely the limit points of the sequence $(x_k)_k$ obtained from the iterations of \cref{eq:stochastic_gradient} are critical points of $\mathcal{L}$ and the sequence $(\mathcal{L}(x_k))_k$ converges. \end{theorem} The above theorem provides explicit conditions ensuring the convergence of stochastic subgradient descent for functions of persistence. The main criterion to be checked is the local Lipschitz condition for $\mathcal{L}$. From the remark following \cref{def:fn-pers}, it is sufficient to check that $\Phi$ and $E$ are Lipschitz. Regarding $\Phi$, it is obvious for the examples of \cref{sec:exs}. This is not the case for some other examples, such as the so-called alpha-complex filtration that can be made locally Lipschitz using a simple technical trick---see Appendix. \subsection{Examples of definable locally Lipschitz functions of persistence} \paragraph{Total persistence.} Let $E$ be the sum of the distances of each point of a persistence diagram with finite coordinates to the diagonal: given a persistence diagram represented as a vector in $\ensuremath{\mathbb{R}}^{2p+q}$, $D = ((b_1,d_1), \dots, (b_p,d_p), e_1, \dots, e_q)$, \begin{align} E(D) = \sum_{i=1}^p |d_i - b_i|. \end{align} Then $E$ is obviously semi-algebraic, and thus definable in any o-minimal structure. It is also Lipschitz. \paragraph{Wasserstein and bottleneck distance} Given a persistence diagram $D^*$, the bottleneck distance between the regular part of a diagram $D$ and the regular part of $D^*$ (see \cref{def:regess}) is given by \begin{align} E(D) = d_B(D_{\mathrm{reg}},D^*_{\mathrm{reg}}) = \min_{m} \ \ \max_{(p,p^*) \in m} ||p - p^*||_\infty, \end{align} where, denoting $\Delta = \{ (x,x) : x \in \ensuremath{\mathbb{R}} \}$ the diagonal in $\ensuremath{\mathbb{R}}^2$, $m$ is a partial matching between $D_{\mathrm{reg}}$ and $D^*_{\mathrm{reg}}$, i.e., a subset of $(D_{\mathrm{reg}} \cup \Delta) \times (D^*_{\mathrm{reg}} \cup \Delta)$ such that every point of $D_{\mathrm{reg}} \setminus \Delta$ and $D^*_{\mathrm{reg}} \setminus \Delta$, appears exactly once in $m$. One can easily check that the map $E$ is semi-algebraic, and thus definable in any o-minimal structure. It is also Lipschitz. This property also extends to the case where the bottleneck distance is replaced by the so-called Wasserstein distance $W_p$ with $p \in \mathbb{N}$ \cite{cohen2010lipschitz}, or its approximation, the Sliced Wasserstein distance~\cite{Carriere2017b}. Optimization of these functions $E$ and other functions of bottleneck and Wasserstein distances have been used, for example, in shape matching in \cite{poulenard2018topological}. See also the example on 3D shape in Appendix. \paragraph{Persistence landscapes \cite{bubenik2015statistical}} To any given point $p = (x,y)\in \ensuremath{\mathbb{R}}^2$ with $x=\frac{b+d}{2}$ and $y=\frac{d-b}{2}$, associate the function $\Lambda_p \colon \ensuremath{\mathbb{R}} \to \ensuremath{\mathbb{R}}$ defined by \begin{equation}\label{eq:triangle} \Lambda_p(t) = \begin{cases} t-b & (t \in [b, \frac{b+d}{2}]) \\ d-t & (t \in (\frac{b+d}{2}, d]) \\ 0 & (\text{otherwise}). \end{cases} \end{equation} Given a persistence diagram $D$, the persistence landscape of $D$ is a summary of the arrangement of the graphs of the functions $\Lambda_p$, $p \in D$: \begin{align} \lambda_D(k,t) = \mathop{k\operatorname{-max}}\limits_{p \in D} \Lambda_p(t), \ \ t \in [0,T], k \in \mathbb{Z}^+, \end{align} where $\mathop{k\operatorname{-max}}\limits$ is the $k$th largest value in the set, or $0$ when the set contains less than $k$ points. Given a positive integer $k$, a finite set $\{t_1, \dots, t_n \} \subset \ensuremath{\mathbb{R}}$, and a simplicial complex $K$, the map that associates the vector $(\lambda_D(k,t_1), \dots, \lambda_D(k,t_n))$ to each persistence diagram $D$ of a filtration of $K$ is Lipschitz \cite{bubenik2015statistical} and clearly semi-algebraic. Other classical ways to vectorize persistence diagrams are the \emph{linear representations} \cite{chazal2018density} which are also definable in o-minimal structures, such as, e.g., persistence images~\cite{adams2017persistence}---see Appendix. In \cite{divol2019understanding}, the authors give explicit conditions for such representations to be locally Lipschitz. \section{Numerical illustrations} \label{sec:implementation} We showed in \cref{sec:ominim,sec:funcs} that the usual stochastic gradient descent procedure of \cref{eq:stochastic_gradient} enjoys some convergence properties for persistence-based functions. This means in particular that the algorithms available in standard libraries such as TensorFlow and PyTorch, which implement stochastic gradient descent (among other optimization methods), can be leveraged and used as is for differentiating persistence diagrams, while still ensuring convergence. The purpose of this section is to illustrate that our code, which implements the general gradient defined in \cref{thm:diff_semialg} for persistence-based functions, and which is based on Gudhi\footnote{https://gudhi.inria.fr/} and TensorFlow, can be readily used for studying several different persistence optimization tasks. On the way, we also suggest regularization terms that one can add to topological losses in order to avoid unwanted behaviors. We only present a few applications due to lack of space, and we refer the interested reader to Appendix for more examples. \paragraph{Point cloud optimization.} A toy example in persistence optimization is to modify the positions of the points in a point cloud so that its homology is maximized~\cite{gabrielsson2020topology, gameiro2016continuation}. In this experiment, we start with a point cloud $X$ sampled uniformly from the unit square $S=[0,1]^2$, and then optimize the point coordinates so that the loss $\mathcal L(X)=P(X)+T(X)$ is minimized. Here $T(X):=-\sum_{p\in D}\|p-\pi_\Delta(p)\|_\infty^2$ is a topological penalty, $D$ is the 1-dimensional persistence diagram associated to the Vietoris-Rips filtration of $X$, $\pi_\Delta$ stands for the projection onto the diagonal $\Delta$, and $P(X):=\sum_{x\in X}d(x,S)$ is a penalty term ensuring that the point coordinates stay in the unit square. The topological penalty $T(X)$ was used in~\cite{bruel2019topology}, and ensures that holes are created within the point cloud so that the cardinality of the persistence diagram $D$ is as large as possible. However, we point out that if one uses $T(X)$ alone without the penalty $P(X)$, as in~\cite{bruel2019topology}, then convergence is very difficult to reach since inflating the point cloud with dilations can make the topological penalty $T(X)$ arbitrarily small. In contrast, using our second term $P(X)$ in addition to $T(X)$ constrains the points to stay in a fixed region $S$ of the Euclidean plane. Another effect of the penalty $P(X)$ is to flatten the boundary of the created holes along the boundary of $S$. See \cref{fig:pc} for an illustration. \begin{figure}[!ht] \centering \includegraphics[width=3.75cm]{images/pc0.png} \includegraphics[width=3.75cm]{images/pc1000.png} \includegraphics[width=3.75cm]{images/badpc.png} \includegraphics[width=3.75cm]{images/pcloss_1.png} \caption{Illustration of point cloud optimization. We initialize with a random point cloud (left), and we show the optimized point cloud when optimization is done with topological and regularization losses (middle left). When only topological loss is used, the optimized point cloud inflated some loops to minimize the loss (middle right). Note how the coordinates are now much larger. We also show the convergence of the total loss (right). } \label{fig:pc} \end{figure} \paragraph{Dimension reduction.} In this experiment, we show how our general setup can be used to reduce dimension with the so-called \emph{topological autoencoders} introduced in~\cite{moor2019topological}. In this family of autoencoders, a topological loss $T(X,Z)$ between the input space $X$ and latent space $Z$ is used in addition to the usual loss $\mathcal D(X,Z)=\sum_i \|x_i-z_i\|_2^2$. This topological loss was computed in~\cite{moor2019topological} by (i)~computing the permutations induced by the persistence map (see \cref{sec:pers}) of the Vietoris-Rips complexes built from the input space $X$ and the latent space $Z$, (ii)~computing, for each simplex in these permutations, the corresponding edge that induces its filtration value, and (iii)~measuring, for all those edges, the differences between the edge lengths in $X$ and the same edge lengths in $Z$. To sum up, the loss function is defined as \begin{equation} \mathcal L(X,Z) = \|M_X[\pi_X]-M_Z[\pi_X]\|_2^2 + \|M_X[\pi_Z]-M_Z[\pi_Z]\|_2^2, \end{equation} where $M_X,M_Z$ are the distance matrices of the input and the latent spaces respectively, and where $\pi_X,\pi_Z$ denote the indices of the entries in $M_X,M_Z$ that are picked by the permutation induced by the persistence map to generate the Vietoris-Rips persistence diagrams of $X$ and $Z$. Note that $\mathcal L$ is obviously semi-algebraic and thus fits in our framework. Moreover, in our setup we can directly use the bottleneck and Wasserstein distances between the Vietoris-Rips persistence diagrams of the input and latent spaces as the topological loss. This is relevant since in \cite{moor2019topological} the authors pointed out that looking at homology in dimension larger than 1 was not adding anything for their loss, and stuck to 0-dimensional homology. We show in \cref{fig:auto} an example in which 1-dimensional homology is also important, that is, a point cloud in $\mathbb R^3$ that is comprised of two nested circles, which is then non-linearly embedded in in $\mathbb R^9$ by converting each point $p=(x,y,z)$ into the exponential of the 3x3 anti-symmetric matrix whose coefficient are $x,y$ and $z$. We then train an autoencoder made of four fully-connected layers with $32$ neurons and ReLU activations, using the usual loss, the usual plus the topological loss described above, and the usual plus a topological loss computed as $\mathcal L(X,Z)=W_1(D_X, D_Z)$, i.e., the 1-Wasserstein distance between the 1-dimensional Vietoris-Rips persistence diagrams of the input and latent spaces. It can be seen from \cref{fig:auto} that autoencoders without the Wasserstein loss cannot embed the point cloud in the plane perfectly, while using the Wasserstein loss between the 1-dimensional Vietoris-Rips persistence diagrams improves on the result by separating better the two intrinsic circles. \begin{figure}[!ht] \centering \includegraphics[width=3.8cm]{images/inputpc.png} \includegraphics[width=3.75cm]{images/usual.png} \includegraphics[width=3.8cm]{images/improvpc.png} \includegraphics[width=3.8cm]{images/lossauto.png} \caption{Example of dimension reduction with autoencoders. An initial point cloud made of two circles (left) is embedded in $\mathbb R^9$, and then fed to autoencoders that either do not use topology, or only use the distances induced by the persistence maps in dimension $0$. The resulting embeddings (middle left, we only show one but the two are similar) cannot separate the circles, while using 1-dimensional topology induces a better embedding (middle right). Convergence of the loss function is also provided (right).} \label{fig:auto} \end{figure} \begin{table*}[!ht] \input{table} \caption{\label{tab:scores} Accuracy scores obtained from persistence diagrams before and after performing our optimization over the filtration. Note that the difference between the scores is almost always positive, i.e., there is almost always improvement after our optimization process. Scores do not have standard deviations since we use the train/test splits of the \texttt{mnist.load\_data} function in TensorFlow 2. } \end{table*} \paragraph{Filter selection.} In this experiment, we address a very common issue in Topological Data Analysis, filter selection. Indeed, when computing persistence diagrams in order to generate topological features from a data set for further data analysis, the filter function that is being used to filter the data set always has to be specified a priori. Here, we provide a very simple heuristic to tune it if it comes from a parametrized family $\mathcal F$ of filters and if the learning task is supervised, which is the case in, e.g., classification. We simply start from a random guess in $\mathcal F$ and then optimize the following criterion, which is inspired from \cite{Zhao2019}: \begin{equation}\label{eq:classloss} \mathcal L(f) = \sum_{l=1}^N \frac{\sum_{i,j:y_i=y_j=l} W_p(D_i(f),D_j(f))}{\sum_{i,j:y_i=l} W_p(D_i(f),D_j(f))}, \end{equation} which amounts to minimize the distances between persistence diagrams that share the same label, and increase the distances between persistence diagrams with different labels. Note that the batch size that we use in this optimization process has a big influence on the computation time, since the larger the batch size, the more Wasserstein distances we will have to compute in our cost. To cope with this issue, we actually used the Sliced Wasserstein distance $SW$~\cite{Carriere2017b} instead of $W_p$, which, since it is computed with projections onto lines, can be defined entirely with matrix operations that are usually available in any library with autodifferentiation. This drastically improves on computation time, while remaining in our framework since the Sliced Wasserstein distance is also a semi-algebraic function. We classify images from the \texttt{MNIST} data set. We assign values to the pixels using a height function given by a direction (parametrized by an angle in the Euclidean plane), and we use 0-dimensional persistence diagrams computed after optimizing this direction using loss~\eqref{eq:classloss}. See \cref{fig:mnist}. \begin{figure}[!ht] \centering \includegraphics[width=7.5cm]{images/digit} \includegraphics[width=7cm]{images/improv.png} \caption{{\bf Left:} Example of images and directions inducing different height functions. Different directions generate different height functions and filtrations and thus different persistence diagrams. In this experiment, we optimize over the direction so that the persistence diagrams are the most efficient for image classification. {\bf Right:} Pairwise differences between the accuracy scores (\%) of optimized and non optimized filtrations for classifying digit $x$ vs. digit $y$. One can see that the difference is almost always positive.} \label{fig:mnist} \end{figure} We then compute the accuracy scores obtained with a random forest classifier for the (binary) classification tasks digit $x$ vs. digit $y$ for all pairs $0\leq x,y \leq 9$, using the first five persistence landscapes with resolution $100$ associated to the persistence diagrams before and after optimization. Even though our primary goal is to demonstrate that optimizing the filter almost always lead to an improvement, we also add a baseline score obtained by training a random forest classifier directly on the images for proper comparison. Some of the scores are displayed in \cref{tab:scores} (the full table can be found in Appendix), and all pairwise scores are shown in \cref{fig:mnist}. Interestingly, when starting with a random direction, scores can be much worse than the baseline, but our optimization process is then able to select the best direction that induces the best persistence diagrams (with respect to the classification task) without prior knowledge on the data set. \section{Conclusion} \label{sec:conclusion} In this article we introduced a theoretical framework that encompasses most of the previous methods for optimizing topology-based functions. In particular, we obtained convergence results for very general classes of functions with topological flavor computed with persistence theory, and provided corresponding code that one can use to reproduce previously introduced topological optimization tasks. For future work, we are planning to further investigate tasks related to classifier regularization in ML~\cite{chen2019topological}, and to improve on computation time using, e.g., vineyards~\cite{Cohen-Steiner2006}. \clearpage \bibliographystyle{alpha}
{'timestamp': '2021-02-19T02:01:41', 'yymm': '2010', 'arxiv_id': '2010.08356', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08356'}
arxiv
\section{Introduction} Modern cryptocurrency systems consist of two largely orthogonal parts: A consensus protocol, and the ledger structure it is used to maintain. While consensus protocols have received a lot of attention (see e.g. \cite{Nak08,Kia17}), the design space of the accompanying ledger structures is barely explored. The recent interest in smart contracts has led to the development of sophisticated ledger structures with complex behaviour (see e.g. \cite{Atz18,Woo14}). These efforts have been largely \emph{ad hoc}, and the resulting ledger structures are difficult to reason about. This difficulty also manifests in the larger system, which has contributed to several unfortunate incidents involving blockchain technology \cite{Atz17}. A strong mathematical foundation for ledger structures would enable more rigorous development of sophisticated blockchain systems. Further, the ability to reason about the ledger at a high level of abstraction would facilitate analysis of system behaviour. This is important: users of the system must understand it in order to use it with confidence. The formalism we propose has an intuitive graphical representation, which would make this kind of rigorous operational understanding possible on a far wider scale that it would otherwise be. Blockchain systems are largely concerned with recording the material history of virtual objects, with a particular focus on changes in ownership. The resource theoretic interpretation of string diagrams for symmetric monoidal categories gives a precise mathematical meaning to this sort of material history. Building on this, we consider string diagrams augmented with extra information concerning the ownership of resources. We give these diagrams a precise mathematical meaning in terms of strong monoidal functors, drawing heavily on the work of \cite{McC11}, where our augmented diagrams originated. We show that an augmented resource theory has the same categorical structure as the original, in the sense that the two corresponding categories are equivalent. Finally, we give a simple example of a ledger structure using our machinery. \section{Monoidal Categories as Resource Theories} We assume familiarity with some basic category theory, in particular with symmetric monoidal categories. A good reference is \cite{Mac71}. Throughout, we will write composition in diagrammatic order. That is, the composite of $f : X \to Y$ and $g : Y \to Z$ is written $fg : X \to Z$. We may also write $g \circ f : X \to Z$, but we will \emph{never} write $gf : X \to Z$. We will make heavy use of string diagrams for monoidal categories (see e.g. \cite{Sel10}), which we read from top to bottom (for composition) and left to right (for the monoidal tensor). Our string diagrams for ownership are in fact the string diagrams for monoidal functors of \cite{McC11}. \subsection{Resource Theories} We begin by observing (after \cite{Coe14}) that a symmetric strict monoidal category can be interpreted as a theory of resource convertibility: Each object corresponds to collection of resources with $A \otimes B$ denoting the collection composed of both $A$ and $B$ and the unit $I$ denoting the empty collection. Morphisms $f : A \to B$ are then understood as a way to convert the resources of $A$ to those of $B$. For example, consider the free symmetric strict monoidal category on the set \[\{\texttt{bread},\texttt{dough},\texttt{water},\texttt{flour},\texttt{oven}\}\] \noindent of atomic objects, subject to the following additional axioms: \begin{mathpar} \texttt{mix} : \texttt{water} \otimes \texttt{flour} \to \texttt{dough} \texttt{knead} : \texttt{dough} \to \texttt{dough} \texttt{bake} : \texttt{dough} \otimes \texttt{oven} \to \texttt{bread} \otimes \texttt{oven} \end{mathpar} This category can be understood as a theory of resource convertibility for baking bread. The morphism $\texttt{mix}$ represents the process of combining water and flour to form a bread dough, $\texttt{knead}$ the process of kneading the dough, and $\texttt{bake}$ the process of baking the dough in an oven to yield bread (and an oven). While this model has many failings as a theory of bread, it suffices to illustrate the idea. The axioms of a symmetric strict monoidal category provide a natural scaffolding for this theory to live in. For example, consider the morphism \[ (\texttt{bake} \otimes 1_{\texttt{dough}})(1_{\texttt{bread}} \otimes \sigma_{\texttt{oven},\texttt{dough}} \texttt{bake})\] \noindent where $\sigma_{A,B} : A \otimes B \stackrel{\sim}{\longrightarrow} B \otimes A$ is the braiding. This morphism has type \[\texttt{dough} \otimes \texttt{oven} \otimes \texttt{dough} \to \texttt{bread} \otimes \texttt{bread} \otimes \texttt{oven}\] \noindent and describes the transformation of two pieces of dough into two loaves of bread by baking them one after the other in an oven. We obtain a string diagram for this morphism by drawing our objects as wires, and our morphisms as boxes with inputs and outputs. Composition is represented by connecting output wires to input wires, and we represent the tensor product of two morphisms by placing them beside one another. Finally, the braiding is represented by crossing the involved wires. For the morphism in question, we obtain: \[ \includegraphics[height=4cm]{diagrams/small-baking-example.png} \] We will think of our ledger systems in terms of such string diagrams: The state of the system is a string diagram describing the \emph{material history} of the resources involved, the available resources correspond to the output wires, and changes are effected by appending resource conversions to the bottom of the diagram. From now on we understand a \emph{resource theory} to be a symmetric strict monoidal category with an implicit resource-theoretic interpretation. \subsection{How to Read Equality} Suppose we have a resource theory $\mathbb{X}$, and two resource transformations $f,g : A \to B$. Each of $f$ and $g$ expresses a different way to transform an instance of resource $A$ into an instance of resource $B$, but these may not have the same effect. For example, consider $\texttt{knead} : \texttt{dough} \to \texttt{dough}$ and $1_{\texttt{dough}} : \texttt{dough} \to \texttt{dough}$ from our resource theory of bread. Clearly these should not have the same effect on the input dough. This is reflected in our resource theory in the sense that they are not made equal by its axioms. For contrast, we can imagine a (somewhat) reasonable model of baking bread in which there is no difference between kneading the dough once and kneading it many times. We could capture this in our resource theory of baking bread by imposing the equation \[ \texttt{knead} = \texttt{knead} \circ \texttt{knead}\] In this new resource theory, our equation tells us that kneading dough once has the same effect as kneading it twice, or three times, and so on, since the corresponding morphisms of the resource theory are made equal by its axioms. Of course, the material history described by $\texttt{knead} \circ \texttt{knead}$ is not identical to that described by $\texttt{knead}$. In the former case, the kneading process has been carried out twice in sequence, while in the latter case it has only been carried out once. That these morphisms are equal merely means that the effect of each sequence of events on the dough involved is the same. We adopt the following general principle in our design and understanding of resource theories: \textit{Two transformations should be equal precisely when they have the same effect on the resources involved}. We further illustrate this by observing that, by the axioms of a symmetric monoidal category (specifically, by naturality of braiding), the following two transformations in the resource theory of baking (expressed as string diagrams) are equal. The transformation on the left describes baking two loaves of bread by first mixing and kneading two batches of dough before baking them in sequence, while the transformation on the right describes baking two loaves of bread by mixing, kneading, and baking the first batch of dough, and \emph{then} mixing, kneading, and baking the second batch. Thus, according to our resource theory the two procedures will yield the same result -- not an entirely unreasonable conclusion! \[\includegraphics[height=10cm]{diagrams/medium-baking-example.png}\] \section{String Diagrams for Ownership} Ledgers used by blockchain systems are largely concerned with \emph{ownership}. For example, in the Bitcoin system, each coin is associated with a computable function called the \emph{validator}, which is used to control access to it. Anyone who wishes to use the coin must supply input data, called a \emph{redeemer}, and the system only allows them to use the coin in question in case running the validator on the redeemer terminates in a fixed amount of time. If the validator is defined only on the data that results from $\texttt{Alice}$ digitally signing a nonce generated by the system, then that coin can only be used by $\texttt{Alice}$, who then effectively owns it. Different use cases call for different authentication schemes. For example, a proposed application of blockchain technology is to improve supply chain accountability by requiring participants to log any transfers and transformations of material on a public ledger (see e.g. \cite{Jab18,Sta17}). Here ownership implies responsibility, and so for Alice to log the transfer of, say, a ton of steel to Bob, \emph{both} Alice and Bob must ratify the transfer via digital signature. What different use cases have in common is that the resources of the ledger system are associated with ownership data. We leave the interpretation of this ownership data, including the specific details of the authentication scheme unspecified, instead giving a structural account of resource ownership. We develop our account of resource ownership intuitively, and somewhat informally, by introducing addtional features to string diagrams. This is made fully formal in the next section. \subsection{Ownership and Collection Management} Begin by assuming a theory of resources $\mathbb{X}$, and a collection $\mathcal{C}$ of potential resource owners, each of which we associate with a colour for use in our diagrams. Suppose for the remainder that $\texttt{Alice}$, $\texttt{Bob}$, and $\texttt{Carol}$ range over $\mathcal{C}$, and are associated with colours as follows: \[ \includegraphics[height=0.8cm]{diagrams/alice-bob-carol-colours.png} \] Our goal will be to construct a new theory of resources in which resources and transformations are associated with (owned and carried out by) elements of $\mathcal{C}$. The objects of our new resource theory will be collections of owned objects of $\mathbb{X}$. That is, for each object $X$ of $\mathbb{X}$ and each $\texttt{Alice} \in \mathcal{C}$ we have an object $X^{\texttt{Alice}}$, which we interpret as an instance of resource $X$ owned by $\texttt{Alice}$, along with the empty collection $I$ and composite collections $X^{\texttt{Alice}} \otimes Y^{\texttt{Bob}}$, in which $\texttt{Alice}$'s instance of $X$ exists alongside an instance of $Y$ owned by $\texttt{Bob}$. Similarly, for each transformation $f : X \to Y$ in $\mathbb{X}$, we ask for transformations $f^{\texttt{Alice}} : X^{\texttt{Alice}} \to Y^{\texttt{Alice}}$ and $f^{\texttt{Bob}} : X^{\texttt{Bob}} \to Y^{\texttt{Bob}}$ for all $\texttt{Alice},\texttt{Bob} \in \mathcal{C}$, whose presence we interpret as the ability of each owner to effect all possible transformations of resources they own. We draw these annotated transformations as, respectively: \[ \includegraphics[height=2cm]{diagrams/alice-bob-resource-transformations.png} \] Since we are building a theory of resources we must end up with a symmetric monoidal category, so we also assume the presence of the associated morphisms, such as $f^{\texttt{Alice}} \otimes g^{\texttt{Bob}}$ and $\sigma_{X^{\texttt{Alice}},Y^{\texttt{Bob}}}$. Next, we account for the formal difference between $X^{\texttt{Alice}} \otimes Y^{\texttt{Alice}}$ and $(X \otimes Y)^{\texttt{Alice}}$. In both situations $\texttt{Alice}$ owns an $X$ and a $Y$, but in the former they are formally grouped together, while in the latter they are formally separated. We understand this formal grouping of $\texttt{Alice}$'s assets by analogy with physical currency. The situation in which $\texttt{Alice}$'s assets are separated is like $\texttt{Alice}$ having two coins worth one euro, while the situation in which they are grouped together is like $\texttt{Alice}$ having one coin worth two euros. In both cases, $\texttt{Alice}$ posesses two euros, but the difference is important: $\texttt{Alice}$ cannot give $\texttt{Bob}$ half of the two euro coin, but can easily give $\texttt{Bob}$ one of the two one euro coins. This distinction is also present in cryptocurrency systems, where there is an operational difference between having funds spread across many addresses and having them collected at one address. Reflecting both the reality of such systems and the principle that one ought to be able to freely reconfigure the formal grouping of things that they own, we ask that for each $X,Y$ objects of $\mathbb{X}$ and each $\texttt{Alice} \in \mathcal{C}$ our new resource theory has morphisms $\phi_{X,Y} : X^{\texttt{Alice}} \otimes Y^{\texttt{Alice}} \to (X \otimes Y)^{\texttt{Alice}}$ and $\psi_{X,Y} : (X \otimes Y)^{\texttt{Alice}} \to X^{\texttt{Alice}} \otimes Y^{\texttt{Alice}}$. We draw these morphisms, respectively, as follows: \[ \includegraphics[height=2cm]{diagrams/alice-phi-psi.png} \] These changes of formal grouping should not interact with the resource transformations of our original theory $\mathbb{X}$, since it ought not matter whether $\texttt{Alice}$ combines (splits) her resources before or after transforming them. That is, we we require: \begin{enumerate}[] \item \textbf{[G.1]} $\phi^{\texttt{Alice}}_{X,Y}(f \otimes g)^{\texttt{Alice}} = (f^{\texttt{Alice}} \otimes g^{\texttt{Alice}})\phi^{\texttt{Alice}}_{X',Y'}$ \item \textbf{[G.2]} $(f \otimes g)^{\texttt{Alice}}\psi^{\texttt{Alice}}_{X',Y'} = \psi^{\texttt{Alice}}_{X,Y}(f^{\texttt{Alice}} \otimes g^{\texttt{Alice}})$ \end{enumerate} \[ \includegraphics[height=2cm]{diagrams/alice-phi-psi-natural.png}\] As it stands, there are many non-equal ways for $\texttt{Alice}$ to reconfigure the formal grouping of their assets. Since these should all have the same effect, we need them all to be equal as morphisms in our resource theory. It suffices to ask that the $\phi^{\texttt{Alice}}$ and $\psi^{\texttt{Alice}}$ maps give, respectively, associative and coassociative operations, and that they are mutually inverse. That is (associativity and coassociativity): \begin{enumerate}[] \item \textbf{[G.3]} $(\phi^{\texttt{Alice}}_{X,Y} \otimes 1_Z^{\texttt{Alice}})\phi^{\texttt{Alice}}_{X\otimes Y,Z} = (1_X^{\texttt{Alice}} \otimes \phi^{\texttt{Alice}}_{Y,Z})\phi^{\texttt{Alice}}_{X,Y\otimes Z}$ \item \textbf{[G.4]} $\psi_{X\otimes Y,Z}^{\texttt{Alice}}(\psi_{X,Y}^{\texttt{Alice}} \otimes 1_Z^{\texttt{Alice}}) = \psi_{X,Y\otimes Z}^{\texttt{Alice}}(1_X^{\texttt{Alice}} \otimes \psi_{Y,Z}^{\texttt{Alice}})$ \end{enumerate} \[ \includegraphics[height=2cm]{diagrams/alice-phi-psi-associative-coassociative.png} \] and (mutually inverse): \begin{enumerate}[] \item \textbf{[G.5]} $\psi^{\texttt{Alice}}_{X,Y}\phi^{\texttt{Alice}}_{X,Y} = 1_{X \otimes Y}^{\texttt{Alice}}$ \item \textbf{[G.6]} $\phi^{\texttt{Alice}}_{X,Y}\psi^{\texttt{Alice}}_{X,Y} = 1_X^{\texttt{Alice}} \otimes 1_Y^{\texttt{Alice}}$ \end{enumerate} \[ \includegraphics[height=2cm]{diagrams/alice-phi-psi-mutually-inverse.png} \] To complete our treatment of these formal resource groupings, we must deal with the empty case $I^{\texttt{Alice}}$. We insist that $\texttt{Alice}$ may freely create and destroy such empty collections via morphisms $\phi^{\texttt{Alice}}_I : I \to I^{\texttt{Alice}}$ and $\psi^{\texttt{Alice}}_I : I^{\texttt{Alice}} \to I$: \[ \includegraphics[height=2cm]{diagrams/alice-phi-psi-empty.png} \] \noindent subject to the following axioms, which state that adding or removing nothing from a group or resources has the same effect as doing nothing, and that $\phi_I$ and $\psi_I$ are mutually inverse, which together ensure that even with $\phi_I$ and $\psi_I$ in the mix, any two formal regroupings with the same domain and codomain are equal. \begin{enumerate}[] \item \textbf{[G.7]} $(\phi_I^{\texttt{Alice}} \otimes 1_X^{\texttt{Alice}})\phi_{I,X}^{\texttt{Alice}} = 1_X^{\texttt{Alice}} = (1_X^{\texttt{Alice}} \otimes \phi_I^{\texttt{Alice}})\phi_{X,I}^{\texttt{Alice}}$ \item \textbf{[G.8]} $\psi_{I,X}^{\texttt{Alice}}(\psi_I^{\texttt{Alice}} \otimes 1_X^{\texttt{Alice}}) = 1_X^{\texttt{Alice}} = \psi_{X,I}^{\texttt{Alice}}(1_X^{\texttt{Alice}} \otimes \psi_I^{\texttt{Alice}})$ \item \textbf{[G.9]} $\phi_I^{\texttt{Alice}}\psi_I^{\texttt{Alice}} = 1_I$ \item \textbf{[G.10]} $\psi_I^{\texttt{Alice}}\phi_I^{\texttt{Alice}} = 1_I^{\texttt{Alice}}$ \end{enumerate} \[ \includegraphics[height=4cm]{diagrams/alice-phi-psi-empty-axioms.png} \] Finally, we ask that $\phi$ and $\psi$ behave coherently with respect to the symmetry maps. It suffices to require that \begin{enumerate}[] \item \textbf{[G.11]} $\phi_{X,Y}^{\texttt{Alice}}\sigma_{X,Y}^{\texttt{Alice}} = \sigma_{X^{\texttt{Alice}},Y^{\texttt{Alice}}}\phi_{Y,X}^{\texttt{Alice}}$ \end{enumerate} \[ \includegraphics[height=2.3cm]{diagrams/swap-axiom-diagram.png} \] \subsection{Change of Ownership} Of course, ownership is not static over time. We require the ability the \emph{change} the owner of a given collection of resources. To this end we add morphisms $\gamma_X^{\texttt{Alice},\texttt{Bob}} : X^{\texttt{Alice}} \to X^{\texttt{Bob}}$ to our new resource theory for each object $X$ of $\mathbb{X}$, each $\texttt{Alice},\texttt{Bob} \in \mathcal{C}$. We depict these new morphisms in our string diagrams as follows: \[ \includegraphics[height=2cm]{diagrams/gamma-alice-bob-diagram.png} \] As with regrouping, change of ownership should not interact with resource transformations, in the sense that: \begin{enumerate}[] \item \textbf{[O.1]} $f^{\texttt{Alice}}\gamma_Y^{\texttt{Alice},\texttt{Bob}} = \gamma_X^{\texttt{Alice},\texttt{Bob}}f^{\texttt{Bob}}$ \end{enumerate} \[ \includegraphics[height=2cm]{diagrams/gamma-alice-bob-natural.png} \] Further, change of ownership must behave coherently with respect to the regrouping morphisms in the sense that: \begin{enumerate}[] \item \textbf{[O.2]} $\phi_{X,Y}^{\texttt{Alice}}\gamma_{X\otimes Y}^{\texttt{Alice},\texttt{Bob}} = (\gamma_X^{\texttt{Alice},\texttt{Bob}}\otimes \gamma_Y^{\texttt{Alice},\texttt{Bob}})\phi_{X,Y}^{\texttt{Bob}}$ \item \textbf{[O.3]} $\gamma_{X \otimes Y}^{\texttt{Alice},\texttt{Bob}}\psi^{\texttt{Bob}}_{X,Y} = \psi^{\texttt{Alice}}_{X,Y}(\gamma^{\texttt{Alice},\texttt{Bob}}_X \otimes \gamma^{\texttt{Alice},\texttt{Bob}}_Y)$ \end{enumerate} \[ \includegraphics[height=2cm]{diagrams/gamma-alice-bob-monoidal-comonoidal.png} \] For completeness, we axiomatize the interaction of change of ownership with empty collections by requiring that: \begin{enumerate}[] \item \textbf{[O.4]} $\phi_I^{\texttt{Alice}}\gamma_I^{\texttt{Alice},\texttt{Bob}} = \phi_I^{\texttt{Bob}}$ \item \textbf{[O.5]} $\gamma_I^{\texttt{Alice},\texttt{Bob}}\psi_I^{\texttt{Bob}} = \psi_I^{\texttt{Alice}}$ \end{enumerate} \[ \includegraphics[height=2cm]{diagrams/gamma-alice-bob-empty-natural.png} \] Finally, we insist that if $\texttt{Alice}$ gives something to $\texttt{Bob}$, and $\texttt{Bob}$ then gives it to $\texttt{Carol}$, this has the same effect as $\texttt{Alice}$ giving the thing directly to $\texttt{Carol}$. Similarly, if $\texttt{Alice}$ gives something to $\texttt{Alice}$, we insist that this has no effect. \begin{enumerate}[] \item \textbf{[O.6]} $\gamma^{\texttt{Alice},\texttt{Bob}}_X\gamma^{\texttt{Bob},\texttt{Carol}}_X = \gamma_X^{\texttt{Alice},\texttt{Carol}}$ \item \textbf{[O.7]} $\gamma^{\texttt{Alice},\texttt{Alice}}_X = 1_X^{\texttt{Alice}}$ \end{enumerate} \[ \includegraphics[height=2cm]{diagrams/axioms-for-equivalence.png} \] We end up with a rather expressive diagrammatic language. For example, if we begin with the resource theory of bread, then our new resource theory is powerful enough to show: \[ \includegraphics[height=8cm]{diagrams/big-baking-example.png} \] which captures the fact that the sequence of events on the left in which $\texttt{Carol}$ gives $\texttt{Alice}$ and $\texttt{Bob}$ each a portion of dough to bake in their ovens, after which they give the resulting bread to $\texttt{Carol}$ \emph{has the same effect} as the sequence of events on the right in which $\texttt{Alice}$ and $\texttt{Bob}$ give their ovens to $\texttt{Carol}$, who bakes the portions of dough herself before returning the ovens to their original owners. Notice that our diagrammatic representation of this is \emph{much} easier to understand than the corresponding terms in linear syntax! \section{Categorical Semantics} In this section we show how our augmented string diagrams can be given precise mathematical meaning. Specifically, from a resource theory and a set whose elements we think of as entities capable of owning resources, we construct a new resource theory in which all resources are owned by some entity. We finish by showing how to model a simple cyrptocurrency ledger with our machinery. \subsection{Interpreting String Diagrams with Ownership} If $\mathbb{X}$ is a theory of resources and $\mathcal{C}$ is our set, we treat $\mathcal{C}$ as the corresponding discrete category, writing $A : A \to A$ for the identity maps, and form the product category $\mathbb{X} \times \mathcal{C}$. Write objects and maps of this product category as $X^A = (X,A)$ and $f^A = (f,A)$ respectively. Now, define $\mathcal{C}(\mathbb{X})$ to be the free strict symmetric monoidal category on $\mathbb{X} \times \mathcal{C}$ subject to the following additional axioms: \begin{mathpar} \inferrule{A \in \mathcal{C} \\ X,Y \text{ objects of } \mathbb{X}}{\phi^A_{X,Y} : X^A \otimes Y^A\to (X \otimes Y)^A \text{ in } \mathcal{C}(\mathbb{X})} \inferrule{A \in \mathcal{C}}{\phi_I^A : I \to I^A \text{ in } \mathcal{C}(\mathbb{X})} \inferrule{A \in \mathcal{C} \\ X,Y \text{ objects of } \mathbb{X}}{\psi^A_{X,Y} : (X \otimes Y)^A \to X^A \otimes Y^A \text{ in } \mathcal{C}(\mathbb{X})} \inferrule{A \in \mathcal{C}}{\psi_I^A : I^A \to I \text{ in } \mathcal{C}(\mathbb{X})} \inferrule{A,B \in \mathcal{C} \\ X \text{ an object of } \mathbb{X}}{\gamma_X^{A,B} : X^A \to X^B \text{ in } \mathcal{C}(\mathbb{X})} \end{mathpar} and subject to equations \textbf{[G.1--11]} and \textbf{[O.1--7]} for $\texttt{Alice},\texttt{Bob},\texttt{Carol} \in \mathcal{C}$, $X,Y,Z$ objects of $\mathbb{X}$, and $f,g$ morphisms of $\mathbb{X}$. Clearly, $\mathcal{C}(\mathbb{X})$ is the new resource theory our coloured string diagrams live in. We think of objects $X^A$ and morphisms $f^A$ as being owned and carried out, respectively, by $A \in \mathcal{C}$. The free monoidal structue gives us the ability to compose such transformations sequentially and in parallel, and the additional axioms ensure our ownership interpretation of $\mathcal{C}(\mathbb{X})$ is reasonable. We can characterize the category-theoretic effect of axioms \textbf{[G.1--11]} and \textbf{[O.1--5]} as follows: \begin{proposition} For any symmetric monoidal category $\mathbb{X}$ and any set $\mathcal{C}$, there is a strong symmetric monoidal functor \[ A : \mathbb{X} \to \mathcal{C}(\mathbb{X}) \] for each $A \in \mathcal{C}$. Further, there is a monoidal and comonoidal natural transformation \[\gamma^{A,B} : A \to B\] between the functors corresponding to any two $A,B \in \mathcal{C}$. \end{proposition} \begin{proof} Define $A : \mathbb{X} \to \mathcal{C}(\mathbb{X})$ by $A(X) = (X,A)$ on objects, and $A(f) = (f,A)$ on maps. For identity maps, $A(1_X) = (1_X,A) = 1_{(X,A)} = 1_{A(X)}$ since $(1_X,A)$ is the identity on $(X,A)$ in $\mathbb{X} \times \mathcal{C}$. For composition, $A(fg) = (fg,A) = (f,A)(g,A) = A(f)A(g)$.Thus $A$ defines a functor. $A$ is strong symmetric monoidal via the $\phi^A$ and $\psi^A$ maps together with \textbf{[G.1]} through \textbf{[G.11]}. Consider $A,B : \mathbb{X} \to \mathcal{C}(\mathbb{X})$ corresponding to $A,B \in \mathcal{C}$. Define $\gamma^{A,B} : A \to B$ to have components $\gamma^{A,B}_X$. Then $\gamma^{A,B}$ is a monoidal and comonoidal via \textbf{[O.1]} through \textbf{[O.5]}. \qed \end{proof} Notice that we did not use \textbf{[O.6--7]} above. These axioms are motivated by our desire to model resource ownership, but they have an important, if subtle, effect on the theory: they allow us to show that $\mathbb{X}$ and $\mathcal{C}(\mathbb{X})$ are equivalent as categories. This means that any suitably categorical structure is present in $\mathbb{X}$ if and only if it is present in $\mathcal{C}(\mathbb{X})$ as well. For example, products in $\mathbb{X}$ manifest as products in $\mathcal{C}(\mathbb{X})$, morphisms that are monic in $\mathbb{X}$ remain monic in $\mathcal{C}(\mathbb{X})$, and so on. We may be confident that our addition of ownership information has not broken any of the structure of $\mathbb{X}$, or added anything superfluous! \begin{proposition} There is an adjoint equivalence between $\mathbb{X}$ and $\mathcal{C}(\mathbb{X})$ for each functor corresponding to some $A \in \mathcal{C}$. \end{proposition} \begin{proof} We show that each $A : \mathbb{X} \to \mathcal{C}(\mathbb{X})$ is fully faithful, and essentially surjective, beginning with the latter. To that end, suppose that $P$ is an object of $\mathcal{C}(\mathbb{X})$. We proceed by structural induction: If $P$ is $I$, then $\phi_0$ witnesses $I \simeq A(I)$. If $P$ is an atom $(X,A)$, then $(X,A) = A(X)$. If $P$ is $Q \otimes R$ for some $Q,R$, then by induction we have that $Q \simeq A(X_1)$ and $R \simeq A(X_2)$ for some objects $X_1,X_2$ of $\mathbb{X}$. We may now form \centerline{\xymatrix{ Q \otimes R \simeq A(X_1) \otimes A(X_2) \ar[r]^(0.66){\phi^A_{X_1,X_2}} & A(X_1 \otimes X_2) }} \noindent which witnesses $P \simeq A(X_1 \otimes X_2)$. Thus, $A$ is essentially surjective. To see that $A$ is fully faithful, let $U : \mathcal{C}(\mathbb{X}) \to \mathbb{X}$ be the obvious forgetful functor. The required bijection $\mathbb{X}(X,Y) \simeq \mathcal{C}(\mathbb{X})(A(X),A(Y))$ is given by $A$ in one direction and $U$ in the other. It sufffices to show that any morphism $h : A(X) \to A(Y)$ with $U(h) = f$ is such that $h = A(f)$. Notice that since each $\gamma^{A,B}$ is a monoidal and comonoidal natural transformation, there is a term equal to $h$ in which all $\gamma$ morphisms occur before all other morphisms (in the sense that $f$ occurs before $g$ in $fg$). Since $h : A(X) \to A(Y)$ we know that in this equal term the composite of the $\gamma$ must have type $A(X) \to A(X)$, and must therefore be the identity by repeated application of \textbf{[O.6]} and \textbf{[O.7]}. This gives a term $h'$ containing no $\gamma$ maps with $h' = h$. Similarly, since the various $\phi$ and $\psi$ morphisms are natural transformations, we may construct a term $h''$ by collecting all instances of $\phi$ and $\psi$ terms at the beginning of $h'$. Once collected there, the composite of all the $\phi$ and $\psi$ must have type $A(X) \to A(X)$, and is therefore equal to the identity. At this point we know that $h'' : A(X) \to A(Y)$ is such that $h'' = A(f_1)\cdots A(f_n)$ for some $f_1,\ldots,f_n$ in $\mathbb{X}$. By assumption $f = U(h) = U(h'') = f_1\cdots f_n$, and therefore $h'' = A(f)$. \qed \end{proof} \subsection{A Simple Example} In this section we attempt to demonstrate the relevance of the above techniques to the cryptocurrency world by building a resource theory that models a simple ledger structure along the lines of Bitcoin \cite{Nak08}. Let $\mathds{1}$ be the trivial category, with one object, $1$, and one morphism, the identity $1_1$. Define $\mathbb{N}$ to be the free symmetric strict monoidal category on $\mathds{1}$, write $0$ for the monoidal unit of $\mathbb{N}$, and $n$ for the $n$-fold tensor product of $1$ with itself for all natural numbers $n \geq 1$. Notice that $n + m$ is $n \otimes m$. We will think of the objects $n$ of $\mathbb{N}$ where $n \geq 1$ as \emph{coins}. Of course, $0 = I$ represents the situation in which no coin in present. Define $\mathbb{N}_\nu$ to be the result of formally adding a morphism $\nu : 0 \to 1$ to $\mathbb{N}$, write $\nu_0 = 1_0 : 0 \to 0$, and $\nu_n : 0 \to n$ for the $n$-fold tensor product of $\nu$ with itself for $n \geq 1$. These morphisms confer the ability to create new coins, so we imagine their use would be restricted in practice. We will not ask for the ability to destroy coins, although there would be no theoretical obstacle to doing so. Now, let $\mathcal{C}$ be a collection of colours, which we can think of as standing in for cryptographic key pairs, or simply entities capable of owning coins. Consider $\mathcal{C}(\mathbb{N}_\nu)$. Objects are lists $n_1^{c_1} \otimes \cdots \otimes n_k^{c_k}$, which we interpret as lists of coins, where $n_i^{c_i}$ is a coin of value $n_i$ belonging to $c_i \in \mathcal{C}$. The morphisms are either $\nu_n^c$ for some $c \in \mathcal{C}$, the structural morphisms of a monoidal category, or the $\phi,\psi$, and $\gamma$ morphisms added by our construction. For $n,m \in \mathbb{N}$ and $\texttt{Alice},\texttt{Bob} \in \mathcal{C}$, the maps $\phi_{n,m}^{\texttt{Alice}} : n^{\texttt{Alice}} \otimes m^{\texttt{Alice}} \to (n + m)^{\texttt{Alice}}$ and $\psi^{\texttt{Alice}}_{n,m} : (n + m)^{\texttt{Alice}} \to n^{\texttt{Alice}} \otimes m^{\texttt{Alice}}$ allow users to combine and split their coins in a value-preserving manner, and the $\gamma^{\texttt{Alice},\texttt{Bob}}_n$ maps allow them to exchange coins. Now, a ledger is a (syntactic) morphism $a : I \to A$ of $\mathcal{C}(\mathbb{N}_\nu)$. A transaction to be included in $a$ consists of a transformation $f : X \to Y$ of $\mathcal{C}(\mathbb{N}_\nu)$ along with information about which outputs of $a$ are to be the inputs of the transformation, which we package as $t = \pi_t(1 \otimes f \otimes 1) : A \to B$. The result of including transaction $t$ in ledger $a$ is then the composite ledger $t \circ a : I \to B$. Put another way, a ledger is given by a list of transformations in $\mathcal{C}(\mathbb{N}_\nu)$: \[I \stackrel{t_1}{\longrightarrow} A_1 \stackrel{t_2}{\longrightarrow} \cdots \stackrel{t_k}{\longrightarrow} A_k \] For the purpose of illustration, we differentiate between $m + n$ and $m \otimes n$ in our string diagrams for $\mathbb{N}_\nu$. We do so by means of the string diagrams for (not necessarily strict) monoidal categories (see e.g. \cite{Coc17}), as in: \[\includegraphics[height=2cm]{diagrams/identity-identities-lol.png}\] \noindent Now, suppose we have a ledger $a : I \to \nu^{\texttt{Carol}}_7 \otimes \nu^{\texttt{Alice}}_5$: \[\includegraphics[height=1.7cm]{diagrams/example-initial-ledger.png}\] \noindent and resource transformations $f_1,f_2,f_3$ defined, respectively, by: \[\includegraphics[height=3.5cm]{diagrams/example-raw-transformations.png}\] \noindent Now, form transaction $t_1 = (1_7^{\texttt{Carol}} \otimes f_1)$ and append it to $a$ to obtain $t_1 \circ a$ \[\includegraphics[height=2.5cm]{diagrams/example-ledger-after-t1.png}\] \noindent Next, form transaction $t_2 = (1_7^{\texttt{Carol}} \otimes f_2)$ and append it to obtain $t_2 \circ t_1 \circ a$ \[\includegraphics[height=3.5cm]{diagrams/example-ledger-after-t2.png}\] \noindent Finally, form transaction $t_3 = (f_3 \otimes 1_3^{\texttt{Bob}})$ and append it to obtain $t_3 \circ t_2 \circ t_1 \circ a$ \[\includegraphics[height=6cm]{diagrams/example-ledger-after-t3-again.png} \] In this manner, we capture the evolution of the ledger over time. Of course, we can also reason about whether two sequences of transactions result in the same ledger state by comparing the corresponding morphisms for equality, although in the case of $\mathcal{C}(\mathbb{N}_\nu)$ there isn't much point, since all morphisms $A \to B$ are necessarily equal. \section{Conclusions and Future Work} We have seen how the resource theoretic interpretation of monoidal categories, and in particular their string diagrams, captures the sort of material history that concerns ledger structures for blockchain systems. Additionally, we have shown how to freely add a notion of ownership to such a resource theory, and that the resulting category is equivalent to the original one. We have also shown that these resource theories with ownership admit an intuitive graphical calculus, which is more or less that of monoidal functors and natural transformations. Finally, we have used our machinery to construct a simple ledger structure and show how it might be used in practice. While we do not claim to have solved the problem of providing a rigorous foundation for the development of ledger structures in its entirety, we feel that our approach shows promise. There are a few differnt directions for future research. One is the development of categorical models for more sophisticated ledger structures, with the eventual goal being to give a rigorous formal account of smart contracts. Another is to explore the connections of the current work with formal treatments of accounting, such as \cite{Kat98}. \newpage \bibliographystyle{plain}
{'timestamp': '2021-04-05T02:16:02', 'yymm': '2010', 'arxiv_id': '2010.08337', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08337'}
arxiv
\section{Introduction} \label{sec:intro} Many classification problems deal with classes that show a natural order. This includes for example patient outcome scores in clinical studies or movie ratings \citep{oghina2012predicting}. These ordinal outcome variables may not only depend on interpretable tabular predictors like age or temperature but also on complex input data such as medical images, networks of public transport, textual descriptions, or spectra. Depending on the complexity of the input data and the concrete task, different analysis approaches have established to tackle the ordinal problems. Ordinal regression as a probabilistic approach has been studied for more than four decades \citep{mccullagh1980regression}. The goal is to fit an interpretable regression model, which estimates the conditional distribution of an ordinal outcome variable $Y$ based on a set of tabular predictors. The ordinal outcome $Y$ can take values in a set of ordered classes and the tabular predictors are scalar and interpretable like age. Ordinal regression models make use of the information contained in the order of the outcome and provide a valid probability distribution instead of a single point estimate for the most likely outcome. This is essential to reflect uncertainty in the predictions. Moreover, the estimated model parameters are interpretable as the effect a single predictor has on the outcome given the remaining predictors are held constant. This allows experts to assess whether the model corresponds to their field knowledge and provides the necessary trust for application in critical decision making. However, there is a trade-off between interpretability and model complexity. The higher the complexity of a model, the harder it becomes to directly interpret the individual model parameters. Deep Learning (DL) approaches have gained huge popularity over the last decade and achieved outstanding performances on complex tasks like image classification and natural language processing \citep{goodfellow2016deep}. The models take the raw data as input and learn relevant features during the training procedure by transforming the input into a latent representation, which is suitable to solve the problem at hand. This avoids the challenging task of feature engineering, which is necessary when working with statistical models. Yet, unlike statistical models, most DL models have a black box character, which makes it hard to interpret individual model components. In addition, ordinal outcomes in DL approaches are frequently modeled in the same way as unordered outcomes using multi-class classification (MCC). That is, softmax is used as the last-layer activation and the loss function is the categorical cross-entropy. In this setting, solely the probability assigned to the true class is entering the loss function, which ignores the outcome’s natural order. To the best of our knowledge, there is currently no ordinal DL model, which enables to integrate tabular predictors and yields interpretable effect estimates for the tabular and the image data. This is a major disadvantage for example in fields like medicine which requires multiple data modalities for decision making but also a reliably interpretable model which quantifies the effects of the predictors on the outcome~\citep{rudin2018stop}. \subsection{Our Contribution} \label{sec:contrib} In this work we introduce ordinal neural network transformation models ({\sc ontram}s), which unite classical ordinal regression with DL approaches while conserving the interpretability of statistical and flexibility of DL models. We use a theoretically sound maximum-likelihood based approach and reparametrize the categorical cross-entropy loss to incorporate the order of the outcome. This guarantees the estimation of a valid probability distribution. By definition, the reparameterized negative log-likelihood (NLL) loss is able to achieve the same prediction performance as a standard DL model trained with cross-entropy loss, but allows a faster training in case of an ordinal outcome. The main advantage of the proposed {\sc ontram}s is that {\sc ontram}s provide interpretable effect estimates for the different input data, which is not possible with other DL models. We view ordinal regression models from a transformation model perspective \citep{hothorn2014conditional,sick2020deep}. This change of perspective is useful because it allows a holistic view on regression models, which easily extends beyond the case of ordinal outcomes. In transformation models the problem of estimating a conditional outcome distribution is translated into a problem of estimating the parameters of a monotonically increasing transformation function, which transforms the potentially complex outcome distribution to a simpler, predefined distribution $F_\rZ$ of a continuous variable. The goal of {\sc ontram}s is to estimate a flexible outcome distribution based on a set of predictors including images and tabular data while keeping components of the model interpretable. {\sc ontram}s are able to seamlessly integrate both types of data with varyingly complex interactions between the two, by taking a modular approach to model building. The data analyst can choose the scale on which to interpret image and tabular predictor effects, such as the odds or hazard scale, by specifying the simple distribution function $F_\rZ$. In addition, the data analyst has full control over the complexity of the individual model components. The discussed {\sc ontram}s will contain at most three (deep) neural networks for the intercepts in the transformation function, the tabular and the image data. Together with the simple distribution function $F_\rZ$ the output of these neural networks will be used to evaluate the NLL loss. In the end, the NNs, which control the components of the model, are jointly fit by standard deep learning algorithms based on stochastic gradient descent. In this work, we feature convolutional neural networks (CNNs) for complex input data like images. However, the high modularity of {\sc ontram}s enables many more applications such as recurrent neural networks for text-based models. \subsection{Organization of this Paper} \label{sec:orga} We first describe the necessary theoretical background of multi-class classification and ordinal regression. Afterwards, an outline of related work is given in Section~\ref{sec:related} to highlight the contributions of {\sc ontram}s to the field. We then provide details about {\sc ontram}s in Section~\ref{sec:ontram}. Subsequently, we describe the data sets, experiments, and models we use to study and benchmark {\sc ontram}s (Section~\ref{sec:experiments}). We end this paper with a discussion of our results and juxtaposition of the different approaches in light of model complexity, interpretability, and predictive performance. We present further results in Appendix~\ref{app:learnspeed} and complement our discussion of different loss functions and evaluation metrics in Appendices~\ref{app:qwk}~and~\ref{app:scoring}, respectively. Because most state-of-the-art approaches to ordinal outcomes are classifiers, we particularly highlight the distinction between ordinal classification and the proposed regression approach of {\sc ontram}s in Appendix~\ref{app:resqwk}. \section{Background} \label{sec:background} First, we will describe the multi-class classification approach frequently applied in deep learning, which will serve as a baseline model in our experiments. We outline cumulative ordinal regression models as the statistical approach to ordinal regression and how they can be viewed as a special case of transformation models. In the end we summarize related work in the field of deep ordinal regression and classification and interpretable machine learning. \subsection{Multi-class Classification} \label{sec:mcc} Deep learning prediction models for multi-class classification (MCC) are based on a NN whose output layer contains $K$ units and uses a softmax as the last-layer activation function to predict a probability for each class. The softmax function is defined as \begin{align} p_k = \softmax(s_k) = \frac{\exp(s_k)}{\sum_{j=1}^K \exp(s_j)}, \end{align} where $s_k$ is the value of unit $k$ before applying the activation function. Typically, a MCC model is trained by minimizing the categorical cross-entropy loss. The categorical cross-entropy is computed over $n$ samples by \begin{align} \label{eq:cce} \text{CE} := - \sum_{i=1}^n \sum_{k=1}^K y_{ki} \log \mathbb{P}(Y=y_{ki} \rvert \boldsymbol x} \def \mX {\boldsymbol X_i) = - \sum_{i=1}^n \log \mathcal L_i, \end{align} with $y_{ki}$ being entry $k$ of the one-hot-encoded outcome for input $\boldsymbol x} \def \mX {\boldsymbol X_i$, which is one for the observed class and zero otherwise. The probability for the observed class is the likelihood contribution $\mathcal L_i$ of the $i$th observation. It is well known that the cross-entropy loss is equivalent to the negative log-likelihood for multinomial outcome variables (see Figure~\ref{fig:ordinal}~A and B). Moreover, Eq.~\eqref{eq:cce} highlights that the likelihood is a local measure because solely the predicted probability for the observed class contributes to the loss. That is, in case of ordinal outcomes, the outcome's natural order is ignored. Note that MCC models as defined above are referred to as multinomial regression in the statistical literature, highlighting the fact that they predict an entire probability distribution instead of a single class (see Appendix~\ref{app:resqwk}). \subsection{Ordinal Regression Models} Ordinal regression aims to characterize the whole conditional distribution of an ordinal outcome variable given its predictors. A discussion of ordinal regression and how they can be viewed as transformation models is given in the following. \subsubsection{Cumulative Ordinal Regression Models} The goal of the statistical approach to ordinal regression is mainly to develop an interpretable model for the conditional distribution of the ordered outcome variable $Y$ with $K$ possible values $y_1 < y_2 < \dots < y_K$. Before discussing how interpretable model components are achieved, we discuss the question of how the order of the outcome can be taken into account. The distribution of an outcome variable is fully determined by its probability density function (PDF). For an ordinal outcome the PDF describes the probabilities of the different classes, which is equivalent to the PDF of an unordered outcome. Yet, unlike an unordered outcome an ordered outcome possesses a well defined cumulative distribution function (CDF) $F_\rY$, which naturally contains the order. The CDF $F_\rY(y_k) = \mathbb{P}(Y \leq y_k)$ is a step function, which takes values between zero and one and describes the probability of an outcome $Y$ of being smaller or equal to a specific class. The steps are positioned at $y_k$, $k = 1,\dots,K$ and the heights of the steps correspond to the probability $\mathbb{P}(Y = y_ k) = F_\rY(y_k) - F_\rY(y_{k-1}) =: \mathcal L_i$ of observing class $k$ (\emph{cf.}~Figure~\ref{fig:ordinal}~A and B). As indicated in the previous subsection, the likelihood contribution for an observation $(y_{ki}, \boldsymbol x} \def \mX {\boldsymbol X_i)$ is given by the predicted probability for the observed class, which can be rewritten as \begin{align} \mathcal L_i = \mathbb{P}(Y=y_{ki} \rvert \boldsymbol x} \def \mX {\boldsymbol X_i) = \mathbb{P}(Y\leqy_{ki} \rvert \boldsymbol x} \def \mX {\boldsymbol X_i) - \mathbb{P}(Y\leqy_{(k-1)i} \rvert \boldsymbol x} \def \mX {\boldsymbol X_i), \end{align} for $k = 1,\dots,K-1$ and $\mathbb{P}(Y \leq y_0) := 0$, $\mathbb{P}(Y \leq y_K) = 1$. Parametrizing the likelihood contributions using the CDF directly enables to incorporate the order of the outcome when formulating regression models for ordinal data (Section~\ref{sec:ontram}). It is worth noting that the loss is still the same negative log likelihood as in eq.~\eqref{eq:cce} merely using a different parametrization to take the outcome's natural order into account. \begin{figure}[!ht] \center \includegraphics[width=0.7\textwidth]{figures/figure1_ordinal.pdf} \caption{ Density and distribution function for an ordered outcome with five classes. (A) The probability density function (PDF) describes the probability of the outcome belonging to class $k$. (B) The cumulative distribution function (CDF) describes the probability of the outcome belonging to any class below and including class $k$. The heights of the steps correspond to the probability of belonging to class $k$, which are given by the PDF. Panels C and D depict the PDF and CDF of the latent variable $Z$ and illustrate the equivalence between modelling on the scale of $Y$ and $Z$. For brevity the cut points are denoted by $h_k := h(y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X)$. Note that $h_5 = + \infty$ gives rise to the yellow area corresponding to the conditional probability of $Y$ belonging to the fifth class, but does not show on the $x$-axis in panels C and D. }\label{fig:ordinal} \end{figure} Many ordinal regression models assume the existence of an underlying continuous latent variable (an unobserved quantity) $Z$. Sometimes field experts can give an interpretation for the latent variable $Z$, e.g., the degree of illness of a patient. The ordinal outcome variable $Y$ is understood as a categorized version of $Z$ resulting from incomplete knowledge; we only know the classes in terms of the intervals in which $Z$ lies. Fitting an ordinal regression model based on the latent variable approach aims at finding cut points $h(y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X)$ at which $Z$ is separated into the assumed classes (see Figure~\ref{fig:ordinal}~C). This is done by setting up a monotonically increasing step function $h$ that transforms the ordinal class values into cut points that retain the order (see Figure~\ref{fig:trafo}). Even if $Z$ can not be interpreted directly, using a latent variable approach has advantages, because the chosen distribution of $Z$ determines the interpretability of the terms in the transformation function (see section \ref{sec:interpretation}). Moreover, the latent variable approach enables to understand ordinal regression as a special case of parametric transformation models, which were recently developed in statistics \citep{hothorn2014conditional} and are applicable to a wide range of outcomes with natural extensions to classical machine learning techniques such as random forests and boosting. Transformation models are able to model highly flexible outcome distributions while simultaneously keeping specific model components interpretable. In transformation models the conditional outcome distribution of $(Y\rvert\boldsymbol x} \def \mX {\boldsymbol X)$ is modeled by transforming the outcome variable $(Y\rvert\boldsymbol x} \def \mX {\boldsymbol X)$ to a variable $(Z\rvert\boldsymbol x} \def \mX {\boldsymbol X)$ with known (simple) CDF $F_\rZ$, like the Gaussian or logistic distribution. Transformation models in general are thus defined by \begin{align} F_\rY(y \rvert \boldsymbol x} \def \mX {\boldsymbol X)=F_\rZ(h(y \rvert \boldsymbol x} \def \mX {\boldsymbol X)), \end{align} and all models in our proposed framework of {\sc ontram}s are of this form. \begin{figure}[!ht] \center \includegraphics[width=0.7\textwidth]{figures/figure2_trafo.pdf} \caption{ Transformation model likelihoods for a model with ordinal outcome. Panel C shows the conditional density of $Y$ given $\boldsymbol x} \def \mX {\boldsymbol X$, which gets mapped onto the density of the latent variable $Z$ (A) via the transformation function $h$ (B). The likelihood contributions are in fact probabilities and given by the area under the density of $Z$ between two consecutive cut points in the transformation function. Note that $h(y_5 \rvert \boldsymbol x} \def \mX {\boldsymbol X) = +\infty$ does not show on the plot for the transformation function, but is evident from the yellow area under the density of $Z$. }\label{fig:trafo} \end{figure} The first step to set up an ordinal transformation model is to choose a continuous distribution for $Z$, which determines the interpretational scale of the effect of a predictor on the outcome (see~Section~\ref{sec:interpretation}). The goal is then to fit a monotonically increasing transformation function $h$, which maps the observed outcome classes $(y_k\rvert\boldsymbol x} \def \mX {\boldsymbol X)$ to the conditional cut points \begin{align} h(y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X), \; k = 1, \dots, K - 1, \end{align} of the latent variable $Z$, as illustrated in Figure~\ref{fig:trafo}. In the example in Figure~\ref{fig:trafo} the outcome can take five classes and the $K-1$ cut points $h(y_1\rvert\boldsymbol x} \def \mX {\boldsymbol X)$, $h(y_2\rvert\boldsymbol x} \def \mX {\boldsymbol X)$, $h(y_3\rvert\boldsymbol x} \def \mX {\boldsymbol X)$, and $h(y_4\rvert\boldsymbol x} \def \mX {\boldsymbol X)$ have to be estimated. The first class of $Y$ on the scale of $Z$ is given by the interval $(-\infty, h(y_1\rvert\boldsymbol x} \def \mX {\boldsymbol X)]$, the fifth class as $(h(y_4\rvert\boldsymbol x} \def \mX {\boldsymbol X),+\infty)$, so often the conventions $h(y_0\rvert\boldsymbol x} \def \mX {\boldsymbol X) = - \infty$ and $h(y_K\rvert\boldsymbol x} \def \mX {\boldsymbol X) = + \infty$ are used. The likelihood contribution of a given observation $(y_{ki},\boldsymbol x} \def \mX {\boldsymbol X_i)$ can now be derived from the CDF of $Z$ instead of $Y$ and is given by \begin{align} \mathcal L_i(h;y_{ki}, \boldsymbol x} \def \mX {\boldsymbol X_i) &= \mathbb{P}(Y=y_{ki} \rvert \boldsymbol x} \def \mX {\boldsymbol X_i) \nonumber \\ &= F_\rY(y_{ki} \rvert \boldsymbol x} \def \mX {\boldsymbol X_i) - F_\rY(y_{(k-1)i} \rvert \boldsymbol x} \def \mX {\boldsymbol X_i) \nonumber \\ &= F_\rZ(h(y_{ki} \rvert \boldsymbol x} \def \mX {\boldsymbol X_i)) - F_\rZ(h(y_{(k-1)i} \rvert \boldsymbol x} \def \mX {\boldsymbol X_i)). \end{align} The single likelihood contributions are the heights of the steps in the CDF or equivalently the area under the density of the latent variable $Z$ between two consecutive cut points (\emph{cf.} Figure~\ref{fig:trafo} B, C). Note that two consecutive cut points enter the likelihood, such that the natural order of the outcome is used to parametrize the likelihood, although the likelihood contribution is given by the probability of the observed class alone. Consequently, minimizing the negative log-likelihood \begin{align}\label{eq:nll} - \ell(h;y_{1:n}, \boldsymbol x} \def \mX {\boldsymbol X_{1:n}) = - \sum_{i=1}^n \log \mathcal L_i(h;y_{ki}, \boldsymbol x} \def \mX {\boldsymbol X_i) \end{align} estimates the conditional outcome distribution of $(Y\rvert\boldsymbol x} \def \mX {\boldsymbol X)$ by estimating the unknown parameters of the transformation function, which in our application are the cut points of $Z$. Note that in principle this formulation allows us to directly incorporate uncertain observations, for instance, an observation may lie somewhere in $[y_k,y_{k+2}]$, $k \leq K - 2$ if a rater is uncertain about the quality of a wine or a patient rates their pain in between two classes. \subsubsection{Interpretability in Proportional Odds Models} \label{sec:interpretation} The interpretability of a transformation model depends on the choice of the distribution $F_\rZ$ of the latent variable $Z$ and the transformation function $h$. A summary of common interpretational scales is given in Table~\ref{tab:interpr}. \begin{table}[ht!] \centering \caption{ Interpretational scales of shift terms induced by $F_\rZ$ \citep{tutz2011regression}. Most link functions have been studied in the context of proportional odds model neural networks and a classification loss \citep{vargas2020cumulative}. More details concerning the interpretational scales are given in Appendix~\ref{app:interpretation}. }\label{tab:interpr} \begin{tabular}{llll} \toprule \textbf{$F_Z$} & \textbf{$F_Z^{-1}$} & \textbf{Symbol} & \textbf{Interpretation of shift terms} \\ \midrule Logistic & $\logit$ & $F_{\SL}$ & log odds-ratio \\ Gompertz & cloglog & $F_{\MEV}$ & log hazard-ratio \\ Gumbel & loglog & $F_{\text{Gumbel}}$ & log hazard-ratio for $Y_r = K + 1 - Y$\\ Normal & probit & $\Phi$ & not interpretable directly \\ \bottomrule \end{tabular} \end{table} Here, we demonstrate interpretability through the example of a proportional odds model, which is well known in statistics \citep{tutz2011regression}. For the distribution of $Z$ we choose the standard logistic distribution (denoted by $F_{\SL}$), whose CDF is given by $F_\rZ(z) = F_{\SL}(z) := (1 + \exp(-z))^{-1}$. The transformation function $h$ is parametrized as \begin{align} \label{eq:simp_shift} h(y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X) = \vartheta_k - \sum_{j=1}^J \beta_j x_j = \vartheta_k - \rx^\top\shiftparm, \; j = 1, \dots, J. \end{align} A transformation model with such a transformation function is called linear shift model, since a change $\Delta x_j$ in a single predictor $x_j$ causes a linear shift of size $\beta_j \Delta x_j$ in the transformation function. In Figure~\ref{fig:conditional} this is visualized for an outcome $y_k$ depending on a single predictor $x$, which is increased by one unit (here from 0 to 1). This increase results in a simple shift of size $\beta$ in the transformation function (Figure~\ref{fig:conditional}~B). However, the resulting conditional distribution changes in a more complex way (Figure~\ref{fig:conditional}~A). Note that the shape of the transformation function $h$ does not depend on $x$ and stays unchanged while it is shifted downwards. \begin{figure}[!ht] \center \includegraphics[width=0.9\textwidth]{figures/figure3_conditional-polr.pdf} \caption{ The conditional probability density, transformation function and latent representation of the ordinal outcome $Y$ with 5 classes depending on a single predictor $x$ which is increased by $\Delta x = 1$ from 0 to 1. The density of $(Y \rvert x)$ for $x=0$ and $x=1$ is shown in A. The simple linear shift model (see eq.~\eqref{eq:simp_shift}) imposes a downward shift of the transformation function by $\beta$ when increasing the predictor from $x=0$ to $x=1$ (B). The shift in the transformation function translates into a shift in the conditional cut points $h(y_k\rvert\boldsymbol x} \def \mX {\boldsymbol X)$ under the density of the latent variable $Z$ (C). Shifting the transformation function downwards results in higher probabilities of $Y$ belonging to a higher class. }\label{fig:conditional} \end{figure} The popularity of this transformation model with $F_\rZ = F_{\SL}$ is due to the insightful interpretation of the parameter $\beta_j$ as demonstrated in the following. Based on the simple distribution $F_\rZ$ and the transformation function $h$, the odds for the outcome to belong to a class higher than class $y_k$ can be written as \begin{align} \odds(Y > y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X) &= \frac{\mathbb{P}(Y > y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X)}{\mathbb{P}(Y \leq y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X)} = \frac{1-F_\rY(y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X)}{F_\rY(y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X)} \nonumber \\ &= \frac{1-F_\rZ(h(y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X))}{F_\rZ(h(y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X))} = \frac{1-F_{\SL}(\vartheta_k - \rx^\top\shiftparm)}{F_{\SL}(\vartheta_k - \rx^\top\shiftparm)}. \end{align} When increasing the predictor $x_j$ by one unit and holding all other predictors constant we change the vector $\boldsymbol x} \def \mX {\boldsymbol X$ to $\boldsymbol x} \def \mX {\boldsymbol X'$ and obtain, after some basic mathematical transformation (\emph{cf.}~Appendix~\ref{app:interpretation}), \begin{align} \odds(Y > y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X') &= \frac{1-F_{\SL}(\vartheta_k - \boldsymbol x} \def \mX {\boldsymbol X'^\top\text{\boldmath$\beta$})}{ F_{\SL}(\vartheta_k - \boldsymbol x} \def \mX {\boldsymbol X'^\top\text{\boldmath$\beta$})} = \frac{1-F_{\SL}(\vartheta_k - \rx^\top\shiftparm - \beta_j)}{ F_{\SL}(\vartheta_k - \rx^\top\shiftparm - \beta_j)} \\ &= \odds(Y > y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X) \cdot \exp(\beta_j) \nonumber. \end{align} Note that the odds change by a constant factor $\exp(\beta_j)$ independent of $k$. Hence, the parameter $\beta_j$ in the linear shift term can be interpreted as the log-odds ratio of the outcome belonging to a higher outcome class than $y_k$ when increasing the predictor $x_j$ by one unit and holding the remaining predictors constant with \begin{align} \log\OR_{\boldsymbol x} \def \mX {\boldsymbol X\to\boldsymbol x} \def \mX {\boldsymbol X'} = \log\left(\frac{\odds(Y > y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X')}{\odds(Y > y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X)}\right) = \beta_j. \end{align} This is depicted in Figure~\ref{fig:conditional} for a positive valued $\beta$, where the effect of increasing the corresponding feature by one unit increases the odds for the outcome to belong to a higher class. More specific, the odds of the outcome for a higher class than $y_k$ is increased by a factor $\exp(\beta_j)$, which holds for each $y_k$. Because the effect of $\beta$ is the same for each class boundary these models are referred to as proportional odds models \citep{tutz2011regression}. \subsection{Related Work} \label{sec:related} Prediction models for ordinal outcomes have been studied in machine learning as extensions of different popular methods like Gaussian Processes \citep{chu2005gaussian}, support vector machines \citep{chu2007support}, and neural networks \citep{cardoso2007learning}. With the advent of deep learning, various approaches have been proposed to tackle classification and regression tasks with ordinal outcomes, which we describe in more detail in the following. Note that we refer to models, which aim to predict a valid entire conditional outcome distribution as ordinal \emph{regression} models, whereas models, which focus on the predicted class label will be referred to as ordinal \emph{classification} models. For instance, the MCC model described in Section~\ref{sec:background} is a regression model (\textit{i.e.}~ multinomial regression), whereas most of the state-of-the-art approaches described below are ordinal classifiers. In the following we discuss literature on ordinal classification and literature related to different aspects of our work, \textit{i.e.}~ regression models, transformation models, and interpretability. \paragraph{Ordinal classification} Deep learning approaches to ordinal regression and classification problems range from using an ordinal metric for the evaluation of multi-class classification models to the construction of novel ordinal loss functions and dummy encodings. The earliest approaches made use of the equivalence of an ordinal prediction problem with outcome $Y \in \{y_1<\dots<y_K\}$, to the $K-1$ binary classification problems given by $\mathbbm{1}(Y\leqy_k)$, $k = 1,\dots,K$ \citep{frank2001simple}, which is still being used in applications such as age estimation \citep{niu2016ordinal}. \citet{cheng2008neural} devised a cumulative dummy encoding for the ordinal response where for $Y=y_k$ we have $y_i = 1$ if $i\leq k$ and 0 otherwise. \citeauthor{cheng2008neural} then suggest a sigmoid activation for the last layer of dimension $K$, together with two loss functions (relative entropy and a squared error loss). Similar approaches remain highly popular in application. For instance, \citet{cao2019rank} extend the approach to rank-consistent ordinal predictions. The problem of rank inconsistency, however, is confined to the $K$-rank and similar approaches and does not appear in ordinal regression models, such as the ones we propose. \citet{xie2019deep} used a similar dummy encoding to train $K-1$ binary classifiers, which share a common CNN trunk for image feature extraction but possess their own fully connected part. This allows flexible feature extraction while reducing model complexity substantially due to weight sharing. Weight sharing is a natural advantage of models which are trained with an ordinal loss function instead of multiple binary losses, which we describe next. A comparison of {\sc ontram} against the method described in \citet{xie2019deep} can be found in Appendix~\ref{app:resqwk}. Recently, the focus shifted towards novel ordinal loss functions involving Cohen's kappa, which was first proposed by \citep{de2018weighted} and subsequently used in ``proportional odds model (POM) neural networks'' \citep{vargas2019deep}. POM neural networks and their extensions to other cumulative link functions in \citep{vargas2020cumulative} are closely related to {\sc ontram}s, proposed in this paper, because they constitute a special case in which the class-specific intercepts do not depend on input data (see Section~\ref{sec:ontram}). The crucial difference between POM NNs (as proposed in \citep{vargas2019deep}) and {\sc ontram}s is the quadratic weighted Cohen's kappa (QWK) loss function in POM NNs, compared to a log-likelihood loss in {\sc ontram}s. Although POM NNs predict a full conditional outcome distribution, their focus lies on optimizing a classification metric (QWK). The idea is to penalize misclassifications that are further away from the observed class stronger than misclassifications that are closer to the observed class. In contrast, in regression approaches, the goal is to predict a valid probability distribution across all classes. We give more detail on and compare our proposed method against the QWK loss in Appendices~\ref{app:qwk}~and~\ref{app:resqwk}, respectively. We use QWK-based models as an example to address the general problem arising when comparing classification and regression models, which address different questions and hence optimize distinct target functions. \paragraph{Ordinal regression} Lastly, \citet{liu2019probabilistic} took a probabilistic approach using Gaussian processes with an ordinal likelihood similar to the cumulative probit model (cumulative ordinal model with $F_\rZ=\Phi$) and a model formulation similar to POM neural networks. We address further related work concerning technical details in Section~\ref{sec:ontram}, such as the explicit formulation of constraints in the loss function. \paragraph{Transformation models} Deep conditional transformation models have very recently been applied to regression problems with a continuous outcome \citep{sick2020deep, baumann2020deep}. Both approaches, as well as our contribution, can be seen as special cases of semi-structured deep distributional regression, which was proposed by \citet{rugamer2020unifying}. \citeauthor{sick2020deep} parametrized the transformation function as a composition of linear and sigmoid transformations and a flexible basis expansion that ensures monotonicity of the resulting transformation function. The authors applied deep transformation models to a multitude of benchmark data sets with a continuous outcome and demonstrated a performance that was comparable to or better than other state-of-the-art models. However, in one of the benchmark data set the authors treated a truly ordinal outcome as continuous, as done by all the other benchmark models. This is indicative for the lack of deep learning models for ordered categorical regression. \paragraph{Interpretability} In general, deep learning models suffer from a lack of interpretability of the predictions they make \citep{goodfellow2016deep}. In DL models related to image data, interpretability is mostly referred to as highlighting parts of the image that explain the respective prediction. Often, surrogate models are build on top of the black-box model's predictions, which are easier to interpret. One such model is LIME \citep{ribeiro2016should}. For problems with an ordinal outcome, \citet{amorim2018interpreting} comment on the limited interpretability of the ensemble of neural networks in the $K$-rank approach described above and propose to use a mimic learning technique, which combines the ensemble with a more directly interpretable model. In the present work we take a different approach to interpretability rooted in statistical regression models. The interpretability of the effect of individual input features is given by the fitted model parameters in an additive transformation function, which is a common modelling choice for achieving interpretability \citep{rudin2018stop}. \citet{agarwal2020neural} take the same approach in the framework of generalized additive models (GAMs). We give more detail in Section~\ref{sec:interpretation} and Appendix~\ref{app:interpretation}. \section{Ordinal Neural Network Transformation Models} \label{sec:ontram} Here, we present ordinal neural network transformation models, which unite cumulative ordinal regression models with deep neural networks and seamlessly integrate complex data like images ($\mathsf{B}$) and/or tabular data ($\boldsymbol x} \def \mX {\boldsymbol X$). At the heart of an {\sc ontram} lies a parametric transformation function $h(y_k\rvert \boldsymbol x} \def \mX {\boldsymbol X, \mathsf{B})$, which transforms the ordinal outcome $y_k$ to cut points of a continuous latent variable and controls the interpretability and flexibility of the model (see Figure~\ref{fig:trafo}). The ordering of the outcome is incorporated in the {\sc ontram} loss function by defining it via the cumulative distribution function \begin{align}\label{ontram_nll} \text{NLL} := - \frac{1}{n} \sum_{i=1}^n \log \left( F_\rZ(h(y_{ki} \rvert \boldsymbol x} \def \mX {\boldsymbol X_i, \mathsf{B}_i)) - F_\rZ(h(y_{(k-1)i} \rvert \boldsymbol x} \def \mX {\boldsymbol X_i, \mathsf{B}_i)) \right). \end{align} In the following we describe the terms of the parametric transformation function and their interpretability. The parameters of these terms are controlled by NNs, which are jointly fitted in an end-to-end fashion by minimizing the NLL (Figure~\ref{fig:ONTRAMarchitecture}). \begin{figure}[!ht] \center \includegraphics[width=0.85\textwidth]{figures/figure4_ONTRAM_v2.pdf} \caption{ Architecture building blocks of {\sc ontram}s. A: Simple intercept and linear shift terms are modeled using a single-layer neural network. Complex intercept and complex shift terms are allowed to depend on the input data in a more complex manner and may be a fully connected or convolutional NN depending on the type of the input data. The input data $D$ can be a single tabular predictor $x_j$ or a set of tabular predictors $\boldsymbol x} \def \mX {\boldsymbol X$ or images $\mathsf{B}$. B: The output of the NNs control the additive components of the transformation function $h$. Together with the choice of $F_\rZ$, $h$ determines the full model, from which the likelihood can be evaluated. During training time (solid lines) the weights of all model components are trained jointly by minimizing the NLL. After training (dashed lines) the shift terms in the transformation function can be interpreted, the conditional outcome distribution can be predicted and the NLL can be evaluated for a given test set. }\label{fig:ONTRAMarchitecture} \end{figure} \paragraph{Modularity} The transformation function, which determines the complexity and interpretability of an {\sc ontram}, consists of an intercept term, optionally followed by additive shift terms, which depend in a more or less complex manner on different input data and are controlled by NNs (see Figure~\ref{fig:ONTRAMarchitecture}). The intercept term controls the shape of the transformation function: \begin{enumerate} \item Simple intercepts (SI) $\vartheta_k$, $k=1,\dots,K-1$ are unconditional, i.e. the shape of the transformation function is independent of the input data. SIs can be modeled as a single layer neural network with $K-1$ output units and linear activation function. The input is given by 1. The outputs are given by $\gamma_1,\dots,\gamma_{K-1}$ controlling the intercepts (see Figure~\ref{fig:ONTRAMarchitecture}). \item Complex intercepts (CI), on the other hand, depend on the input data, which may be tabular data, image data or a combination of both, yielding $\vartheta_k(\boldsymbol x} \def \mX {\boldsymbol X)$, $\vartheta_k(\mathsf{B})$, or $\vartheta_k(\boldsymbol x} \def \mX {\boldsymbol X,\mathsf{B})$, respectively. CIs enable more complex transformation functions, whose shape may vary with the input. Depending on the type of input data, CIs are modeled using a multi-layer fully connected neural network, a convolutional neural network or a combination of both. Analogous to SI terms, the number of output units in the last layer is equal to $K-1$ with linear activation function, yielding $\gamma_1(\boldsymbol x} \def \mX {\boldsymbol X, \mathsf{B}), \dots, \gamma_{K-1}(\boldsymbol x} \def \mX {\boldsymbol X, \mathsf{B})$ depending on the input (see upper right panel in Figure~\ref{fig:ONTRAMarchitecture}). \end{enumerate} To ensure that the transformation function is non-decreasing, the outputs $\gamma_1, \dots, \gamma_{K-1}$ of simple and complex intercept models are transformed before entering the likelihood via \begin{align} \label{eq:constraints} \begin{split} \vartheta_k &= \vartheta_1 + \sum_{i = 2}^k \exp(\gamma_i), \quad k = 2, \dots, K - 1, \\ \vartheta_0 &= - \infty, \; \vartheta_1 = \gamma_1, \; \vartheta_K = + \infty. \end{split} \end{align} The addition of $\vartheta_0 = - \infty$ and $\vartheta_K = + \infty$ is important for computing the loss as described in Section~\ref{sec:background}. Enforcing a monotone increasing transformation function via eq.~\eqref{eq:constraints}, such that $\vartheta_0 < \vartheta_1 \leq \dots < \vartheta_K$, has been done similarly in the literature. In what \citet{cheng2008neural} call threshold models, $\gamma_i$ is squared instead of taking the exponential to ensure the intercept function is non-decreasing \citep{liu2019probabilistic,vargas2020cumulative}. A different but related approach is to softly penalize the loss for pair-wise rank inconsistencies using a hinge loss \citep{liu2017deep,liu2018constrained}. Note that the special case $\vartheta_k(\boldsymbol x} \def \mX {\boldsymbol X,\mathsf{B})$ already includes both tabular and image data. That is, the transformation function and therefore the outcome distribution is allowed to change with each input $\boldsymbol x} \def \mX {\boldsymbol X$ and $\mathsf{B}$, which represents the most flexible model possible. In fact, this most flexible {\sc ontram} is equivalent to a MCC model with softmax as last-layer activation function and a categorical cross-entropy loss, albeit parametrized differently to take the order of the outcome into account. Shift terms impose data dependent vertical shifts on the transformation function: \begin{enumerate} \item Linear shift (LS) terms $\rx^\top\shiftparm$ are used for tabular features and are directly interpretable (see Section \ref{sec:interpretation}). The components of the parameter $\text{\boldmath$\beta$}$ can be modeled as the weights of a single layer neural network with input $\boldsymbol x} \def \mX {\boldsymbol X$, one output unit with linear activation function and without a bias term (see lower left panel in Figure~\ref{fig:ONTRAMarchitecture}). \item Complex shift (CS) terms depend on tabular predictors or image data. Complex shift terms are modeled using flexible dense and/or convolutional NNs with input $\boldsymbol x} \def \mX {\boldsymbol X$ and/or $\mathsf{B}$, and a single output unit with linear activation (see lower right panel in Figure~\ref{fig:ONTRAMarchitecture}). Similar to linear shift terms, the output of $\beta$ and $\eta$ can be interpreted as the log odds of belonging to a higher class, compared to all lower classes, if $F_\rZ=F_{\SL}$. Again, this effect is common to all class boundaries. In contrast to a linear shift term, we can model a complex shift for each tabular predictor $\beta(x_j)$ akin to a generalized additive model. Alternatively, we can model a single complex shift $\beta(\boldsymbol x} \def \mX {\boldsymbol X)$ for all predictors, which allows for higher order interactions between the predictors. This way, the interpretation of an effect of a single predictor is lost in favour of higher model complexity. \end{enumerate} \paragraph{Interpretability and flexibility} In the following, we will present a non-exhaustive collection of {\sc ontram}s integrating both tabular and image data. We start to introduce the least complex model with the highest degree of interpretability and end with the most complex model with the lowest degree of interpretability. The simplest {\sc ontram} conditioning on tabular data $\boldsymbol x} \def \mX {\boldsymbol X$ and image data $\mathsf{B}$ is given by \begin{align} h(y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X, \mathsf{B}) = \vartheta_k - \rx^\top\shiftparm - \eta(\mathsf{B}), \end{align} where $\vartheta_k$ is a simple intercept corresponding to class $k$, $\text{\boldmath$\beta$}$ is the weight vector of a single layer NN as described above and $\eta(\mathsf{B})$ the output of a CNN (Figure~\ref{fig:ONTRAMarchitecture}~A). In this case, $\text{\boldmath$\beta$}$ and $\eta$ can be interpreted as cumulative log odds-ratios when choosing $F_\rZ = F_{\SL}$ (see Section~\ref{sec:interpretation}). The above model can be made more flexible, yet less interpretable, by substituting the linear predictor for a more complex neural network $\beta$, such that \begin{align} h(y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X, \mathsf{B}) = \vartheta_k - \beta(\boldsymbol x} \def \mX {\boldsymbol X) - \eta(\mathsf{B}), \end{align} where $\beta(\boldsymbol x} \def \mX {\boldsymbol X)$ is now a log odds ratio function that allows for higher order interactions between all predictors in $\boldsymbol x} \def \mX {\boldsymbol X$. For instance, one may be interested in the odds ratio $\OR_{\mathsf{B} \to \mathsf{B}'}$ of belonging to a higher category when changing an image $\mathsf{B}$ to $\mathsf{B}'$ and holding all other variables constant. As a special case, complex shifts include an additive model formulation in the spirit of generalized additive models (GAMs) by explicitly parametrizing the effect of each predictor $x_j$ with a single neural network $\beta_j$ \citep{agarwal2020neural} \begin{align} \label{eq:gam_shift} h(y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X, \mathsf{B}) = \vartheta_k - \sum_{j=1}^J \beta_j(x_j) - \eta(\mathsf{B}), \; j = 1, \dots, J. \end{align} For $F_\rZ = F_{\SL}$ the complex shift term $\beta_j(x)$ can be interpreted as a log-odds ratio for the outcome to belong to a higher class than $y_k$ compared to the scenario where $\beta_j(x)=0$, all other predictors kept constant. Another layer of complexity can be added by allowing the intercept function $\vartheta_k$ for $Y = y_k$, to depend on the image \begin{align} h(y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X, \mathsf{B}) = \vartheta_k(\mathsf{B}) - \beta(\boldsymbol x} \def \mX {\boldsymbol X). \end{align} In this transformation function we call $\vartheta_k(\mathsf{B})$ complex intercept, because the intercept function is allowed to change with the image (Figure~\ref{fig:ONTRAMarchitecture}~A). One does not necessarily have to stop here. Including both the image and the tabular data in a complex intercept \begin{align} h(y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X, \mathsf{B}) = \vartheta_k(\boldsymbol x} \def \mX {\boldsymbol X, \mathsf{B}) \end{align} represents the most flexible model whose likelihood is equivalent to the one used in MCC models, solely with a different parametrization. Consequently, solely the most flexible {\sc ontram}s achieve on-par performance compared with deep classifiers trained using the cross-entropy loss, while the less flexible {\sc ontram}s are attractive because of their easier interpretability. In fact, we illustrate empirically that a minor trade-off in predictive performance leads to a considerable ease in interpretation. \paragraph{Computational details} The parameters of an {\sc ontram} are jointly trained via stochastic gradient descent. The parameters enter the loss function via the outputs of the simple/complex intercept and shift terms modeled as neural networks (see Figure~\ref{fig:ONTRAMarchitecture}~A). The gradient of the loss with respect to all trainable parameters is computed via automatic differentiation in the \texttt{TensorFlow} framework. Note that any pre-implemented optimizer can be used and that there are no constraints on the architecture of the individual components besides their last-layer dimension and activation function. \section{Experiments} \label{sec:experiments} We perform several experiments on data with an ordinal outcome to evaluate and benchmark {\sc ontram}s in terms of prediction performance and interpretability. For the experiments we use two publicly available data sets as presented in the following section. In addition, we simulate tabular predictors to assess estimation performance for the effect estimates in {\sc ontram}s. \subsection{Data} \label{sec:data} \paragraph{UTKFace} UTKFace contains more than 23000 images of faces belonging to all age groups \citep[dataset][]{utkface}. The ordinal outcome is determined by age using the classes baby (0--3, $n_0 = 1894$), child (4--12, $n_1 = 1519$), teenager (13--19, $n_2 = 1180$), young adult (20--30 $n_3 = 8068$), adult (31--45, $n_4 = 5433$), middle aged (46--61, $n_5 = 3216$) and senior ($>$61, $n_6 = 2395$) \citep[dataset][]{das2018}. The images are labeled with the people’s age (0 to 116) from which the age-class is determined. In addition, the data set provides the tabular feature sex (female, male). As our main goal is not on performance improvement but on the evaluation of our proposed method, we use the already aligned and cropped versions of the images. For some example images see Figure~\ref{fig:images}. \begin{figure}[!ht] \centering \includegraphics[width=\textwidth]{figures/figure5_Example_images_UTKFace.pdf} \vspace{-0.8cm} \caption{ Example images for UTKFace. Example images of the seven ordinal age-classes (baby, child, teenager, young adult, adult, middle aged and senior) of the cropped and aligned UTKFace data set are presented. } \label{fig:images} \end{figure} We simulate tabular predictors $\boldsymbol x} \def \mX {\boldsymbol X$ with predefined effects on the ordinal outcome of the UTKFace data set, where we assume a proportional odds model $F_\rY(y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X) = F_\rZ(\vartheta_k - \rx^\top\shiftparm)$ (see Section \ref{sec:interpretation}). The simulation scheme is closely related to choice-based sampling \citep{manski1977estimation}. Ten predictors are simulated, four of which are noise predictors that have no effect on the outcome. The six informative predictors are simulated to have an effect of $\pm \log 1.5$, $\pm \log 2$ and $\pm \log 3$ on the log-odds scale, to reflect small to large effect sizes commonly seen in medical and epidemiological applications. All predictors are mutually independent of each other and the image data. The predictors are simulated from the conditional distribution $X_j \rvert \boldsymbol{y} \sim \mathcal N(\boldsymbol{y}^\top\boldsymbol\xi_j, \sigma^2)$, where $\boldsymbol{y}$ denotes the one-hot encoded outcome and $(\boldsymbol\xi_j)_k = k \cdot \beta_j$ for $k = 1, \dots, K$, to emulate the proportional odds property. All simulated predictors have a common variance of $\sigma^2 = 1.55^2$, which was tuned such that the estimated $\hat\beta_j$ on average recovers the true $\beta_j$ when estimating the conditional distribution $Y \rvert \boldsymbol x} \def \mX {\boldsymbol X$ in a proportional odds model. A summary of the simulation procedure is given in Figure~\ref{fig:sim}. \begin{figure}[!ht] \centering \resizebox{0.6\textwidth}{!}{% \begin{tikzpicture}[auto, Arr/.style={-{Latex[length=1.5mm]}}] \node (X2) {$X_{\{2, 3\}}$}; \node (Xn) [below =1.5cm of X2] {$X_{\{1, 4, 7, 10\}}$}; \node [below =1.5cm of Xn] (X5) {$X_{\{5, 6\}}$}; \node [below =1.5cm of X5] (X6) {$X_{\{8, 9\}}$}; \node [right =8cm of Xn] (Y) {$Y$}; \node [right =3cm of Y] (B) {$\mathsf{B}$}; \draw[Arr] (X2) to [bend left=20, "$\pm \log 2$"] (Y); \draw[Arr] (Xn) to ["$0$"] (Y); \draw[Arr] (X5) to [bend right=20, "$\pm \log 1.5$"] (Y); \draw[Arr] (X6) to [bend right=20, "$\pm \log 3$"] (Y); \draw[Arr, dotted] (B) to (Y); \end{tikzpicture} } \caption{Simulation of predictors for UTKFace data. $X_j \stackrel{\iid}{\sim} \ND(0, \sigma^2)$, $j = 1, \dots, 10$, with $\sigma^2 = 1.55^2$. The predictors $X_j$ are simulated such that their effects adhere to the proportional odds assumption. That is, the effect of $\text{\boldmath$\beta$}$ is common to all class boundaries. Note that the arrows indicate effects on the log-odds scale of the outcome $Y$, i.e., $F_\rY(y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X) = F_L(\vartheta_k - \rx^\top\shiftparm)$. The dotted arrow from $\mathsf{B}$ to $Y$ indicates that the image is not entering the simulation directly but is assumed to have an effect on the outcome.} \label{fig:sim} \end{figure} \paragraph{Wine quality} The Wine quality data set consists of 4898 observations \citep[dataset][]{cortez2009modeling}. The ordinal outcome describes the wine quality measured on a scale with 10 levels of which only 6 consecutive classes (3 to 8, $n_3 = 10$, $n_4 = 53$, $n_5 = 681$, $n_6 = 638$, $n_7 = 199$, $n_8 = 18$) are observed. The data set contains 11 predictors, such as acidity, citric acid and sugar content. As in \citet{gal2015dropout}, we consider a subset of the data (red wine, $n = 1599$). \subsection{Models} \label{sec:models} The models we use for evaluating and benchmarking the proposed {\sc ontram}s are summarized in Table~\ref{tab:models}. \begin{table}[!ht] \centering \caption{% Summary of the models used for evaluating the {\sc ontram} methods. In the upper part we list models used for the Wine data, which contain only tabular predictors ($\boldsymbol x} \def \mX {\boldsymbol X$). In the lower part, we show models for the UTKFace data, which consist of image data and tabular predictors $(\boldsymbol x} \def \mX {\boldsymbol X,\mathsf{B})$. Above the thin lines we list the baseline models; below the {\sc ontram}s. For each model, which can be framed as a transformation model, the transformation function is given. Parameters in the shift terms of a transformation function can be interpreted as log odds-ratios if $F_Z$ is chosen to be the standard-logistic distribution. Then, any model involving a simple intercept is an instance of a proportional odds model.} \label{tab:models} \resizebox{\textwidth}{!}{% \begin{tabular}{@{}llll@{}} \toprule \textbf{Data set} & \textbf{Model name} & \textbf{Abbreviation} & \textbf{Trafo} $h(y_k \rvert \boldsymbol x} \def \mX {\boldsymbol X, \mathsf{B})$ \\ \midrule \multirow{8}{*}{UTKFace} & Multi-class classification & MCC & \\ & Multi-class classification + tabular& MCC-$\boldsymbol x} \def \mX {\boldsymbol X$ & \\ \cline{2-4} & Complex intercept & CI$_\mathsf{B}$ & $\vartheta_k(\mathsf{B})$ \\ & Complex intercept + tabular & CI$_\mathsf{B}$-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$ & $\vartheta_k(\mathsf{B}) - \rx^\top\shiftparm$ \\ & Simple intercept + complex shift& SI-CS$_\mathsf{B}$ & $\vartheta_k - \eta(\mathsf{B})$ \\ & Simple intercept + complex shift + tabular& SI-CS$_\mathsf{B}$-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$ & $\vartheta_k - \eta(\mathsf{B}) - \rx^\top\shiftparm$ \\ & Simple intercept + tabular & SI-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$ & $\vartheta_k - \rx^\top\shiftparm$ \\ \midrule \multirow{5}{*}{Wine} & Multi-class classification & MCC & \\ & Generalized additive proportional odds model & GAM & $\vartheta_k - \sum_{j=1}^p \beta_j(x_j)$ \\ & Proportional odds logistic regression & polr & $\vartheta_k - \rx^\top\shiftparm$ \\ \cline{2-4} & Complex intercept & CI$_{\boldsymbol x} \def \mX {\boldsymbol X}$ & $\vartheta_k(\boldsymbol x} \def \mX {\boldsymbol X)$ \\ & Simple intercept + GAM complex shift & SI-CS$^\star_{\boldsymbol x} \def \mX {\boldsymbol X}$ & $\vartheta_k - \sum_{j=1}^p \beta_j(x_j)$ \\ & Simple intercept + linear shift & SI-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$ & $\vartheta_k - \rx^\top\shiftparm$ \\ \bottomrule \end{tabular}} \end{table} These models feature a different flexibility and interpretability and are trained with the different loss functions described in Sections~\ref{sec:background}~and~\ref{sec:ontram}. \subsection{Training and Validation Setup} \label{sec:expsetup} The models are implemented and evaluated on the UTKFace and Wine quality data set as described in the following. The NN architectures used for the different applications are summarized in Appendix~\ref{app:NN}. \paragraph{UTKFace} The UTKFace data set is split into a training (80\%) and a test set (20\%); 20\% of the training set is used as validation data. The images are resized to $128\times128\times3$ pixels. The resized images are normalized to have pixel values between 0 and 1. No further preprocessing is performed. The models are trained for up to 100 epochs with the Adam optimizer with a batch size of 32 and a learning rate of 0.001. Overfitting is addressed with early stopping. That is, we retrospectively search for the epoch in which the validation loss is minimal and consider the respective parameters for our trained models. We analyse the data set using deep ensembling \citep{lakshminarayanan2017simple}, a state of the art approach in probabilistic deep learning methods leading to more reliable probabilistic predictions \citep{wilson2020bayesian}. Specifically, models are trained five times with a different weight initialization in each iteration. The resulting predicted conditional outcome distribution is averaged over the five runs and this averaged conditional outcome distribution is then used for model evaluation. This procedure is supposed to prevent double descent and improve test performance \citep{wilson2020bayesian}. \paragraph{Wine quality} For analyses of the wine quality data we employ the same cross-validation scheme as \citet{gal2015dropout} and split the data into 20 folds of 90\% training and 10\% test data. The predictors are normalized to the unit interval. Otherwise, no further preprocessing is performed. The architectures of the used NNs are described in Appendix \ref{app:NN}. All NNs are jointly trained via stochastic gradient descent using a learning rate of 0.001. The linear shift model is trained for 8000 epochs with a batch size of 90. The {\sc ontram} GAM is trained for 1200 epochs with a batch size of 180. All other models are trained for 100 epochs with a batch size of 6. \subsection{Software} \label{sec:software} We implement MCC models and {\sc ontram}s in the two programming languages \proglang{R} 3.6-3 and \proglang{Python} 3.7. The models are written in \texttt{Keras} based on a \texttt{TensorFlow} backend using \texttt{TensorFlow} version $>$2.0 \citep{chollet2015keras,tensorflow2015} and trained on a GPU. Both polr and generalized additive proportional odds models are fitted in \proglang{R} using \cmd{tram::polr} \citep{pkg:tram} and \cmd{mgcv::gam} \citep{wood2017gam}, respectively. Further analysis and visualization is performed in \proglang{R}. For reproducibility, all code is made available on GitHub.\footnote{\url{https://www.github.com/LucasKookUZH/ontram-paper}} \subsection{Model Evaluation} \label{sec:eval} \emph{Evaluation metrics:} The main focus of {\sc ontram}s is to be able to interpret their individual components and the most flexible {\sc ontram} is equivalent to the MCC model. In turn, prediction performance of {\sc ontram}s can only ever be as good as in MCC. Therefore, we assess prediction performance mainly to illustrate trading off model flexibility against ease of interpretation. We evaluate the prediction performance of {\sc ontram}s and MCCs with proper scoring rules, namely the negative log-likelihood (NLL) and the ranked probability score (RPS). Roughly speaking, proper scoring rules encourage honest probabilistic predictions because they take their optimal value when the predicted conditional outcome distribution corresponds to the data generating distribution (for details see Appendix~\ref{app:scoring}). In Appendix~\ref{app:confmats} we compute additional evaluation metrics which are commonly used for ordinal classification models, \textit{i.e.}~ accuracy and QWK which is discussed in Appendix~\ref{app:qwk}. \paragraph{Estimation and interpretability} To evaluate whether {\sc ontram}s yield reliably interpretable effect estimates of shift components we make use of the simulated tabular predictors and compare the known true effects of the individual predictors to the estimates. For other predictors we discuss the plausibility of the estimated effects or, if applicable, compare them to results of other benchmark experiments. \section{Results} \label{sec:discussion} Results for the MCC models and {\sc ontram}s for the UTKFace and wine data are given in the following Sections~\ref{sec:resdrface} and \ref{sec:reswine}, respectively. \subsection{UTKFace} \label{sec:resdrface} We first evaluate {\sc ontram}s on the UTKFace data set, which contains images and tabular predictors that allow to illustrate the interpretation of the shift terms. As in other applications, age is discretized and treated as an ordinal outcome (see \textit{e.g.}~ \citep[]{liu2017ordinal}). We first train a SI-CS$_{\mathsf{B}}$-LS$_{\text{sex}}$ {\sc ontram} with transformation function $h(y_{k} \rvert \boldsymbol x} \def \mX {\boldsymbol X)=\vartheta_k - \eta(\mathsf{B}) - \beta_{\text{sex}}\cdot \mathds{1}(\text{sex}=\text{female})$ that includes the tabular predictor sex in addition to the images. We assume that the prediction of the age class depends on the appearance of a person and therefore on the image but not on a person's sex. On the other hand, a person's sex can often be deduced from an image, which renders the tabular feature and image data collinear and makes estimation and interpretability of the individual effects more difficult. However, collinear data is representative for most practical applications. We thus expect the estimated coefficient $\beta_{\text{sex}}$ to be small in comparison to the effect of the image $\eta(\mathsf{B})$, which we expect to be a better predictor of a person's age. \begin{figure}[!ht] \centering \includegraphics[width=0.55\textwidth]{figures/figure7_interpret-streep.pdf} \caption{ Predicted densities in a SI-CS$_{\mathsf{B}}$-LS$_{\text{sex}}$ {\sc ontram} once using the image of a 41 year-old and a 67 year-old Meryl Streep, while the gender is female in both cases. What sets {\sc ontram}s apart from other ordinal DL classifiers, is the directly interpretable effect of changing an image in terms of a log odds-ratio. Namely, the odds of belonging to a higher age change by a factor of $\exp(5)$ when changing image $\mathsf{B}$ to $\mathsf{B}'$, keeping sex constant. In turn, a change in the odds results in a change of the corresponding conditional outcome distribution, which puts higher probability mass on larger age groups when changing $\mathsf{B}$ to $\mathsf{B}'$. } \label{fig:streep} \end{figure} For evaluation, we use publicly available data of the actress Meryl Streep, i.e., female sex and two images showing her at the age of 41 ($\mathsf{B}$, age group $[31, 46)$) and 67 ($\mathsf{B}'$, age group $[61, 117)$) to depict the predicted PDF and estimated log odds-ratio in the SI-CS$_{\mathsf{B}}$-LS$_{\text{sex}}$ model (see Figure~\ref{fig:streep}). The model yields the image-effect estimates $\eta(\mathsf{B})=5.1$ and $\eta(\mathsf{B}')=10.1$, while the effect of sex stays constant ($\beta_{\text{sex}}=0.3$). As expected $\eta(\mathsf{B}')>\eta(\mathsf{B})$, indicating that $\mathsf{B}'$ is more likely to belong to a higher age group than $\mathsf{B}$. In particular, the difference between the two estimates yields a log odds-ratio $\eta(\mathsf{B}')-\eta(\mathsf{B}) = 5$, which is interpretable as an $\exp(5)$-fold increase in the odds of belonging to a higher age class compared to all classes below, when changing from $\mathsf{B}$ to $\mathsf{B}'$ and keeping sex constant. For a more systematic and empirical evaluation of the flexibility and interpretability of {\sc ontram}s, we fit seven models with the image data, the 10 simulated tabular predictors with known true effect sizes $\text{\boldmath$\beta$}$ and a combination of both (see Table~\ref{tab:models}). The models differ in their flexibility due to different transformation functions and the parametrization of the loss. In Appendix~\ref{app:resqwk}, we compare the MCC model and the CI$_{\boldsymbol x} \def \mX {\boldsymbol X}$ {\sc ontram} to another ordinal classification model trained with a loss based on Cohen's quadratic weighted kappa \citep[QWK,][]{de2018weighted}. We first consider the most flexible models, MCC and CI$_{\mathsf{B}}$, which are based on the UTKFace image data and only differ in the parametrization of the loss function (see eq.~\ref{eq:cce} for the MCC and eq.~\ref{ontram_nll} for the {\sc ontram} loss). As expected, the CI$_{\mathsf{B}}$ {\sc ontram} and MCC model achieve comparable prediction performances in terms of NLL and RPS (see Figure~\ref{fig:facesim}~A and B). After including the simulated tabular predictors, the performance in both models increases notably (see MCC-$\boldsymbol x} \def \mX {\boldsymbol X$ and CI$_{\mathsf{B}}$-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$ in Figure~\ref{fig:facesim}~A and B). In case of the MCC-$\boldsymbol x} \def \mX {\boldsymbol X$ model, the tabular predictors are attached to the feature vector resulting from the convolutional part of the CNN, which allows interactions between image and tabular predictors and therefore makes the model slightly more flexible than the CI$_{\mathsf{B}}$-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$. However, in contrast to the CI$_{\mathsf{B}}$-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$, the MCC-$\boldsymbol x} \def \mX {\boldsymbol X$ allows no interpretation of the effect of the tabular predictors on the outcome. Less flexible but more interpretable {\sc ontram}s are obtained by including the image data as complex shift rather than as complex intercept term (SI-CS$_{\mathsf{B}}$). Although the SI-CS$_{\mathsf{B}}$ model is less flexible than the CI$_{\mathsf{B}}$ model, prediction performance is comparable (see Figure~\ref{fig:facesim}~A and B). Again, adding the simulated tabular data as a linear shift term (SI-CS$_{\mathsf{B}}$-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$) results in improved prediction performance. Using a model with simulated tabular data only (SI-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$) yields a better performance than models that include image data only (see SI-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$ \emph{vs.} MCC, CI$_{\mathsf{B}}$, SI-CS$_{\mathsf{B}}$ in Figure~\ref{fig:facesim}~A and B). However, when comparing the models with image data and tabular predictors to the model with tabular predictors only, an increase in prediction performance is observed (see SI-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$ \emph{vs.} MCC-$\boldsymbol x} \def \mX {\boldsymbol X$, CI$_{\mathsf{B}}$-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$ and SI-CS$_{\mathsf{B}}$-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$). This indicates that the images contain additional information for age prediction. In practice, the {\sc ontram}s CI$_{\mathsf{B}}$-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$ and SI-CS$_{\mathsf{B}}$-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$ are most attractive because they provide interpretatable estimates for the effects of the tabular predictors with an acceptably low decrease in prediction performance. \begin{figure}[!ht] \centering \includegraphics[width=0.8\textwidth]{figures/figure8_merge-fig-metrics-estimates.pdf} \caption{ Test prediction performance for deep ensembles based on the UTKFace data. The figure summarizes the results for the models MCC, MCC-$\boldsymbol x} \def \mX {\boldsymbol X$, CI$_{\mathsf{B}}$, CI$_{\mathsf{B}}$-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$, SI-CS$_{\mathsf{B}}$, SI-CI$_{\mathsf{B}}$-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$, SI-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$ (x-axes) in terms of negative log-likelihood (A) and ranked probability score (B). Lower values in NLL and RPS indicate improved model performance. Baseline models are highlighted in red, {\sc ontram}s in blue. C: True versus estimated predictor effects. The figure summarizes the true versus estimated effects of the simulated tabular predictors of the UTKFace data set. The effect estimates result from the linear shift terms, LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$, in the models CI$_{\mathsf{B}}$-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$, SI-CS$_{\mathsf{B}}$-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$, SI-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$. In case of correct estimation, the parameters lie on the main diagonal. } \label{fig:facesim} \end{figure} To assess whether effect estimates for the tabular predictors are reliable in models with and without additional image data, we compare the true effects $\beta$ to the estimated effects $\hat{\beta}$ for the {\sc ontram}s with linear shift terms (CI$_{\mathsf{B}}$-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$, SI-CS$_{\mathsf{B}}$-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$, SI-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$). As summarized in Figure~\ref{fig:facesim}~C, all models recover the correct estimates. \subsection{Wine Quality} \label{sec:reswine} The experiments with the UTKFace data have shown that we get reliable and interpretable model components when including simulated, mutually independent tabular predictors besides image data. In the following, we summarize a couple of experiments with the smaller wine data set containing solely tabular predictors to demonstrate how we can estimate reliable linear and non-linear effect estimates for potentially dependent tabular predictors. In addition, we evaluate how the {\sc ontram} parametrization of the loss (see eq.~\ref{ontram_nll}) yields a gain in training speed and how this gain depends on the size of the training data. Note that all those models can simply be extended to additionally include image data, e.g. by attaching a complex shift term CS$_{\mathsf{B}}$. The wine dataset is a benchmark data set for a proportional odds model that allows to interpret the fitted effect estimates as log odds-ratios (see Section~\ref{sec:interpretation}). To illustrate the high flexibility of {\sc ontram}s and that we correctly estimate linear, non-simulated tabular predictors, we fit a proportional odds model with linear effects via a SI-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$ model and compare the model to the same model using the \proglang{R} function \cmd{tram::Polr}. As expected, Figure~\ref{fig:predwine} shows that both models yield the same prediction performance in terms of NLL (A) and RPS (B) and estimated predictor effects (C). \begin{figure}[!ht] \centering \includegraphics[width=0.8\textwidth]{figures/figure9_wine_complete.pdf} \caption{ Results of the wine quality data based on the test sets from the cross validation setting. Panels A and B summarize the prediction performance for the models MCC, CI$_{\boldsymbol x} \def \mX {\boldsymbol X}$, GAM, SI-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$ and polr (x-axes) based on the wine quality data set in terms of negative log likelihood (A) and ranked probability score (B). Lower values in NLL and RPS indicate improved model performance. Results of {\sc ontram}s are indicated as blue triangles, others as red dots. The black point gives the mean across the respective metric resulting from the single CV folds. C: Effect estimates with 2.5th and 97.5th percentile for polr and SI-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$ model over the 20 CV folds of the wine quality data set. } \label{fig:predwine} \end{figure} \begin{figure}[!ht] \centering \includegraphics[width=0.8\textwidth]{figures/figure10_ensemble_gam.pdf} \caption{ Estimated non-linear effects of 11 tabular predictors on the ordinal quality outcome in the wine data set as achieved by the {\sc ontram} GAM model. The estimates log odds-ratio functions of an ensemble of 20 runs with different initial weights are shown in blue. The solid black line depicts the estimated log odds-ratio functions estimated by the \texttt{mgcv::gam()} function in \proglang{R} together with a 95\% confidence interval (dashed black lines). Rugs on the bottom of each plot indicate the observed values for $X_k$, $k = 1, \dots, 11$, in the training data. } \label{fig:gampred} \end{figure} GAMs (see Table~\ref{tab:models}, SI-CS$_{\boldsymbol x} \def \mX {\boldsymbol X}^*$ with $h(y_k \rvert D)=\vartheta_k - \sum_{j=1}^p \beta_j(x_j)$) add another layer of complexity to the model by allowing non-linear effects for each predictor. Because the individual NNs estimating the additive components $\beta_j(x_J)$ do not interact explicitly the estimated log odds-ratio function retains the interpretability of a proportional odds model. Figure~\ref{fig:gampred} depicts the estimates of an ensemble of {\sc ontram} GAMs in comparison to a GAM from the \proglang{R}-package \pkg{mgcv}. Apart from the constraint-enforced smoothness in \pkg{mgcv}'s GAM, both models agree in magnitude and shape of the estimated predictor effects. For instance, predictor $X_{10}$ (sulphate content) has a strong positive influence on the rating when increased from 0 to 0.25 (on the transformed scale), in that the odds of the wine being rated higher increase by a factor of $7.4$, all other predictors held constant ($\exp(\hat\beta_{10}(0.25) - \hat\beta_{10}(0)) \approx \exp(2) \approx 7.4$). Afterwards the effect levels off and stays constant for the {\sc ontram} GAM, due to regularization and few wines with higher sulphate levels being present in the training data. The curve estimated by \pkg{mgcv} follows smoothness constraints and instead drops with a large confidence interval, also covering 0. GAMs are a special case of complex shift models, the latter of which allow for higher order interactions between the predictors. Conceptually, {\sc ontram}s enable to further trade off interpretability and flexibility by modelling some predictor effects linearly while including others in a complex shift or intercept term. If field knowledge suggests non-linearity of effects or interacting predictors, they can be included as a complex shift or, if the proportionality assumption is violated, in a complex intercept term. From Figure~\ref{fig:gampred} we can see that most of the coefficients could be safely modelled in a linear fashion, which is also evident from the minor loss in predictive power when comparing the GAM against the linear shift {\sc ontram} (see Figure~\ref{fig:predwine}~A, GAM \emph{vs.} SI-LS$_{\boldsymbol x} \def \mX {\boldsymbol X}$). \begin{figure}[!ht] \centering \includegraphics[width=0.8\textwidth]{figures/figure11_euml.pdf} \caption{ Epochs until minimum test loss for varying sizes of the training data using the wine quality data set. The data are split into $n/n_t$, $n_t\in\{50, 100, 200, 480\}$ folds each of which serves as training data for a multi-class classification and a complex intercept {\sc ontram}. The median test loss is computed for each scenario $n_t$ and each epoch. Afterwards, the number of epochs until minimum median test loss and the minimum median test loss are recorded. Here the epochs until minimum test loss (A) and the minimum test loss (B) are plotted against the 4 scenarios given by $n_t$. } \label{fig:eff} \end{figure} To assess the effect of respecting the order of the ordinal outcome, we evaluate the most flexible CI$_{\boldsymbol x} \def \mX {\boldsymbol X}$ {\sc ontram} and the MCC model, which solely differ in the parametrization of their loss. As in the UTKFace data, both models show the expected agreement in achieved prediction performance w.r.t. NLL and RPS (see Figure~\ref{fig:predwine}~A and B). However, the CI$_{\boldsymbol x} \def \mX {\boldsymbol X}$ model learns much faster in terms of number of epochs until the minimum test loss is achieved, compared to the MCC model. To further investigate this gain in learning speed, we split the wine quality data into $n/n_t$, $n_t\in\{50, 100, 200, 480\}$ folds of size $n_t$ and fit a MCC model and CI$_{\boldsymbol x} \def \mX {\boldsymbol X}$ {\sc ontram} to each fold. The median test loss is computed for each scenario of size $n_t$. The number of epochs needed to achieve minimal median test loss is summarized in Figure~\ref{fig:eff}~A. The training speed is consistently lower and therefore more efficient for the CI$_{\boldsymbol x} \def \mX {\boldsymbol X}$ {\sc ontram} than for the MCC model (Figure~\ref{fig:eff}~A). The CI$_{\boldsymbol x} \def \mX {\boldsymbol X}$ {\sc ontram} yields a slightly better prediction performance (median test NLL) for larger sample sizes. This can be explained by the fact that after 200 epochs the MCC model still has not reached the minimum test loss (Figure~\ref{fig:eff}~B). Note that the gain in training speed is only present if the outcome is truly ordered. In Appendix \ref{app:learnspeed}, we show that the effect vanishes when the ordering of the class labels is permuted. \section{Discussion and Outlook} \label{sec:conclusion} In this work we demonstrate how to unite the classical statistical approach to ordinal regression with DL models to achieve interpretability of selected model components. This allows us to estimate effects for the input data. In case of tabular predictors, we prove that the effects are correctly estimated, also in the presence of complex image data. Moreover, we show that the most flexible {\sc ontram} trained with the reparametrized NLL achieves on-par performance with a MCC DL model using the cross-entropy loss. This may first seem counter-intuitive because the cross-entropy loss ignores the outcome's order. However, the {\sc ontram} NLL is a reparametrization of the cross-entropy loss and can, therefore, at most achieve the same performance. The advantages of reparametrizing the NLL are (i) a natural scale for the additive and hence interpretable decomposition of tabular and image effects, (ii) a valid probability distribution for the ordinal outcome and (iii) an increase in training speed. In this context, interpretability is the main advantage over other state-of-the-art models because it is of crucial importance in sensitive applications as, for example, in medicine~\citep{rudin2018stop}. If the focus lies mainly on classification of an ordinal outcome and less on interpretability and probabilistic predictions, the data analyst may be interested in optimizing a classification metric such as Cohen's kappa. Indeed, Cohen's kappa directly considers the outcome's natural order and misclassifications further away from the observed class are penalized more strongly than misclassifications closer to the observed class. However, this approach results in predictions different from those of regression models such as the MCC and CI$_{\mathsf{B}}$, which is further highlighted in Appendix~\ref{app:resqwk}. In a regression model, on the other hand, the goal is rather to estimate a valid probability distribution which is achieved with proper loss functions such as the NLL. These fundamental differences between ordinal classification and regression make a fair comparison nearly impossible, as we highlight in Appendix~\ref{app:resqwk}. Further, we demonstrate how to select an {\sc ontram}, which possesses the appropriate amount of flexibility and interpretability for a given application. To achieve a higher degree of interpretability, flexibility has to be restricted, \textit{e.g.}~ by moving from a complex intercept to a simple intercept, complex shift model. However, we show that a restriction of flexibility can still yield adequate prediction performance which may even be similar to that of a more flexible model. Interpretability of different model components is further showcased for simple models including only tabular predictors and more complex models with tabular and image data. The modular nature of {\sc ontram}s makes them highly versatile and applicable to many other problems with ordinal outcome and complex input, such as text or speech data. Instead of using a CNN for image data, a recurrent neural network can be used to define a more flexible complex intercept or a simpler, but more interpretable complex shift term as in a SI-CS$_\mathsf{B}$ {\sc ontram}. Tabular predictors can then simply be added with linear shift or complex shift terms depending on the degree of interpretability the data analyst aims for. This work shows the potential of deep transformation models for ordinal outcomes. The predictive power of deep transformation models on regression problems with continuous outcomes has already been demonstrated \citep{sick2020deep}. However, the approach is easily extendable to the full range of existing interpretable regression models, including models for count and survival outcomes. The extension from ordinal data to count and survival data is hinted at by the parametrization of the {\sc ontram} NLL, which can be viewed as an interval-censored log-likelihood over the latent variable $Z$ for which the intervals are given by the conditional cut points $h(y_k \rvert D)$. For count data these cut points are given by consecutive integers, i.e., $(0,1]$, $(1,2]$, and so on. In survival data the interval is given by (commonly) right censored outcomes when a patient drops out of a study or experiences a competing event. In case of right-censoring the interval is given by $(t,+\infty)$ for a patient that drops out at time $t$. All benefits in terms of interpretability and modularity will carry over to the deep transformation version of other probabilistic regression models by working with an appropriate likelihood and parametrizing the transformation function via (deep) neural networks. \paragraph{Acknowledgements} We would like to thank Elvis Murina and Muriel Buri for insightful discussions and Malgorzata Roos for her feedback on the manuscript. We thank all anonymous reviewers for their comments and suggestions, which helped contextualize our proposed method among other state-of-the-art approaches. The research of LH, LK and BS was supported by Novartis Research Foundation (FreeNovation~2019). TH was supported by the Swiss National Science Foundation (SNF) under the project ``A Lego System for Transformation Inference'' (grant no. 200021\_184603). OD was supported by the Federal Ministry of Education and Research of Germany (BMBF) in the project ``DeepDoubt'' (grant no. 01IS19083A). \clearpage
{'timestamp': '2021-04-21T02:23:52', 'yymm': '2010', 'arxiv_id': '2010.08376', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08376'}
arxiv
\section{Introduction} Human health and behavioral research is primarily conducted in laboratories under conditions that poorly approximate real-world conditions. While this model has been successful, it may miss key aspects of human behaviors that are elicited only during more natural conditions or interactions. This concern has driven interest in developing and using remote sensing technologies to measure individuals completing their normal day-to-day activities in their natural environment. An explosion in modern technologies, many of which are in common usage, now provide the ability to monitor and understand health and human behavior in ways not previously possible. Smartphones, smart home devices, wearables, and online digital behaviors provide new ways to track sleep, emotions, spatial mobility, activity, environmental exposures, and social interactions to name just a few. These technological advances offer opportunities to unobtrusively collect real-time data on a wide range of social-behavioral and health variables with less participant burden and more ecological validity than ever before \cite{harari2016using} In the past decade we have seen growing effort worldwide in collecting real-time sensing and experience sampling data from human participants in natural, uncontrolled settings \cite{aharony2011social, wang2014studentlife, stopczynski2014measuring, kiukkonen2010towards, purta2016experiences, boukhechba2018demonicsalmon}. Smartphones are the staple of sensing hardware to measure different aspects of daily behavior \cite{harari2017smartphone}. Four main categories of behavioral patterns can be captured passively: (a) mobility trajectories, measured by GPS and further processed into location clusters that represent significant places visited \cite{canzian2015trajectories}; (b) physical activity, measured by accelerometer and further processed into activity status labels such as walking and staying still \cite{wannenburg2016physical}; (c) social context, reflected in different modes including phone calls, message exchange, and physical proximity detected by Bluetooth, which may be used to reconstruct social networks \cite{wu2018improving}, and; (d) interaction with the device, such as screen unlock status and app usage, which are logged by the smartphone itself \cite{do2011smartphone}. Additionally, ecological momentary assessment (EMA) surveys can be deployed to actively collect participant's self-reports of mood, behavior, and well-being in real time. While many aspects of behavior and health can be captured in smartphone sensing data including EMAs with satisfactory ecological validity, we realize that other key dimensions of well-being are better measured using complementary technologies. A person spends a significant proportion of their time at home but measurements of their home environment are not generally investigated in existing studies in parallel with other aspects of daily behavior. To this end, we developed a home environment sensing device, named \textit{BEVO Beacon}, that is capable of continuously collecting and uploading multiple measures of indoor air quality. This device can provide critical insights into a participant's living environment and evaluate its behavioral and health implications. Additionally, sleep is a critical health outcome and independent variable that is difficult to measure objectively using unobtrusive instruments. We argue it is especially beneficial to utilize the sleep measuring capability of wearable devices such as Fitbit to validate EMA answers. Furthermore, the vast majority of existing human sensing studies used less than a few hundred participants \cite{cornet2018systematic}. A larger sample is needed to obtain more reliable assessments of the correlations between key behavior and health measures, especially when a large number of variables is assessed. Reflecting these considerations, we conducted a multi-modal human sensing study named \textit{UT1000}, for which we recruited more than 1000 college students as participants over two deployments and distributed a variety of sensors and instruments including smartphone, Fitbit, BEVO Beacon, and EMA. The resulting data allow us to pursue research questions that previous data were unable to accommodate. With numerous types of technologies and methods potentially available to measure individual humans' health, behavior, and environment, we begin in Section \ref{sec:framework} by proposing a novel conceptual framework that organizes the various modalities of human-centric data based on their properties. Then, we present the study design and the types of data collected in our UT1000 Project in Section \ref{sec:ut1000}. We discuss the procedures and results of our extensive exploratory analyses and visualizations in Section \ref{sec:results}, covering data robustness and novel findings from four types of human-centric data, and caveats from data collection and analysis in Section \ref{sec:discussion}. Through this study we are able to gain comprehensive understandings of the lives of college students and learn valuable lessons about the design, deployment, and data analysis for large-scale human sensing studies. \section{Conceptual Framework}\label{sec:framework} \begin{figure} \centering \includegraphics[width = 0.8\columnwidth]{framework2.png} \caption{Human-centric Data Modality Framework} \label{fig:framework} \end{figure} Figure \ref{fig:framework} illustrates the conceptual framework we devised for organizing different technologies and methods for observing human outcomes based on properties of their data collection procedure and resulting data. A primary property of human-centric data is its \textit{temporal coverage}, represented by the bottom horizontal axis from low (left) to high (right). Temporal coverage is defined by the inherent suitability of a data modality to monitor extended proportions of time of an individual's daily life. Data modalities that can provide only single-time observations are on the low end of the temporal coverage dimension. Examples include (1) traditional survey inventories that are designed to provide a one-time diagnosis of a potential patient and (2) medical procedures that typically require in-person clinical visits such as electroencephalography (EEG), electrocardiography (EKG), and buccal swabs. Some data collection methods or technologies accommodate measurements taken at multiple points in time, thus are placed mid-range along the temporal coverage dimension. Examples include (1) self-reports in response to EMAs delivered via mobile devices and (2) record data such as transaction history which contains user information logged at different times of user engagement with a service or services. Highest temporal coverage is achieved by continuous tracking. Various sensors embedded in devices people carry where they go and install where they stay belong in this category, such as smartphones, wearable devices, and environmental sensors used as smart home technology. Wearable devices including smartphones tend to enjoy an even higher level of temporal coverage than environmental sensors. This is because wearable devices are able to accompany and monitor the user at all times as long as the user keeps the devices on their person and powered on, thus observing the user for longer periods of time compared to environmental sensors, which can only offer \textit{human-centric} sensing capability when the individual in question remains within their proximity (e.g., home environment sensors are only human-centric when the person is at home). A second property of human-centric data is its \textit{spatial freedom}, represented by the vertical axis ranging from fixed (bottom) to mobile (top). Spatial freedom is defined by the ability of a data modality to reflect an individual's health, behavior, and environment at a variety of locations. Data modalities with greater temporal coverage tend to permit a wider range of locations where an individual can be monitored, a.k.a. higher spatial freedom. For this reason the coordinate space presented in Figure \ref{fig:framework} is a triangle. A discrete-time measurement of low temporal coverage is typically taken at a specific location, only allowing minimal spatial freedom, thus occupying the left vertex of the triangle. However, spatial freedom may vary greatly among instruments that can track users continuously over time. For example, both a PM2.5 sensor installed at home and a smart wristband can be considered as having high temporal coverage; however, they correspond to fixed and mobile, respectively, on the spatial freedom dimension. The temporal coverage and spatial freedom of a data modality is often governed by the unobtrusiveness \cite{webb1966unobtrusive} of the technology or method producing it. Data modalities of higher temporal coverage and spatial freedom are usually produced by devices and procedures that are more user-friendly, more portable, and overall less burdensome for the user. Unobtrusive methods allow for more naturalistic and non-interfering ways to monitor a participant's daily life, thus producing measures of greater ecological validity. We identify a major correlation between ecological validity and temporal coverage/spatial freedom: measures of high ecological validity tend to enable observations over extended periods of time and with greater mobility. However, the relation between ecological validity and temporal coverage/spatial freedom is not a necessary one. In the classic example of Barker \& Wright's study of Raymond Birch \cite{barker1951one}, in which a research team followed a subject around for a whole day making observations every few minutes, temporal coverage and spatial freedom are both high however ecological validity is low, because the observation method was extremely intrusive. The example data modalities shown in Figure \ref{fig:framework} are based on how the generating methods are naturally and realistically carried out. For example, a buccal swab procedure takes a few minutes to complete but it requires a high level of participation and effort from the patient; therefore even though technically buccal swabs can be frequently administered, we still consider it to be a highly intrusive, one-time measurement. Many human-monitoring technologies, over their course of development, have seen themselves ascend on the temporal coverage scale and often on spatial freedom as well. For example, blood glucose testing used to require clinical visits, thus the burden was high; however, as the technology for on-body continuous glucose monitoring becomes perfected, blood glucose measurements can be obtained with unprecedentedly high unobtrusiveness, allowing its temporal coverage and spatial freedom to increase as well. A critical challenge in interdisciplinary research joining social sciences and engineering is the high-fidelity mapping between human-centric constructs and technology-advanced methods. Our framework provides an interface between the constructs and the methods based on their temporal and spatial characteristics and implications for ecological validity and unobtrusiveness. Thus it can help social scientists locate fitting methods to measure the constructs of interest. Furthermore, this framework can be used to guide data collection and hypothesis generation concerning interrelations of different aspects of human behavior. Researchers can delineate a subarea in the triangle to serve as the scope of their own data collection. Hypotheses or research questions can be straightforwardly formulated by linking two spots on the triangle and querying the relationship between the two corresponding data modalities. Moreover, the two-dimensional space describes one individual and can be conceptually stacked up to represent a group of individuals and their data and descriptors. Linkage between slices representing different individuals can inform the generation of research questions into the relations between individual outcomes and inter-personal interactions. \section{The UT1000 Project}\label{sec:ut1000} The UT1000 Project is a multi-modal data collection study conducted at the University of Texas at Austin to measure aspects of the health, behavior, and home environment of a large-scale participant cohort using a wide variety of technologies and methods, including traditional surveys, swabbing, EMAs, smartphone sensing, wearable trackers, and environmental sensors. We undertook two deployments, one in the Fall of 2018 the other in the Spring of 2019, totaling 1584 participants (62\% female) and lasting three weeks each. Participants for this study were recruited through an introductory psychology course. Enrolled students were instructed to sign up for the EMA and smartphone sensing components of the study as a class assignment that counted toward their final grade. Students who did not want to self-track using a smartphone were given the option to record their behaviors and moods by answering emailed EMA questions or keeping a daily diary. The other data modalities such as those from the wearable trackers and environmental sensors, on the other hand, were collected in return for experimental credits which the students used as partial fulfillment of the course requirements. The following subsections outline the different components of the UT1000 Project including the purpose, procedure, and types of data collected. Discussions of different study components are organized into three main categories based on the data modalities, namely \textit{single-time}, \textit{multiple-time}, and \textit{continuous} measures, following an order of temporal coverage from low to high consistent with the horizontal dimension of Figure \ref{fig:framework}. \subsection{Single-time measures} \subsubsection{Home Environment and Health (HEH) Survey}\label{subsubsec:heh} The Home Environment and Health (HEH) questionnaire consists of 63 questions asking students to report on home environment factors such as their current living situation including number of roommates, number and type of pets, and flooring type; their recent health and medical histories including colds, allergies, and flu shots received; and other behaviors such as hand washing frequency and use of electric scooters. A full list of the HEH questions are provided in Appendix A. The purpose of this survey was to obtain a better understanding of the participants' home environment and to clarify discrepancies found in the other data streams. The HEH questionnaire was a voluntary survey sent directly to participants via the email they provided to register for the study. Completing the HEH survey was a prerequisite for the subsequent home environment sensing component of the study discussed in Section \ref{subsubsec:beacon}. The survey was sent once during the first two weeks of the study period. Participants were asked to fill out the survey based on their situation when they received it rather than some time in the past or the future. A total of 56 participants completed the HEH questionnaire, with 46 in Fall 2018 and 10 in Spring 2019. \subsubsection{Student Environment and Buccal Swabbing}\label{subsubsec:swab} A subset of the study participants were provided with a dust sampling kit to collect dust samples from various surfaces in their home and classroom environment. The same participants that completed the HEH survey were given the kits ($N=56$). The kit consisted of six, individually-packaged Phosphate-Buffered Saline Tween-20 (PBST) wetted FLOQswabs\textsuperscript{\textregistered} (manufactured by COPAN\footnote{\url{https://www.copanusa.com/sample-collection-transport-processing/floqswabs/}}, Murrieta, CA) and six corresponding plastic, resealable test tubes that participants would place the swabs in after collecting samples. Participants were asked for identification in order to gather sampling materials from a refrigerator-equipped storefront created ad hoc in a convenient place at a central location of the university. Testing materials to be distributed to different participants were labeled with distinct barcodes so that we could easily trace the materials back to the participants and streamline the checkout process. Participants followed instructions to collect samples from the interior and exterior of their front door trim, cellphone screen, living room floor, HVAC filter or air diffuser if applicable, and a desktop where they normally sit when attending university classes. After sample collection, participants sealed swabs in the provided test tubes and placed them in their refrigerator until transportation to the university lab. When participants return the testing materials, material barcodes were scanned, the identity of the participant cross-referenced to the materials, and the temperature-sensitive samples were stored until transfer to a -4$^\circ$F freezer daily after storefront closure. They were asked to provide feedback on the challenges while performing home sampling and also whether they are willing to submit a buccal swab. If they consented, the research assistant in charge of operating the storefront would ask the participant to use a swab to collect a sample from the inside of their cheek. Samples were then stored in a small, resealable test tube and refrigerated before transfer to a -80$^\circ$F daily after storefront closure. The dust samples are useful to help understand more deeply about the participants' home environment beyond the HEH survey and what they might be exposed to on campus when attending classes. Examination of the dust samples can determine what types of microbial exposures commonly occur in students' indoor environments. Buccal swabs can be used for a variety of reasons, but were conducted as part of this study to understand how certain chemical markers like cytokine levels are related to mood and stress in participants. \subsection{Multiple-time measures} \subsubsection{Ecological Momentary Assessment}\label{subsubsec:ema} Ecological Momentary Assessments (EMAs) involve brief questions about a participant's behavior and feelings that are answered in real-time while the participant is in their natural environment. EMAs were administered using the Beiwe mobile application\footnote{\url{https://www.hsph.harvard.edu/onnela-lab/beiwe-research-platform/}} running on their smartphones at regularly scheduled times throughout each day. For both the Fall 2018 and the Spring 2019 cohorts, EMAs were drawn from four categories of questions: sleep questions, momentary context questions, momentary well-being questions, and an audio question. The full text of these questions are included in Appendix B. Briefly, the three sleep questions were designed to assess the duration and quality of sleep, momentary context questions were designed to determine what the participant was doing and who they were doing it with, and five well-being questions sampled participants' mood (sadness, loneliness, contentment, and stress) and energy level on a Likert scale. The audio question asked the participant to describe what they were doing and to include a brief segment of background noise. Both the Fall 2018 and Spring 2019 cohorts received EMAs at five different times during the day. At 9am each morning they received the three sleep questions, four momentary context questions that were framed to assess the 15 minutes prior to receiving the EMAs, and five mood questions that were framed to assess how they feel at the moment. At 12pm, 3pm, and 6pm participants received EMAs that were similar to those from the morning, except that the sleep questions were removed and the audio question was added. Each night at 9pm they received the four momentary context questions and five mood questions that were framed to assess participant behaviors and feelings across the entire day. \subsection{Continuous measures} \subsubsection{Smartphone} Passive monitoring data were collected using the Beiwe digital phenotyping platform, which is a freely available open-source system that includes mobile phone applications for Apple iOS and Google Android operating systems, and a backend server implemented in Python. The backend server was run using Amazon Web Services cloud based computing infrastructure. The backend includes a study administration web application for designing and conducting Beiwe studies and monitoring their progress, an API for sending study parameters to and receiving data from the mobile phone applications, a database for storing study state information, and an encrypted Amazon Simple Storage Service bucket for storing study data. The Beiwe developers maintain versions of the app in the Apple App store and Google Play store for easy deployment to study participants. The full set of passive monitoring parameters are listed in the Appendix C. Due to differences in operating system security settings and device capabilities, different data sources were collected on Android and iOS devices. Basic device and operating system information (make, model, version), accelerometer, GPS, and power state data were available and collected on both devices. iOS specific data sources include gyroscope, magnetometer, the proximity of the device to the user, and whether the phone is connected to the internet by WiFi or cellular. Android specific data sources include a list of WiFi routers and Bluetooth devices in the phone's proximity, the time, duration, and hashed phone numbers for incoming and outgoing calls, and time, message length, and hashed phone numbers of incoming and outgoing text messages. To maintain participant privacy, WiFi and Bluetooth identifiers, and phone numbers are encoded with a hashing function. The function is unique however, so calls to the same destination and proximity to the same WiFi access points can be tracked across time. The Beiwe mobile application was configured to store collected information locally and to upload it only when connected to the internet using WiFi. If an error was encountered during transmission, the app stores the data and retries transmission until receiving an indication that the data was successfully received by the backend. Each data source is stored in its own set of CSV files that are broken down and organized by timestamp. These files are encrypted on the phone before being transmitted over an SSL connection to the backend. When received, the data are unencrypted, processed to correct for errors, and update received data statistics, and then re-encrypted for storage. All encryption is performed using randomly generated participant specific encryption keys. As per the study design, participants were instructed to download and allow all permissions for the Beiwe platform. Each participant had a randomly generated identification tag that consisted of eight letters and numbers and were prompted to create their own password after entering a temporary password given to them by the study coordinator. Participants did not have direct access to their data and used the login credentials when completing the EMA surveys. \subsubsection{Wearable Activity Tracker} Participants' activity and sleep patterns were captured using the Fitbit Charge2\textsuperscript{TM} wearable activity trackers. The devices require participants to input their height, weight, gender, and age to accurately calculate the number of steps taken, calories burned, and the wearer's heart rate. In addition, participants can track different exercises by selecting them from the device's interface or through the paired smartphone application. Most Fitbit products, including those supplied to the study participants, are capable of passively monitoring the wearer's sleep as long as the device detects that the user has been asleep for a minimum number of hours. The wearer's sleep is subdivided into four categories based on movement and heart rate: awake, light, deep, and rapid-eye-movement (REM). Over the past few years, many studies have looked at the accuracy and utility of using Fitbit and other personal monitoring devices in sleep studies \cite{liang2018validity,de2018validation,baron2018feeling,liang2019accuracy}. Results from these studies show that these devices can be useful when determining total sleep time, awake time, and the amount of time spent in REM sleep. Similar to the swabs discussed in Section \ref{subsubsec:swab}, each Fitbit was numbered, barcoded, and provided to participants also at the storefront location if they consented to participate in the activity monitoring component of the study. In addition to receiving the device, each participant was required to register a Fitbit account and download the smartphone application if they did not already hold an account. Participants were asked to wear the activity monitors as much as possible, removing them only when bathing, participating in aquatic activities, or charging the device. Participants were instructed to wear the Fitbit monitor over a period of at least two weeks and were free to use the device outside of the study requirements. If broken or damaged, participants were given a new device to register and use for the remaining portion of the study. \subsubsection{Building Environment and Occupancy Beacon}\label{subsubsec:beacon} \begin{figure}[] \centering \includegraphics[width=0.5\columnwidth]{beacon.jpg} \caption{Building EnVironment and Occupancy (BEVO) Beacon} \label{fig:beacon_portrait} \end{figure} The Building EnVironment and Occupancy (BEVO) beacon is a low-cost sensor platform we developed in-house that is capable of measuring multiple indoor environmental quality (IEQ) variables in addition to detecting Bluetooth and WiFi signals. The BEVO Beacon consists of a Raspberry Pi (RPi) micro-computer connected to a variety of environmental sensors arranged into a 6"$\times$6"$\times$4" housing made of plywood and acrylic (see Figure \ref{fig:beacon_portrait}). The RPi can detect Bluetooth devices and WiFi access points in its proximity, which can help determine occupancy. The RPi is additionally capable of storing data captured by itself and the co-locating IEQ sensors on a local micro SD card, and then uploading the data to a cloud-based storage system hosted by the Texas Advanced Computing Center once connected to WiFi. Table \ref{tab:bevo_variables} outlines the environmental sensors used in BEVO Beacon and the variables they measure. The RPi is housed in a lower compartment, separated from the sensors and wired to a small fan to help with heat regulation. To avoid the possibility of re-sampling air trapped inside the device's housing, and further help with heat management, the environmental sensors are housed in a compartment above the RPi with their inlets/exhausts exposed to the ambient air. The BEVO Beacon requires a 5B micro-USB portal connection to power. \begin{table}[] \centering \begin{tabular}{p{0.23\linewidth}p{0.14\linewidth}p{0.12\linewidth}p{0.39\linewidth}} \toprule Variable & Unit & Sensor & Notes\\ \midrule Temperature (T) & $^{\circ}F$ & Adafruit SHT31-D & Occupant thermal comfort \\ \midrule Relative humidity (RH) & \% & Adafruit SHT31-D & Occupant thermal comfort \\ \midrule Particulate matter (PM) & $\mu g/m^3$ & Plantower PMS5003 & EPA-specified criteria air pollutant with respiratory health implications \\ \midrule Total volatile organic compounds (TVOCs) & $ppb$ (parts per billion) & Adafruit SGP30 & Compounds with a wide-range of health implications from respiratory issues to cancer\\ \bottomrule \end{tabular} \caption{IEQ variables measured by the environmental sensors housed in the BEVO Beacon} \label{tab:bevo_variables} \end{table} The commercially available sensors used on the BEVO Beacon afforded us two benefits. These sensors were low-cost ($<$US\$100), which allowed us to develop and deploy more devices than what is typically done when measuring indoor air quality. The second benefit is that these sensors serve as the base units in many other commercially available IEQ products. Using the base units rather than off-the-shelf devices ensures that there is no proprietary algorithm that alters the raw values measured by the sensors. However, reliability and accuracy are two main issues surrounding the use of low-cost sensors since they use less sophisticated electronics than high-grade reference monitors that can cost more than US\$10000. Our beacon development effort is a step toward integrating low-cost sensors to achieve high home-sensing performance. BEVO Beacons were each assigned a number and a barcode. Only the participants who completed the HEH survey (see Section \ref{subsubsec:heh}) were eligible to receive a BEVO Beacon. Participants who were eligible and consented to participation were instructed to stop by the storefront and check out the device. At check-out, the device was supplied to the participant along with a 5V micro-USB to wall outlet adapter. Participants were instructed to power the device using any open outlet in their home. In total, we distributed 15 BEVO Beacons: five in Fall 2018 and ten in Spring 2019. \section{Exploratory Results}\label{sec:results} \subsection{Data collected}\label{subsec:data_collected} \begin{figure}[] \centering \includegraphics[width=0.8\columnwidth]{example_participant.png} \caption{Data collected from the smartphone, Fitbit, and BEVO Beacon of an example participant during a given day (March 30th 2019). Plotted data modalities are: EMA (questions and answers shown against phone image background on top), GPS (clustered significant places and an example movement trajectory shown in maps on top and as vertical bands), accelerometry (black dots), screen activity (short grey bands), heart rate (BPM), calories spent in the past hour (Calories), steps taken in the past hour (StepTotal), home relative humidity (RH), home temperature in degrees Fahrenheit (TF), home particulate matter in $\mu g/m^3$ (PM), and home TVOC (TVOC).} \label{fig:example_pid} \end{figure} To showcase the diverse data streams collected from our participants, we plot in Figure \ref{fig:example_pid} data collected from a particular participant's smartphone, Fitbit, and BEVO Beacon on a given day (March 30th, 2019) as an example. The top third of Figure \ref{fig:example_pid} shows the data types collected by the Beiwe smartphone platform. We conducted temporal clustering \cite{kang2005extracting} with the raw GPS traces and processed them into periods of stay at significant places (represented by the colored vertical bands) and periods of movement between significant places (represented by the white spaces between the colored bands). We used Open Street Map API to query for the place type of the significant places found. We show the geographic location and venue type of the significant places, as well as the trajectory and time of the third transition period of the day (``Move${}_3$") in the two maps on top. In total on March 30th, 2019, the participant made 6 stays at 3 distinct places (residence hall, art museum, and entertainment venue) and made 5 trajectories of movement between them. The participant spent her entire night and most of the morning (midnight to around 11am) at the residence hall (red band/dot), which was her main residence. Notice that even though the trajectory of Move${}_3$ (top right map) passes through the residence hall but did not register another period of stay, suggesting that the participant merely swung by the residence hall without making a stop for an extended period of time. \begin{figure}[] \centering \includegraphics[width=\columnwidth]{ut3000_reliability.png} \caption{Completeness of four types of data collected from participants in the Fall and Spring deployments combined: (A) daily EMA (1482 participants); (B) Smartphone sensing, GPS data shown as example (1539 participants); (C) Fitbit (36 participants), and; (D) BEVO Beacon (9 participants).} \label{fig:data_reliability} \end{figure} During the three-week official study period, we were able to record some GPS and accelerometer data from approximately 950 participants each day. Within these days, data completeness for GPS and accelerometer followed a highly regular and well-synced daily cycle where the least percentage of participants submitted data in the early morning hours and the highest during the evening hours. Averaging the hourly completeness percentages gives us a daily average of around 65\% of the participants submitting data during any given hour. In addition to mobility information, smartphone acceleration magnitude is plotted as black dots and episodes of unlocked screen as short grey bands. We observe that periods of high acceleration magnitude correspond well with periods of movement between places. Screen activity, on the other hand, varies heavily depending on the place: for example, the screen stayed unlocked during the entire Stay${}_3$ at the entertainment venue, but locked during Stay${}_4$ at the art museum. Moreover, the participant responded to an EMA survey at 9am, providing a self-report of her sleep quality, hours of sleep, as well as the semantics of her location at the moment. The participant did not respond to any EMA questions scheduled at other times of the day. Her answer ``dorm; campus" to the location question matches with the significant place detected by GPS. The middle third of Figure \ref{fig:example_pid} shows three data streams recorded by Fitbit: heart rate (BPM), calories expense (Calories), and steps taken (StepTotal). The patterns of fluctuation of the three data streams are largely in sync with one another, with values significantly higher during the day than during the night. Three points of peak values in heart rate and calories (11am, 4pm, 9pm) visibly correspond to time intervals of high smartphone accelerometer readings, suggesting a positive correlation between smartphone accelerometry and physical activity status recorded by wearable devices. The bottom third of Figure \ref{fig:example_pid} shows four data streams recorded by BEVO Beacon, all of which are metrics of indoor air quality. Note that only when the participant is located at her home location (indicated by red band in this plot, specifically Stay${}_{1,2,5}$) is she exposed an environment described by these metrics; when she goes away, the metrics merely reflect her home environment status that does not affect her directly. We observe a sharp rise in humidity and PM concentration between 4-5am, which is potentially indicative of a change in the HVAC system. \subsection{Data completeness}\label{subsec:data_completeness} Completeness encompasses two metrics: first, the amount of time each participant stays in the study and continues to submit data, actively and passively; second, when the data type is continuous, the proportion of time during the entire period of participation that data are available. The first metric is important because it represents \textit{participant compliance} and a higher value in it (or, closer to the length of the intended study period) indicates more successful participation. The latter measure is also important in that it represents \textit{data continuity} and a higher value in it indicates fewer data-missing intervals during the total period of time a participant is submitting data. In Figure \ref{fig:data_reliability} we present the completeness of four major types of data we collected, namely EMA, smartphone, Fitbit, and BEVO Beacon. In Figure \ref{fig:data_reliability}-(A), we show the number of participants (height of bars) who submitted answers to daily EMAs for all different numbers of days (horizontal position of bars), as well as the percentage of participants (projection of red dots on vertical axis on right) who submitted answers to daily EMAs \textit{at least} a certain number of days (horizontal position of red dots). We observe that more than 60\% of participants submitted daily EMA answers for more than 14 days and more than 20\% more than 21 days. In Figure \ref{fig:data_reliability}-(B), we show the distribution of participants with respect to the total duration of time they were contributing smartphone GPS data (i.e., compliance, on the horizontal axis) and the proportion of that duration for which their data are available (i.e., continuity, on the vertical axis). We use the color of square cells to indicate the number of participants that fall in particular compliance-continuity boundaries: the brighter-colored vertical bar between 20-25 days correspond well with our planned study length which is three weeks. Shown by the blue horizontal lines, 283 participants (18.4\%) had smartphone GPS data available for more than 80\% of the hours they participated in study, 53.7\% of participants more than 60\%, and 84.7\% of participants more than 40\%. Figure \ref{fig:data_reliability}-(C) contains the same information as (B) but plotted for Fitbit data. As opposed to aggregating the number of participants like we did for (B), because of the lower number of participants who chose to wear a Fitbit (36), we simply represented each Fitbit participant as an opaque grey dot, forming a darker cluster when more participants fall in a close region of compliance-continuity value combination. Compared to smartphone data, Fitbit data enjoyed significantly higher continuity: out of the 36 participants, 30 submitted data for more than 80\% of their in-study time. This may suggest that Fitbit as a wearable device requires less human attention and interference, as opposed to smartphones which are constantly being handled and require more frequent charging, and thus are more prone to produce uninterrupted data streams. Out of the 15 BEVO Beacons we distributed, we found that only nine recorded and uploaded data reliably and they were all from the Spring 2019 deployment. Due to such a small number of participants who returned substantial environmental sensing data, in Figure \ref{fig:data_reliability}-(D) we simply plotted entire time series of data availability of each IEQ measure captured by BEVO Beacons (indicated by different colored dots, jittered) for each of the nine participants. Visibly, three of the nine BEVO Beacons submitted data perfectly whereas the remaining six primarily had trouble submitting PM data (red strip on the bottom). Upon inspection we found that communication errors between the sensors and the RPi accounted for a large amount of data loss. Fluctuations in power delivery between the RPi and the environmental sensors caused some environmental sensors to go offline for periods and resulted in data loss during the study. One highly notable difference is in the number of participants who signed up for smartphone sensing compared to wearable and home environment sensing ($>$1000 vs. $<$100). We believe that both hardware availability and the incentive structure contributed to this discrepancy. First, the smartphone component of the study required the participants' own primary phone, which was widely available; whereas the Fitbit and BEVO Beacon components required extra hardware we needed to purchase, build, and provide for the participants, thus limiting the number of participants we could enroll. Second, the incentive for students to complete smartphone sensing and EMAs was to receive credits on an assignment that counted toward their final grade (with the alternative to opt out of using smartphone and only logging manually instead), which proved to be an effective strategy to improve participant compliance \cite{harari2017evaluation}; whereas participation in the other parts of the study was rewarded by extra experimental credits, which may not have been nearly as attractive to the students. \subsection{EMA findings}\label{subsec:ema_findings} \begin{figure}[] \centering \includegraphics[width=\columnwidth]{ema_findings3.png} \caption{Self-reported momentary mood ratings from Ecological Momentary Assessments. The type of venue, type of companionship, and the Activity of Daily Living were self-reported together with the mood surveys. Each dot represents the average value of a participant under a corresponding category. The black vertical bars indicate the mean of the participant-wise (i.e., calculated within each participant) average scores and the surrounding grey bands indicate a bootstrapped 95\% confidence interval of the mean. In panels (B)(C)(D), categories are arranged from bottom up in a least-to-most-desirable order based on the corresponding mood outcome.} \label{fig:ema_findings} \end{figure} With our EMA data we explore how participants' self-reported momentary mood ratings vary under different temporal, spatial, social, and behavioral contexts. Each context is specified by a categorical variable with multiple levels. For temporal context, we focused on the day of week and thus have 7 levels. For spatial context, we organized the answers to the place type EMA question into 8 categories: \textit{campus/library}, \textit{home} (including dorm), \textit{work} (the site of a job), \textit{worship} (e.g., church), \textit{social} (Greek house, friends' house, or party place), \textit{cafe/food}, \textit{gym}, \textit{shopping} (store or mall). For social context, we organized the answers to the ``who are you with" EMA question into 8 categories: \textit{alone}, \textit{strangers}, \textit{classmates}, \textit{family}, \textit{co-workers}, \textit{roommates}, \textit{friends}, \textit{significant other}. For behavioral context, we organized the Activity of Daily Living question into 10 categories: \textit{class/meeting}, \textit{study/reading}, \textit{rest/do nothing}, \textit{transit}, \textit{work a job}, \textit{socialize} (including talk, text, and using social media), \textit{chore/errand}, \textit{eat/drink}, (watching) \textit{tv/movies}, and \textit{exercise}. For each of the four mood outcomes (sadness, stress, loneliness, contentment), the self-ratings were evaluated on a 0-3 ordinal scale, with 0-3 corresponding to a mood outcome being \textit{not at all}, \textit{a little bit}, \textit{quite a bit}, and \textit{very much} so respectively. We computed a participant-wise average for each participant when they are under each of the contextual categories listed above. We bootstrapped the mean of the participant-wise averages for each contextual category with 2000 with-replacement samples to determine a 95\% confidence interval. We show some of the results in Figure \ref{fig:ema_findings}. Figure \ref{fig:ema_findings}-(A) shows participants' stress level on different days of week. A participant tends to experience significantly lower stress on Fridays and Saturdays than the rest of the week while Monday to Wednesday are the most stressful days. Figure \ref{fig:ema_findings}-(B) shows participants' sadness level felt at different kinds of places. A participant tends to feel the least sad at a store or mall and saddest at home or on campus. Figure \ref{fig:ema_findings}-(C) shows participants' loneliness while accompanied by different types of individuals. A participant tends to feel the most lonely being alone and least lonely being with a significant other; and there appears to be a decrease in loneliness with the type of companionship becoming more intimate. Figure \ref{fig:ema_findings}-(D) shows participants' contentment experienced while engaging in different types of daily activities. School related activities such as attending classes and studying see the lowest contentment whereas exercise is associated with the highest contentment, with watching tv/movies and dining being not-surprising runner-ups. These results portray the general patterns of a college student's psychological experience in her daily life. \begin{figure}[] \centering \includegraphics[width=0.66\columnwidth]{all7_mgm.png} \caption{Interdependency between a participant's self-reported average daily mood ratings (sadness, stress, loneliness, contentment), energy level (energy), sleep quality (restful), and sleep duration (hrs.sleep). For each variable (node), a LASSO regression model is fitted with other variables as predictors and the regularization parameter $\lambda$ optimized by 10-fold cross validation. The completeness of the ring around each node indicates the proportion of its variance explained. The color and the weight of the edges are determined by the sign (green-positive; red-negative) and the value of the coefficients from the LASSO models fitted.} \label{fig:ema_interdependency} \end{figure} In addition to the effect of daily life context on mood outcomes, we further explore the interdependency between these outcomes together with other health outcomes reported by the participants, that is how these outcomes are robustly related with one another. We focus on 7 daily measures, namely sadness, stress, loneliness, contentment, energy level, restfulness of sleep, and hours of sleep. The values of these outcomes are obtained from the daily EMA questions: end-of-day self-assessment of mood and energy level experienced during the day, and beginning-of-day self-assessment of the quality and duration of the previous night's sleep. We start by taking the average of each participant's 7 daily measures (so that each data point represents a distinct participant and is independent) and then fit a LASSO regression model for each of the 7 measures using the other 6 measures as predictors, with the regularization parameter $\lambda$ optimized by 10-fold cross validation (so that unimportant and fortuitous correlations get reduced to zero). Through this operation (essentially a double round robin), the relation between each pair of outcomes receives a coefficient in two models. We take the average of the two coefficients and use that value as the dependency value between the corresponding pair of outcomes. Figure \ref{fig:ema_interdependency} shows these dependency values by the edges between nodes that represent the daily outcomes: the dependency values' sign corresponding to the color (green being positive) and magnitude proportional to the thickness. We also computed the percentage of variance in each outcome explained by the other outcomes via the fitted models and indicate as the completeness of the ring surrounding each node in Figure \ref{fig:ema_interdependency}. The most prominent dependency we observe is between sadness and loneliness, with sadness robustly correlated with only loneliness, stress, and contentment in the expected directions, but neither with energy level nor with sleep quality and duration. 70.4\% of variance over participants' average daily sadness levels can be explained by their other three mood outcomes and that is the highest percentage of all 7 outcomes investigated. We observe a strong correlation between perceived sleep quality (restful) and perceived sleep duration (hrs.sleep), but also a clear difference between how the two sleep metrics are correlated with other measures. Perceived sleep quality of the previous night is robustly correlated with the contentment and energy level of the current day whereas sleep duration does not display such effect. Of the four mood outcomes, contentment appears to the only one that has a strong correlation with both energy level and the sleep quality of the previous night. \subsection{Smartphone findings}\label{subsec:smartphone_findings} \begin{figure}[] \centering \includegraphics[width=\columnwidth]{beiwe_cov_lattice2.png} \caption{Scatter plot matrix of four mobile sensing phenotypes and two mood symptom metrics. Density plots of each variable are shown on the diagonal. Pairwise correlation values together with their significance level are shown in the cells above the diagonal (p-value: \textbf{***}$<0.001$; \textbf{**}$<0.01$; \textbf{*}$<0.05$*; \textbf{.}$<0.1$)} \label{fig:beiwe_findings} \end{figure} Smartphone sensing data has been extensively studied for its utility in diagnosing and predicting mental and physical health symptoms. Existing research has identified a number of digital phenotypes \cite{rohani2018correlations} extracted from GPS, accelerometer, phone usage, and phone call/SMS log data that are significantly correlated with aggravated mood. Most of these studies used smartphone data collected from less than 200 participants and we wonder whether some of the important correlations can be replicated in our data with $\sim$1500 participants. We focus on accelerometer, GPS, and screen usage since these three types of smartphone data are available for both iPhone and Android using participants, the latter constituting 1/8 of the entire cohort. We selected from our participants those who completed at least 7 days of daily sadness level self-reports and computed the average daily value of the following four features: \textit{acc.mag.rmssd}, \textit{loc.var.log}, \textit{ent.pls}, and \textit{unlocked.dur}. \textit{acc.mag.rmssd} refers to the root mean square of successive differences of acceleration magnitude (unit: gravity) and quantifies the suddenness of the smartphone's movement with a higher value indicating more transition between staying relatively still to moving intensely. \textit{loc.var.log}, log-transformed location variance, is computed by summing the variance in longitude and latitude values of a participant's GPS coordinates and then taking the natural logarithm. Participants who visit many different places that are far apart register a higher value in location variance. \textit{ent.pls} is defined by the normalized entropy of the amounts of time spent at difference places. To compute this feature, we first undertake a temporal clustering procedure mentioned in Section \ref{subsec:data_collected} to obtain a list of key places, then find the duration of time spent at each of the key places, and finally calculate the normalized entropy over these duration values. Lastly, \textit{unlocked.dur}, a.k.a. duration of screen unlocked, is simply the amount of time (minutes) a participant's smartphone screen stays unlocked. In addition to these 4 smartphone phenotypes, we computed \textit{mean.sadness} and \textit{sd.sadness}, the mean value and standard deviation of daily sadness scores representing the severity and the fluctuation intensity of sadness respectively, to serve as the health outcomes of interest. Figure \ref{fig:beiwe_findings} shows pairwise scatter plots and correlations among the four smartphone sensing features and two mood symptom metrics. \textit{mean.sadness} and \textit{sd.sadness} are highly correlated, suggesting that participants who reported greater sadness during the study period also reported greater variation of sadness levels. Apart from the correlation with each other, both \textit{mean.sadness} and \textit{sd.sadness} appear significantly and negatively correlated with \textit{acc.mag.rmssd}, indicating a positive connection between active motion and improved mood. However, they do not display a significant correlation with other sensing features, with the exception of \textit{loc.var.log} which shows a significant positive correlation with \textit{sd.sadness} but none with \textit{mean.sadness}. The three variables, \textit{acc.mag.rmssd}, \textit{unlocked.dur}, and \textit{ent.pls}, are all highly correlated with one another. This suggests that the participants whose smartphones have more highly fluctuating movement tend to divide their time more evenly at different places and spend more time with their smartphone unlocked. \textit{loc.var.log} is also significantly correlated with \textit{ent.pls} and \textit{unlocked.dur}, but not with \textit{acc.mag.rmssd}. This indicates that it is visiting and spending time at multiple places during a day, rather than merely covering more expansive geographic area which may not entail stopping, that is associated with active motion. \subsection{Fitbit findings}\label{subsec:fitbit_findings} A notable functionality of Fitbit is to infer and categorize the wearer's bedtime into sleep stages: awake, non-REM sleep (including ``light" and ``deep" sleep), and REM sleep. Researchers have sought to validate Fitbit's ability to accurately measure sleep stages by concurrently monitoring Fitbit wearers' sleep using polysomnographic devices and found satisfactory accuracy of differentiating asleep and awake as well as delineating REM stage sleep \cite{de2018validation,liang2018validity}. Many others used Fitbit sleep stage data to study the relations between sleep patterns and other health and performance outcomes such as asthma \cite{bian2017exploring}, cognitive ability \cite{tucker2006daytime}, and sleep disorders \cite{silva2008sleep}. However, less is known about how the amount of REM and non-REM sleep is associated with an individual's perceived sleep quality. To help answer this question, we correlate three Fitbit-measured nighttime sleep duration metrics (REM time, non-REM time, and total asleep time that is REM + non-REM) with participants' answer to a question about self-perceived quality of the previous night's sleep (``How restful was your last night's sleep?"). This question was part of the EMA survey sent to participants at 9am each day (see Section \ref{subsubsec:ema}). Cross-referencing our Fitbit and EMA data indicates that seven participants totaling 41 nights had both reliable bedtime Fitbit data and self-reported restfulness score the next morning available. These observations are retained for the correlation analysis. \begin{figure}[] \centering \includegraphics[width=0.9\columnwidth]{ut3000-fitbit-beiwe-REMandNREM-restful-LMEscatter-annotated.pdf} \caption{Relationship between participants' self-reported sleep restfulness in the morning and Fitbit-measured duration of REM, non-REM, and total sleep received the previous night. Each dot represents one night and is colored to indicate distinct participants. Colored-lines and black line represent individual and overall linear trends respectively.} \label{fig:fitbit-beiwe-sleep-restful} \end{figure} \begin{table}[] \centering \caption{Coefficients and significance (p-value) of the correlations between self-reported sleep quality (restfulness) and Fitbit-measured sleep metrics based on mixed-effect ordinal regression. } \begin{tabular}{@{ }lll@{ }} \toprule Fitbit-measured duration (hours) & coefficient ($\beta$) & p-value\\ \midrule REM & 1.312 & 0.04 \\ Non-REM & 1.136 & 0.003 \\ Asleep (REM + non-REM) & 0.535 & 0.012\\\bottomrule \end{tabular} \label{tab:fitbit_sleep_outcomes_ordinal} \end{table} For each participant-night, the duration of Fitbit-measured REM, non-REM, and total sleep time (in minutes) were paired with the perceived restfulness self-rating the next morning (on a 0-3 ordinal scale) and plotted in three scatter plots shown in Figure \ref{fig:fitbit-beiwe-sleep-restful}. The REM time plot and the total sleep time plot are arranged abreast one another because total sleep time is always greater than REM-time and the two measures occupy two disjoint spaces on the time axis. Each dot represents one night and is color-coded to represent distinct participants. Colored linear lines are fitted specific to each participant while the thick black line represents the linear trend over all observations. Visibly there is a strong positive correlation between all three Fitbit-measured sleep duration metrics and perceived restfulness, both individually and overall. Exceptions exist in REM time plot where we observe two participants who had a non-positive correlation between REM time and perceived restfulness. To be rigorous, we further conducted ordinal regression modeling and present our results in Table \ref{tab:fitbit_sleep_outcomes_ordinal}. Since the restfulness score is an ordinal variable and multiple observations belong to the same participants, we used mixed-effect ordered logit models to model perceived restfulness rating with each of the three Fitbit-measured sleep duration metrics, with the participant-wise random effect accounted for: $logit[P(restful \leqslant i)] = \alpha_{i} - (\beta \times FitbitSleepMetric + u + \epsilon), i \in \{0,1,2\}$. Likelihood ratio tests indicated that this is superior to a fixed effect model with the corresponding Fitbit metric being the only predictor. Based on results shown in Table \ref{tab:fitbit_sleep_outcomes_ordinal}, duration of non-REM sleep appears the most significantly correlated with self-reported restfulness. \begin{figure}[] \centering \includegraphics[width=\columnwidth]{ut3000-fitbit-outcomes-swarm.pdf} \caption{Differences in Fitbit-measured sleep metrics on days when participants rated aspects of their mood and energy as low ($\leqslant1$, no more than ``a little bit") or high ($\geqslant2$, at least ``quite a bit") and walked more or less than 10,000 steps. Colors in the swarm plots correspond to data from individual participants. P-values from a mixed effect models accounting for the individual random effect are included in addition to the direction of the correlation. Bold values indicate p-values less than 0.05.} \label{fig:fitbit_sleep_outcomes} \end{figure} Another group of studies have focused on the relationship between sleep quality and mental health, and found that negative mood such as anxiety, sadness, stress, and loneliness are all associated with poorer sleep quality \cite{thomsen2003rumination,akerstedt2006psychosocial,zawadzki2013rumination}. These studies typically (1) investigated between-subjects variances treating an individual participant as the unit of analysis and (2) used either questionnaires (e.g., Pittsburgh Sleep Quality Index) or in-lab sensors (e.g., polysomnography, actigraphy) to assess sleep quality. We, on the other hand, wanted to explore how an individual's mood, energy, and physical activity levels assessed on a \textit{daily} basis may influence her sleep quality on the immediately following night as measured by the more convenient and less intrusive Fitbit. Specifically, we calculated three sleep metrics based on Fitbit sleep stage data: (1) time asleep, which is the sum of both REM and non-REM time; (2) sleep efficiency, defined as the ratio of time asleep to time in bed, and (3) the REM-to-non-REM ratio. For daily mood and energy ratings, we used participants' end-of-each-day EMA self-reports of contentment, sadness, loneliness, stress, and energy levels, evaluated on a 0-3 ordinal scale (with the exception of energy level which was evaluated on a 0-4 ordinal scale); for each of the mood and energy questions, we labeled a day as ``low" if the participant's self-rating was below or equal to 1 (i.e., no more than ``a little bit") and ``high" if greater than or equal to 2 (i.e., at least ``quite a bit"). For physical activity level, we used the daily step count also captured by Fitbit, and labeled a day as ``low" if the participant registered less than or equal to 10000 steps and ``high" otherwise, which is consistent with a guideline widely used in health research \cite{wattanapisit2017evidence}. We then compared each of the three nightly Fitbit sleep metrics with each of the binary mood, energy, and activity levels of the day preceding sleep. Requirements for data availability for Fitbit sleep stage data, daily EMA data, and Fitbit step count data narrowed our sample size down to 41 observations (days) from 7 participants for the sleep-EMA pairing and 252 observations from 34 participants for the sleep-steps pairing. The distributions of the three Fitbit sleep metrics given high or low mood, energy, and step counts are shown in Figure \ref{fig:fitbit_sleep_outcomes}. Mood/energy and sleep metric relationships are shown as swarm plots with data points colored by participant. Step count and how it relates to sleep metrics are shown in the final column of Figure \ref{fig:fitbit_sleep_outcomes} as a pair plot. In addition to plotting, we built mixed effect models of each sleep metric using each of the mood, energy, and step count binary levels with the individual participant's random effect accounted for and show the sign and p-value of the coefficient in each corresponding cell in Figure \ref{fig:fitbit_sleep_outcomes}. Class imbalance between high and low sadness and loneliness is visibly severe (panels B, C, H, I, N, O), undermining the reliability of the corresponding results, therefore we limit our interpretation to the remaining four explanatory variables (contentment, stress, energy, and step count). Contentment and stress share a similar pattern in terms of correlation with the Fitbit sleep metrics: they are both significantly correlated with time asleep (panels A and D, albeit in opposite directions) but not with sleep efficiency or REM-to-non-REM ratio (panels G, M, J, P). A day reported by a participant as higher in contentment and lower in stress tends to end with significantly greater amount of time asleep at night, which is consistent with existing research on negative mood and sleep duration \cite{kim2007effect,vandekerckhove2011role,zhai2015sleep}. The only variable that has a significant correlation with both sleep efficiency and REM-to-non-REM is energy level during the day (panels K and Q). Days on which participants reported feeling more energetic tend to have worse sleep efficiency (e.g., longer time tossing and turning before falling asleep) but a higher REM-to-non-REM ratio. The final column of plots show that on days when participants took more than 10000 steps, their sleep time was shorter and had a lower REM-to-non-REM ratio, which seems to contradict the finding in most studies that increased exercise is correlated with improvements in sleep duration and quality \cite{dolezal2017interrelationship,kelley2017exercise}. This result suggests that steps taken on a day may not be an effective indicator of the amount of physical exercise, at least among college students. \subsection{Home environment findings}\label{subsec:bevo_findings} We begin by plotting data from two example participants' BEVO Beacons (IDs \textit{vvlm8iyi}, \textit{19k2rlua} in Figure \ref{fig:data_reliability}) in Figure \ref{fig:beacon_iaq_heatmap} to show the hourly variation of indoor air quality throughout the study period. We chose these participants because their devices collected the most complete sets of environmental data and their responses on the Home Environment and Health survey revealed no major differences in their living situations: each participant had one roommate, did not smoke, did not have any carpeting, did not own pets, and did not regularly change their AC air filter. Figure \ref{fig:beacon_iaq_heatmap} shows the variation of PM2.5 and TVOC concentrations over different days and different hours of the day for the three participants. The colors in Figure \ref{fig:beacon_iaq_heatmap} correspond to air quality index (AQI) values for PM2.5 \cite{mintz2009technical} and approximated AQI values for TVOC. For PM2.5, AQI is a scale from 0 to 500 that indicates the severity of pollutant concentration. An AQI of 100 is consistent with recommendations from the US Environmental Protection Agency's (EPA) National Ambient Air Quality Standards (NAAQS) therefore values for AQI below 100 are generally considered healthy while values above can be a concern depending on the concentration and duration of the exposure. \begin{figure}[] \centering \includegraphics[width=\columnwidth]{ut2000-beacon-iaq-heatmap-b1and2.png} \caption{Hourly and daily variations of PM2.5 and TVOC concentration from three BEVO Beacons throughout the data collection period. The color of a cell indicates the environmental hazard associated with a certain level of PM2.5 and TVOC.} \label{fig:beacon_iaq_heatmap} \end{figure} All three participants experienced consistently high concentration of PM2.5 on days such as the fifth and tenth days of the study compared to other days. The participant in column (A) saw decreases in PM2.5 concentration every day starting after 12:00 with the exception of days 5 and 7. One plausible explanation is that the participant's AC turns on at this time and remains operating during the hottest part of the day. Weather data indicate that temperatures on day 5 were lower, on average, than most other days during the study period which could have made running the AC unnecessary. Between days 10 and 18, this participant's BEVO Beacon captures 1-3 hour events where concentrations were uncharacteristically high. These typically occur in the early-to-late morning which may indicate the participant was cooking breakfast and the effects of these events lingered for a few hours after. There are no noticeable trends for the participant in column (B), however their PM2.5 concentrations decrease starting at 12:00 on day 15 and remain suppressed for the remainder of the study. One shared pattern between PM2.5 and TVOC measurements is an initial period of low value readings. Lower PM2.5 concentrations were grouped toward the beginning of the study period and not measured again for the remainder of the study. TVOC concentrations are also similarly low during the first few days of the study. This pattern could be explained by either or both of the following. First, sensors may have required significant time to warm-up; for example, metal oxide sensors used to measure TVOCs, like the SGP30 sensor on the BEVO Beacon, typically have a burn-in time meaning that when the sensors are initially powered on, measurements are uncharacteristically low. Second, sensors may have experienced a certain degree of \textit{drift} or \textit{fouling} that artificially increased the measured concentration during later portions of the study: sensor drift refers to the gradual increase or decrease in measured values over a long period of time due to degradation of electrical and mechanical components, while fouling occurs when sensors are exposed to dramatically high concentrations or in operation for long periods of time which allows dust and other materials to build up around the sensors inlet. The TVOC plots in columns (B) suggest that the sensor might have become over-saturated because the concentrations get progressively higher throughout the study period. These concentrations, like PM2.5 of (B), are also dramatically higher than the values measured for the participant in column (A) who experienced worse concentrations during the middle of the study period and a decrease during the final few days. \begin{figure}[] \includegraphics[width=\columnwidth]{ut2000-heh-beacon-vape-pmtvoc-kdediff.png} \caption{Comparison of distributions of PM2.5 and TVOC measurements in homes between participants who do not vape and those who do (one participant, indicated by red curve).} \label{fig:iaq_vape_trends} \end{figure} Figure \ref{fig:iaq_vape_trends} shows the distinctive distribution densities of PM2.5 and TVOC concentration values in the living environment of the vaping participant compared to the concentrations measured in nine other non-vaping participants, suggesting that our BEVO Beacon can potentially be used to detect living habits and inform behavioral health interventions. Recent studies have indeed measured increased concentrations of PM2.5 and TVOCs in rooms after vaping \cite{eaton2018cigarette,chen2018assessment}. Only one participant out of the ten who received a BEVO Beacon during the Spring 2019 deployment also reported that they vaped. This vaping participant had an elevated density of PM2.5 concentrations around 75 $\mu$g/m$^3$ but did not record values as high as other participants. Compared to other participants, the vaper also recorded higher TVOC concentration on average and especially an increased proportion of TVOC concentration between 300-500 ppb. Our results, while limited to one individual, are consistent with previous study findings that vaping increases the amount of PM and TVOCs in one's indoor environment. \section{Discussion}\label{sec:discussion} We have focused on four types of human-centric data and their inter-connections in our analysis, namely EMA self-reports, smartphone sensing, wearable sensing (Fitbit), and home environment sensing (BEVO Beacon). The four data modalities serve as an illustrative subset of the space outlined by our conceptual framework (Figure \ref{fig:framework}) and are not meant to be exhaustive. For example, we collected single-time, highly participatory measures such as buccal swabs but chose not to include them in our data experiments due to the limited available sample size. Future work could very well place heavier emphasis on obtaining these data types that are usually more logistically challenging to collect and explore how key well-being outcomes revealed in those data types can be inferred by more passive data streams. Another type of data that we did not collect in the UT1000 Project is individual social media data including both the content created and the interaction patterns, which have been utilized to predict personal mental health outcomes in past studies \cite{mendu2019socialtext}. In our conceptual framework of human-centric data modality, social media data would fit in the medium range on both the temporal coverage and the spatial freedom axes, similar to the position of EMAs. A recurring theme in the data analysis using multi-modal human-centric data, as we encountered throughout Section \ref{sec:results}, is multiple measurements from the same participant. Typically, when researchers collect sensing or survey data from participants, multiple data points for each data type are collected from each participant, resulting in a situation where one has $N$ observations from $M$ participants and $N > M$. This is not a trivial issue because observations that belong to one participant tend to be more correlated with each other than with those from other participants, which makes the direct application of regression models onto the entirety of the $N$ observations statistically unsound \cite{bolger2013intensive}. We identify the following strategies for dealing with this technical challenge. First, if the inter-individual variation in a particular variable is of interest and the number of participants $M$ with data available is satisfactorily high, one appropriate approach is to aggregate the variable by the individual, such that each individual is mapped to only one value (e.g., mean value) of that variable. This is the approach we adopted for the analysis in Section \ref{subsec:ema_findings}. Interpretations made from models created on such aggregated data would be regarding the cross-participant patterns rather than within-participant ones. Second, if one has limited amount of data available that does not justify aggregation, an appropriate solution is to use mixed effect models to account for individual differences between participants. We used a mixed effect ordinal regression models in Section \ref{subsec:fitbit_findings}. An individual random effect could be added to both the intercept or a variable coefficient of a (generalized) linear model and the eventual selection will need to depend on model selection metrics or tests such as AIC, BIC, or a likelihood ratio test to determine whether the added effect (thus increasing variance explained) is worth the increased model complexity. In our experiments discussed in Section \ref{subsec:fitbit_findings}, specifically those presented in Table \ref{tab:fitbit_sleep_outcomes_ordinal} and Figure \ref{fig:fitbit_sleep_outcomes}, we found that adding only an individual random effect to the intercept is sufficient and the most appropriate. Most of the analysis done in this paper (Section \ref{sec:results}) falls in the category of \textit{correlation analysis}, where one builds statistical models to fit to all data to learn the correlations between variables, and evaluate the models using some goodness-of-fit metric (e.g., adjusted R squared, significance). Another type of tasks researchers often conduct with multi-modal human-centric data is \textit{predictive modeling}, for which the multiple measurement issue may have different and nuanced implications. In a predictive modeling task, one builds (trains) a model to fit to a subset of all data and seeks to evaluate (test) the predictive power of the model using the remaining subset with a prediction performance metric (e.g., area under ROC curve). When the multiple measurement issue is present (i.e., $N > M$), the train-test partition needs to be carefully executed based on the nature of the predictive task at hand. If the predictive modeling task focuses on detecting (especially previously unknown) individuals that belong in a certain class (e.g., clinical diagnosis), it is advisable to assign observations from different participants into the training and test set because having the same participant's (thus correlated) observations in both sets data will inflate predictive performance. However, if the predictive task aims to monitor a participant's status and raise warnings when undesirable changes are detected, then the correlation between observations from the same participant becomes a valuable source of information to capitalize on: by training models using past observations from a participant, future observations of the same individual, being correlated with her previous ones, become easier for the models to classify. This is why personalized models typically perform better than generic models for personal monitoring tasks \cite{constantinides2018personalized}. To achieve decent performance for a personal monitoring task, an initial period of model training tuning is usually necessary (as opposed to a ``cold start"); sometimes, the optimal strategy for improved prediction performance may be a hybrid model using both other participants' data and the same participant's previous data. \section{Conclusion} We conducted the UT1000 Project, a multi-modal data collection study using a variety of technologies and methods to monitor and understand aspects of the health, behavior, and living environments (See Figure \ref{fig:example_pid}) of a college student cohort of more than 1500 participants for 3 weeks. Some participants voluntarily monitored themselves for several more weeks after the official 3-week study period ended. The project is highly novel due to not only the large scale of participation but also the emphasis on incorporating the monitoring of personal living environment with health and behavior sensing to achieve a multi-faceted dashboard of human-centric information. With many types and sources of data at hand, we proposed a conceptual framework systematically organizing human-centric data modalities and their corresponding technologies and methods with respect to their temporal coverage and spatial freedom, which is further helpful for guiding data collection and research question formulation. Temporal coverage and spatial freedom overlap with ecological validity and are constrained by the unobtrusiveness of the method. Hurdles to unobtrusiveness include the size, weight, and power need of a device, requirement for human attention and maintenance, and many potential others. A general direction of evolution for human-centric design and technology is to become more portable, convenient, and user-friendly thus affording higher and higher unobtrusiveness and ecological validity for its capacity of understanding and assisting humans, until it is truly ``woven into the fabric of everyday life" \cite{weiser1999computer}. We were able to collect from a large participant cohort satisfactorily complete multi-modal data in terms of both data continuity and participant compliance (see Figure \ref{fig:data_reliability} and discussions in Section \ref{subsec:data_completeness}). Our findings with EMA data point to differential emotional experience associated with the places in which one spends time and the people with whom one spends time. Certain aspects of emotions are more interlinked than others; for example, a person's sadness is especially connected with feelings of loneliness but less so with contentment and stress. Our smartphone data confirms the benefit of a broadly construed ``activeness" in life, whereby individuals that move more and spend time at more different places generally enjoy a more healthy mind. Fitbit findings support the utility of Fitbit's sleep measuring capability and reveal several significant correlations between Fitbit sleep metrics and self-reported sleep restfulness and mood outcomes. Lastly, the environmental sensors in our BEVO Beacons are capable of detecting abnormalities in an individual's indoor living environment, some of which are useful for detecting daily activities and lifestyle choices. Several limitations exist in our study, which we would like to address in future work. First, we would like to monitor participants for a longer period of time than three weeks so that we are be able to observe more reliable patterns of behavioral variation and build more accurate personalized predictive models. Second, there is a sharp imbalance between the availability of smartphone and EMA data and the availability of Fitbit and BEVO Beacon data due to our incentive structure and hardware availability. As a result, analyses involving Fitbit and BEVO Beacon data encountered the problem of small sample size and our results are of a preliminary and exploratory nature rather than final verdicts. We are preparing for a third deployment of the UT1000 Project that directly addresses these limitations by recruiting (potentially fewer) participants who will commit to longer study periods as well as increasing the number of Fitbits and BEVO Beacons distributed. We anticipate the collection, integration, and mining of diverse modalities of human-centric data from different technologies and methods and of various degrees of temporal coverage and spatial freedom to be key to the development of a new generation of digital solutions for personal well-being enhancement. \section*{Funding} This work was supported by Whole Communities—Whole Health, a research grand challenge at the University of Texas at Austin, and National Science Foundation Award SES-1758835. \bibliographystyle{plain}
{'timestamp': '2020-10-19T02:19:56', 'yymm': '2010', 'arxiv_id': '2010.08457', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08457'}
arxiv
\section{Introduction} \label{sec:introduction} Device fingerprinting is a process of identifying a device or device type based on its unique intrinsic or behavioural properties~\cite{xu2015device, gu2018fingerprinting-hindawi, hamad2019iot}. Device fingerprinting is very popular in internet-connected general purpose computing devices to track user behaviour and application usage. Some of the interesting applications include browser fingerprinting for web analytics, user tracking, fraud detection and accountability~\cite{Laperdrix2020, Hupperich2015, Crabtree2018} and have gained a significant interests from cyber-security community. While it is clear that device fingerprinting can bring a lot of benefits -- especially for providing automated and customisable user experience -- there are also concerns that it can pose security and privacy risks \cite{manginointernet, ren2019information}. On the other hand, it has been suggested that device fingerprinting can also be used to help improve the security of smart home automation \cite{jose2016improving}. There are three main properties that need to be satisfied in order to achieve effective fingerprinting of devices \cite{xu2015device}: \begin{itemize} \item \textit{unique identity property}: the device fingerprint has to be unique for the device; \item \textit{integrity property}: the fingerprints must be impossible -- or at least, difficult -- to forge; \item \textit{reproducibility property}: the features used in the fingerprinting process must be stable, especially in the presence of environment changes and mobility. \end{itemize} The increased prevalence of Internet of Things (IoT) devices makes the task of fingerprinting devices more challenging. To start with, there is a great variety of IoT devices available on the market, and there are many different ways for them to operate. These pose a challenge in creating a generic mechanism that can perform accurate fingerprinting of all IoT devices. Furthermore, there are some fundamental differences between IoT devices and general computers (for which, more mature fingerprinting mechanisms have been developed). For example, IoT devices do not have many standard browser-based applications, which means many standard fingerprinting mechanisms will not work for IoT devices. Moreover, many IoT devices do not have a standard Graphical User Interface~(GUI) and they might even work autonomously in pervasive environments without user's direct control. Due to resource constraints and insecure designs, IoT devices are prone to be involved in cyber-attacks, ranging from being the target \cite{skowron2020traffic, Hariri2019} to being exploited to create a botnet to mount a massive Distributed Denial of Service attack \cite{Antonakakis2017, mirai}. Therefore, it is necessary and desirable to be able to automatically detect whether certain IoT devices might be vulnerable or could be exploited in cyber-attacks. The automatic device identification is one of the core requirements for building a secure IoT ecosystem, including cyber-attack and anomaly detection systems and automatic management and control. Various device fingerprinting mechanisms have been proposed in the last few years. However, not all of these mechanisms are suitable for the IoT domain. Many IoT device fingerprinting mechanisms are only suitable for specific use cases or tailored to certain requirements, making it challenging to choose a correct fingerprinting mechanism that will be appropriate for a new use case, for example. This shortcoming is the motivation behind our paper. In this paper, we explore and collate existing IoT fingerprinting mechanisms -- especially those that leverage Machine Learning (ML) techniques -- and present a holistic view and terminologies used in the fingerprinting context, which can be used for further research and development. \vspace{0.2cm} \noindent {\bf{Contributions.}} The key contributions of our paper are: \begin{itemize} \item The compilation of a key set of fingerprinting terminologies. \item The identification of important features to be included for achieving effective and accurate fingerprinting of IoT devices. \item The construction of \textbf{\textit{IDWork\xspace}}: a systematic framework for categorising IoT device fingerprinting mechanisms, which can be used for comparing and selecting suitable fingerprinting mechanism(s) for an IoT application. \end{itemize} The rest of the paper is organised as follows. Section~\ref{sec:background} provides some background and related work, while Section~\ref{sec:methods} outlines the methodology we followed in our research. Section \ref{sec:fingerprinting} represents the core of our work, giving an overview of the \textbf{\textit{IDWork\xspace}} framework, along with the key terminologies and our results. Finally, Section~\ref{sec:conclusion} concludes our paper and provides some ideas for future work. \section{Related Work} \label{sec:background} Several papers have discussed various fingerprinting mechanisms, although they are not necessarily dedicated to IoT devices~\cite{xu2015device, Franklin2006, Wang2018}. Cunche et al. \cite{cunche2014linking} looked into device fingerprinting based on monitoring wireless probes that a device may make, based on the preferred network (access points) stored on that device. The main concern of the paper was privacy infringement, for example by exploiting information contained in the fingerprint to infer social links between device owners. Spooren et al. \cite{spooren2015mobile} provides a critical assessment of device fingerprinting for risk-based authentication. In particular, they pointed out that device fingerprinting carries a lot of similarity among mobile devices, making this approach less reliable for risk assessment and step-up authentication. Ferrag et al. \cite{ferrag2019authentication} looked at human physiological and behavioural features in their investigation into factors that might hinder biometrics models’ development and deployment on a large scale for authenticating IoT devices. They classified related survey papers based on deployment scope, focus biometric area, threat models, countermeasures, as well as the ML algorithms and Data Mining methods used by existing authentication and authorisation schemes for IoT devices. The paper also listed a set of biofeatures that can be used for biometric authentication of IoT devices, including gaze gestures, electrocardiogram, keystroke dynamics, fingerprint, ear shape and hand geometry \cite{ferrag2019authentication}. They focus only on biofeatures, so other traits (such as network characteristics and device information) are not considered. Skowron et al. \cite{skowron2020traffic} study the information leakage exposed by traffic fingerprinting attacks. They use features of statistical network flows and ML. Hence, this approach is effective even when the IoT traffic is encrypted. This approach relies on decision trees (CART classifier) and heuristically creates random forests out of 100 trees. The proposed approach aims at both device identification as well as the detection of anomalous user activities. The latter is based on features such as packet size, packet inter-arrival time, and transmission rate. Hamad et al. \cite{hamad2019iot} perform IoT device identification using traffic characteristics (network flows), based on real-time devices connected to an IP network. A passive behavioural fingerprinting approach is used, while device classification is based on features extracted from both packet header and payload. These include IP address, packet size, and other traffic related features. The authors investigated different supervised learning classifiers such as ABOOST, LDA, KNN, Decision Tree, Naive Bayesian, and SVM Random Forest (RF), with RF showing the best performance. \section{Methods} \label{sec:methods} Between March and June 2020, we carried out a systematic review of relevant papers that have been published on various venues, including USENIX, ACM, IEEE, Nature, ScienceDirect, MDPI, Springer, Elsevier, and Hindawi. We also utilised Google Scholar for comparison and for augmenting our search. The following keywords were used to gather the initial set of papers: ``IoT'', ``fingerprinting'', ``device identification'', ``device authentication'', ``device authorisation'', ``traffic filtering'', ``anomaly detection''. We then divided up these papers among ourselves in order to analyse them and to extract key features of each paper. In order to be able to compare these papers fairly and consistently, we constructed a framework we call {\bf {\em {IDWork\xspace}}}, as outlined in Section \ref{sec:framework}. At various stages, we also performed synchronisation checks among ourselves to make sure the process is robust and consistent. Further papers were added to the list between July and September 2020, mostly as a result of following up cited papers by those in the initial main list. The same analysis and extraction process using {\bf {\em {IDWork\xspace}}} were applied to these additional papers to ensure consistency. Our process came up with a final list of 31 articles from the 142 papers that we analysed carefully. The papers in our final list are shown in Table \ref{tab:classification}, which is constructed by populating a table as a result of applying our {\bf {\em {IDWork\xspace}}} framework. \section{Overview of IDWork\xspace}\label{sec:fingerprinting} \begin{figure} \includegraphics[width=\columnwidth]{images/iot.pdf} \caption{Edge/IoT device network end-to-end components} \label{fig:iot_block} \end{figure} For building {\bf {\em {IDWork\xspace}}}, we systematically reviewed the literature and recent state-of-the-art work to understand different terminologies used in IoT fingerprinting mechanisms. We simplified the presentation of IoT end-to-end ecosystem, as shown in Figure~\ref{fig:iot_block}. The Edge/IoT device -- showing the TCP/IP networking stack -- is partitioned horizontally. The upper partition represents \textit{software feature extraction}, which is composed of application, networking and Medium Access (MAC) layers. The lower partition represents \textit{hardware feature extraction} comprising of two sub-layers - the first layer (upper) represents the features extracted from the Physical Network Layer along with the firmware and hardware (Networking Interface responsible for Link/Physical layer communication) layers and the second layer (lower) represents the hardware features which explicitly use the hardware device. Similarly, same layer partition is performed at Network Gateway and Cloud Node. \subsection{Fingerprinting terminology}\label{sec:term} In this section, we explain the key terminology that is important to grasp, before we define the \textbf{\textit{IDWork\xspace}} framework.\\\\ \textbf{Passive vs Active Fingerprinting}: In passive fingerprinting, we collect information produced by a device and create an identification pattern by only observing the data coming from the device, i.e., no interaction with the device is carried out. In active fingerprinting, we instigate the target device to produce useful information, e.g. by making the device emit particular signals (at the physical-layer), or by producing packets which require a specific response from the device (at the network-layer). Thus, the difference between the two methods is that the former uses a sniffer to capture and analyse traffic, but it does not send traffic to the target~\cite{yang2019towards}, while the latter sends queries to the target and analyses the response.\\\\ \textbf{Static Feature vs Dynamic Feature Fingerprinting}: A static feature fingerprinting includes only features that do not usually change over the time (e.g. MAC address), while dynamic feature fingerprinting uses dynamic features that can change over time such as inter-arrival time associated with data flow. \\\\ \textbf{Adaptive vs Fixed Fingerprinting Algorithms}: An ``adaptive'' fingerprinting approach uses an algorithm that changes in response to certain conditions observed during the fingerprinting process. On the other hand, when the fingerprinting process always uses the same (deterministic) algorithm with pre-determined and constant parameters for all cases observed, we can consider that as ``fixed''.\\\\ \textbf{Hardware Feature vs Software Feature Fingerprinting}: The former approach uses features that are extracted using special Physical Unclonable Function (PUF) circuits to capture hardware-intrinsic properties. The latter approach uses behavioural software properties, which could be found in the network traffic generated by the IoT device.\\\\ \textbf{Rule-based vs ML-based Fingerprinting}: In rule-based approaches, the fingerprinting criteria are mathematically-formalised in the form of {\em {if-then-else}} rules. Such rules are often defined by thresholds and used to create fingerprints by capturing the correlation between the features/parameters. In ML-based fingerprinting, an ML model is created using the input features/parameters, and trained on the data to learn possible data correlations for generalisation.\\\\ \textbf{Device vs Network vs Cloud Level}: Fingerprinting approaches can act on different levels. Usually in the case of device-level fingerprinting, the approach generates a device signature which relies on its hardware characteristics, e.g. Radio Signal or clock skew. When the approach analyses network traffic -- i.e. there is an additional entity within the network that monitor the traffic to produce device pattern -- we refer to it as network-level fingerprinting. It is even possible that fingerprinting procedures are applied externally to a network so that they can be executed on multiple networks. We refer to this case as cloud-level figerprinting.\\\\ \textbf{White-box vs Black-box Fingerprinting}: White-box fingerprinting is possible when we can directly access a device's firmware source code and then build a dynamic model of that device~\cite{Li2018}. Black-box fingerprinting exploits the interaction between different layers (e.g. application layer and transport layer) to build devices' fingerprints.\\\\ \textbf{Unique Device Identification vs Type Identification vs Class Identification}: Fingerprinting approaches can have different outputs depending on the designer's goal. In particular they can produce: a unique device identifier, device model or device class (devices with similar properties). \\\\ \textbf{Supervised vs Unsupervised ML-based Fingerprinting}: Supervised learning involves labeled data, which means that a prior knowledge about the classification of the learning data is provided. Conversely, unsupervised learning involves unlabeled data, so the ML goal is to infer a suitable classification of the data involved as well as classifying the data.\\\\ \textbf{Radio vs MAC vs Network vs Application Layer}: Radio fingerprinting exploits the unique characteristics in the radio signal emitted by a device. MAC fingerprinting exploits the characteristics of the data frames produced by a device (e.g. probe request in Wi-Fi). In network fingerprinting, the network packet parameters are used to build an identification pattern. Application fingerprinting approaches typically gather information to find out the device's services and operating system. \\\\ \textbf{Open-world vs Close-world Evaluation}: Open-world refers to any approach that is able to identify IoT devices within a larger set of devices not only restricted to IoT devices. Closed-world is when identification is evaluated on data that is restricted to only IoT devices. \\\\ \textbf{Network Packet vs Flow-based Features}: A fingerprinting approach that relies on network traffic can use packet-based or flow-based features, or both. Packet-based features use the content of individual packet payloads and headers, whereas flow-based features are based on temporal features of multiple packets coming from the same device, e.g. packet flow direction, inter-arrival time and inter-packet length~\cite{Moustafa2015}.\\\\ \textbf{Network Packet Header vs Deep Packet Based Features}: When fingerprinting involves packet payload we refer to it as using deep-packet features. Otherwise, when only packet header parameters are used to build an identification pattern, we refer to it as using packet header features.\\\\ \textbf{Encrypted vs Unencrypted Network Traffic}: Some fingerprinting approaches do not need access to the packet payload, i.e. they can work on both encrypted and unencrypted packets. Conversely, others are designed to work on encrypted and unencrypted packet payloads, such as the algorithm proposed by Robyns et al.~\cite{robyns2017noncooperative} which exploits per-bit entropy analysis (MAC address randomization). Furthermore, some approaches are able to extract the features required only if the payload is not encrypted. \\\\ \textbf{Real Devices vs Simulated}: Fingerprinting approaches based on deep-learning algorithms require a large amount of data to properly identify devices. Moreover, budget constraints do not allow for a large number of devices to produce an exhaustive dataset for evaluation purposes. Thus, tools to simulate IoT devices are used (e.g. Node-RED \cite{koroniotis2019towards}). In this case, traffic flows and most of the important features of typical categories of IoT devices -- such as fridges or washing machines -- can be simulated and used to build datasets. On the other hand, if real devices are used, the results will be more representative of real-world scenarios, but the budgetary requirements are higher as well.\\\\ \textbf{Testbed vs Real World Evaluation}: Fingerprinting approaches are developed either on testbeds or in real-world environments. The latter approaches provide additional resilience and deployment credibility for the fingerprinting algorithm. \input{mtable} \subsection{IDWork\xspace Framework}\label{sec:framework} The construction of {\bf {\em {IDWork\xspace}}} started with an understanding of the basic fingerprinting creation and verification workflow, as shown in Figure~\ref{fig:iot_fingerprint}. The fingerprinting process consists of three steps: (1) Fingerprint template creation and storage, (2) Live fingerprint creation, and (3) Fingerprint verification. We analysed different considerations under each step. The task of initial template creation is a one-time process. The live fingerprint creation process may or may not follow the same approach or steps; however, the general approach follows these two sub-steps every time: feature extraction from the raw input features, and fingerprint generation. \begin{figure}[ht] \includegraphics[width=1\columnwidth]{images/fingerprint_stages.pdf} \caption{IoT device fingerprinting workflow.} \label{fig:iot_fingerprint} \end{figure} In the fingerprint template creation, the final step involving template storage and access mechanism is essential. In our work, we have considered different options under each sub-step (as shown in Figure~\ref{fig:iot_fingerprint}), that differentiates one fingerprinting mechanism from another. Some of these options are either implementation-related or real-time deployment-related and they need to be considered, analysed and accessed before deciding an appropriate fingerprinting process suitable for an IoT application. Some of the important options we explored are: \begin{itemize} \item [--] Does fingerprint feature extraction, or creation mechanism need device access to gather fingerprinting raw input? \item [--] Does fingerprint feature extraction, or creation mechanism need invasive mechanisms? \item [--] Does fingerprint feature extraction, or creation mechanism need additional hardware? \item [--] What is the fingerprint feature extraction and creation, or what is the storage location in the IoT end-to-end system, for example, on the device, at a network gateway or on a cloud server? \item [--] What are the security, integrity, anti-tempering considerations when storing and accessing the pre-created fingerprints? \item [--] What is the computational complexity of individual steps? \end{itemize} After careful consideration, we picked seven labels categorised under three broad steps: \textit{fingerprinting methods}, \textit{fingerprinting input features} and \textit{fingerprinting output}. We studied two categorisations under \textit{fingerprinting methods}, namely Passive (P)/Active (A) fingerprinting and Static (S)/Dynamic (D) fingerprinting. Under \textit{fingerprinting input features}, we considered categorisation using TCP/IP networking stack label and we used three choices: MAC/Network/Application Layers under this label. We further analysed these layers with two sub-labels with these choices: Packet/Dataframe/Flow and Header/Payload. We also explored the mechanisms which use these sub-labels for fingerprint creation, and we categorise them as Rule-based or ML-based. We classify \textit{fingerprint output} into three categories: Class, Type and Unique. As a summary, in this work we present seven important features (as shown in Table~\ref{tab:classification}), which broadly allow for a systematic and consistent way for classifying IoT fingerprinting mechanisms into logical categories. In total, there are potentially 432 exhaustive combinations, but certain combinations are more prevalent than others. We perceive these popular categories as the more promising approaches that one should take in their effort to achieve a meaningful fingerprinting exercise of IoT devices. \footnotetext[1]{They use an ML algorithm only for evaluation purposes} \footnotetext[2]{Their mechanism can also identify unique device events} \footnotetext[3]{A Physical Unclonable Function (PUF) is being used rather than any network traffic based approaches} \footnotetext[4]{They also use Flow in the shape of inter-arrival time} \section{Conclusion} \label{sec:conclusion} IoT fingerprinting has become an important research area, due to the increased prevalence of IoT devices. Fingerprinting mechanisms serve as a key component in a network administrator's effort to identify and categorise IoT devices, in order to be able to observe and manage IoT devices in their network properly, especially in relation to pinpointing potential causes of security problems. There are many existing IoT fingerprinting mechanisms available, but it is not easy to choose a suitable mechanism for one's network, because there is currently no consistent framework for analysing these mechanisms. This is a gap that our paper aims to address. Firstly, we compiled a list of key terminologies that are essential in understanding and analysing IoT fingerprinting mechanisms. From there, we carefully constructed a framework called \textbf{\textit{IDWork\xspace}}, which provides a frame of reference for a fair and consistent comparison of these mechanisms. And finally, we demonstrated the usefulness of our framework by populating a table with some example mechanisms. We mainly focused on the mechanisms that use Machine Learning techniques. However, there are several mechanisms employing Rule-based techniques that are worth mentioning. There are several key insights that came up from our research. We found that the majority of existing IoT fingerprinting mechanisms use a passive fingerprinting approach. This means a less intrusive approach is generally favoured. Furthermore, a dynamic approach -- or a combination of both static and dynamic approaches -- is very popular, quite possibly due to the need to fulfill a liveness property to minimise the risk of stale data or replay attacks. On the other hand, the least common mechanism seems to be based on a combination of active and static approach. This could be because such a combination might be more prone to a spoofing attack. While we endeavoured to be as thorough and exhaustive as we can in our research, we are aware that there are some limitations in our work. For example, there are seven categories that we mainly consider in our framework, as presented in Table \ref{tab:classification}. However, it is possible that there are other categories that need to be considered in more detail. Furthermore, our current classification is mostly based on the software-related features of the IoT fingerprinting mechanisms. It would be more complete if hardware-related features -- in particular, leveraging the Physical Unclonable Function (PUF) features -- are also considered. An interesting direction for future work is to look at the distribution and impact of IoT fingerprinting mechanisms and see if any significant patterns emerge in terms of mechanisms that are more popular or more effective, and how such patterns change over time. Further work will also need to be carried out to validate our framework. This could be done by utilising publicly available datasets (provided by some IoT fingerprinting mechanisms) in an experiment to classify real-world IoT devices in a live setting. This will allow for the accuracy of existing mechanisms to be calculated, enabling a fairer comparison of these mechanisms to be performed. Achieving this will enable system administrators to justify their choices with regard to which IoT fingerprinting mechanism(s) they would like to employ in their network. \section*{Acknowledgement} Yadav and Feraudo are supported in part by "Data Negotiability in Multi-Mode Communication Networks" sub-awarded project funded by EPSRC grant EP/R045178/1. \section{List of Abbreviations} \begin{tabular}{ll} \textbf{ML} & Machine Learning \\ \textbf{FPR} & False Positive Rate \\ \textbf{TPR} & True Positive Rate \\ \textbf{SVM} & Support Vector Machine\\ \textbf{k-NN} & k Nearest Neighbour \\ \end{tabular} \section*{Appendix} \bibliographystyle{ACM-Reference-Format} \balance
{'timestamp': '2020-10-20T02:40:10', 'yymm': '2010', 'arxiv_id': '2010.08466', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08466'}
arxiv
\section{Modelling the evolution of genomes in populations} When modelling the evolution of large genomic sequences at the population level, in particular for sexually reproducing species, a key biological mechanism to account for is meiotic recombination, which shuffles genetic material at each generation. We first introduce the concept of the ancestral recombination graph, needed to represent the complete genealogy of a sample undergoing recombination. We then review the statistical approaches used to fit models accounting for recombination to population genomics data. \subsection{The ancestral recombination graph} The evolution of the set of sequences carried by all individuals forming a population, generation after generation, can be modelled by a stochastic process, where each individual leaves a variable number of descendants in the next generation. As a result, at any position of the sequence, the \emph{genealogy}\index{genealogy} of a sample of $n$ individuals can be described by a tree (Figure~\ref{JD-fig1}A) \cite{JD-Kingman1982}. The tips of the tree represent the sampled individuals and the inner nodes their common ancestors. In the case of sexually reproducing organisms, which will be the focus of this chapter, the genealogy is not identical for every position in the sequence. During \emph{sexual reproduction}\index{sexual reproduction}, two individuals contribute part of their sequence to their descendant(s) in the next generation. The mechanism of \emph{recombination}\index{recombination} is responsible for randomly sampling the new sequence from the two parental ones (Figure \ref{JD-fig1}B). How often and where the recombination points occur will be discussed in Section~\ref{JD-section-het}. The consequences of the recombination process can be stated as: (1) the genealogy of the sequence on the left of a recombination breakpoint potentially differs from the genealogy of the sequence on the right, (2) the genealogy at two positions in the sequence are more likely to differ as the distance between the two points is large, and (3) the genealogy of the complete sequence can no longer be described by a single tree, but by a collection of such trees and associated breakpoints. This tree and breakpoints collection can be represented as a single graph, called the \emph{ancestral recombination graph (ARG)}\index{ancestral!recombination graph} (Figure \ref{JD-fig1}C) \cite{JD-Griffiths1996}. The complexity of the ARG grows with the number of individuals (which dictates the size of the underlying trees) and the number of recombination events (which determines how many trees are needed to represent the history of the full sequences). The ARG represents the complete history of the sampled individuals, where the trees at each position (referred to as the ``marginal genealogies'')are embedded \cite{JD-McVean2005}. It describes the history of each segment of the sampled sequences, tracing back their ancestors in potentially distinct individuals. Such segments, which have left descendants in the sample, are termed \emph{ancestral}. Contained in the ARG is also the history of some \emph{non-ancestral segments}, which did not leave a descendant in the sample, but were once part of a sequence that contained both ancestral and non-ancestral segments (Figure \ref{JD-fig1}D). The characteristics of the ARG are determined by the demography of the population (the history of population size changes), the recombination landscape (where do the recombination events occur), but also the selective forces acting on the sequence, as natural selection influences the distribution of the number of descendants for each individual, based on the nature of the sequences themselves. While the ARG contains the signature of the biological processes that shaped the genome sequences, it is unfortunately not directly accessible. In order to access the embedded information, it is necessary to model the evolution of sequences in populations. \begin{figure}[p] \begin{center} \includegraphics[width=0.9\textwidth]{Figure1} \end{center} \caption{\label{JD-fig1} Genealogies and recombination: relationships between individuals and along sequences. A) example genealogy of a sample of five individuals at a given position in the sequences, under a Kingman coalescent. Tip nodes represent the samples (1-5) and inner nodes their common ancestors (6-9). B) illustration of the recombination tree resulting from a process without coalescence (large number approximation): two chromosomes (solid black and dotted grey) are paired during sexual reproduction and exchange segments at a breakpoint $x_1$. At the next generation, the descendant sequence recombines with another sequence (solid grey) at another breakpoint $x_2$, etc. The sequence of any sampled individual is therefore a mosaic of segments with distinct ancestors separated by a series of breakpoints ($x_1$, $x_2$, $x_3$). C) a simple ancestral recombination graph (ARG) representing the genealogy of a sample of size three with one recombination event. The ARG is a combination of a coalescence tree (as in A) and a recombination tree (as in B). For ease of interpretation, two mutation events, $\bullet a$ and $\bullet b$ have been added. The relative coordinate of the recombination event is also indicated: $x = 0.4$, assuming a total sequence length of 1. D) partial graph showing the different classes of recombination events. Ancestral segments are depicted as filled rectangles, while non-ancestral segments are shown as simple lines (subfigure created after Figure 1 in \cite{JD-Marjoram2006}). } \end{figure} \subsection{The coalescent with recombination as a chronological process} When modelling evolution, the most intuitive approach is to consider the process chronologically, that is, to model the state of the system generation after generation. One of the most simple models, the so-called \emph{Wright--Fisher process}, \index{Wright--Fisher!process}\index{process!Wright--Fisher} considers that the gametes forming one generation are a random sample of the gametes produced at the previous generation, that is, reproduction is a purely random process where each individual has the same a priori chance to contribute to the next generation. In addition, the population has a finite, constant size. A similar model, termed the \emph{Moran process}\index{Moran!process}, considers a slightly different set-up with overlapping generations \cite{JD-Moran1958}. The Wright--Fisher and Moran processes can both accommodate recombination, modelled by randomly choosing a breakpoint along the genome and exchanging the parental genetic segments (see the contribution of Baake and Baake~\cite{JD-EBMB20} in this volume). In such processes, the fate of a genetic variant is purely stochastic and governed only by the population size. When conditioning on a sample of the result of the evolutionary process, a backwards-in-time modelling is used. Each sequence in the sample represents a lineage, and the aim of the model is to determine which lineages find a common ancestor in the past and when. Every time two lineages \emph{coalesce} into a common ancestor, the number of lineages to model is reduced by one, until the last common ancestor of the sample is reached. This process of lineages merging backwards in time is termed the \emph{coalescent}\index{coalescent} \cite{JD-Kingman1982}. The probability that two lineages merge at a given generation back in time depends on the population size. When the population size is constant in time, the number of generations until coalescence follows a geometric distribution with parameter $\frac{1}{2\cdot N_e}$, where $N_e$ is the \emph{effective population size}.\index{effective!population size} Assuming a large $N_e$, this discrete-time coalescent is well approximated by a continuous-time coalescent, where the divergence time between two sequences follows an exponential distribution with average $2\cdot N_e$ generations. For convenience, time is, therefore, measured in ``coalescence'' units equal to $2\cdot N_e$, so that the mean divergence time between two sequences in a sample is equal to 1. In the \emph{coalescent with recombination}\index{coalescent!with recombination} process, recombination events are modelled in addition to coalescence events \cite{JD-Hudson1983}. Backwards-in-time, a lineage undergoing a recombination event splits in two, the left and right sequences having distinct ancestors. Since the rates of coalescence and recombination events, at any time point, depend only on the current lineages, the process is Markovian in time \cite{JD-Simonsen1997}. This property enabled the development of simulation procedures and inference methods, allowing the estimation of various parameters by integrating over the unknown genealogy of a sample (e.g. \cite{JD-Adams2004, JD-Drummond2005}). Such methods, however, do not scale well with the length of the modelled sequences, as the number of events in the underlying ARG grows with the sequence length \cite{JD-Ethier1990}, preventing efficient integration even with Markov chains Monte-Carlo \cite{JD-Stumpf2003}. These methods are, therefore, restricted to small samples with relatively few loci. \subsection{The coalescent with recombination as a sequential process} Following the initial work by Simonsen and Churchill \cite{JD-Simonsen1997}, Wiuf and Hein extended the two-loci model of coalescence with recombination to multiple loci \cite{JD-Wiuf1999}. The resulting process models the ARG sequentially along the genome rather than chronologically. The resulting \emph{sequential coalescent with recombination}\index{sequential!coalescent with recombination} aims at modelling the genealogy of the sample at position $i$ given the genealogies at previous positions. In fact, genealogies at two distinct positions in the sequence are not independent: they are identical if no recombination event occurred between the two positions since the last common ancestor of the sample and can only differ if at least one recombination event occurred. Despite this intuitive correlation structure, the coalescent with recombination is not Markovian along the sequence. Computing the probability distribution of the marginal genealogy at a given position proved to be quite challenging because of long-range dependencies, the genealogy at position $i$ depending not only on the genealogy at position $i-1$, but on the genealogy at all positions $1$ to $i-1$. With the goal to simplify the likelihood calculation under the coalescent with recombination, McVean and Cardin proposed an approximation where certain types of coalescence events are ignored \cite{JD-McVean2005}. An intuitive description of the simplified process was provided by Marjoram and Wall \cite{JD-Marjoram2006}, who recognised five types of recombination events on the ARG, based on the type of segments in the parental sequences on both sides of the recombination event (Figure~\ref{JD-fig1}D): type 1 events occur in ancestral segments (events at $x_3$ and $x_4$ in Figure \ref{JD-fig1}D) while types 2-5 occur in non-ancestral segments. Type 2 events occur in so-called \emph{trapped genetic material}\index{trapped genetic material} \cite{JD-Rasmussen2014}, that is, non-ancestral segments flanked on both sides by ancestral segments (event at $x_1$ in Figure~\ref{JD-fig1}D). Events of types 3, 4, and 5 occur in non-ancestral segments only flanked by non-ancestral segments on one or both sides (e.g. event at $x_2$ in Figure~\ref{JD-fig1}D). Such events (3, 4 and 5) do not affect the sample generated by the corresponding ARG, and therefore do not impact the likelihood of the sample given the ARG. They can therefore be ignored without introducing any additional hypotheses, see \cite{JD-Wiuf1999} (types 4 and 5) and \cite{JD-Hudson2002} (types 3, 4 and 5). The process of McVean and Cardin, which was further improved by Marjoram and Wall \cite{JD-Marjoram2006} and Hobolth and Jensen \cite{JD-Hobolth2014} also ignores type 2 recombination events, that is, recombination events occurring in trapped genetic material \cite{JD-Rasmussen2014}. Doing so implies ignoring potential long-range dependencies between loci, and the distribution of samples generated by this approximated process is, therefore, different from that of the standard coalescent with recombination. The approximated process, however, has the additional property that the distribution of genealogies at position $i$ is only dependent on the genealogy at position $i-1$, and is, therefore, Markovian along the sequence. Such a process is referred to as the \emph{sequentially Markov coalescent (SMC)}\index{sequential!Markov coalescent} \cite{JD-McVean2005, JD-Marjoram2006}. Importantly, the SMC process generates samples with patterns of genetic diversity that are very similar to the ones generated by the full coalescent process \cite{JD-McVean2005}. The SMC, in particular, can be seen as a first-order Markov approximation of the true coalescent with recombination process \cite{JD-Wilton2015}, and higher order extensions have been introduced \cite{JD-Staab2015}. Furthermore, the Markov property enables very efficient likelihood calculation using dynamic programming algorithms to integrate over all ARGs. Such methodology comes from the field of \emph{hidden Markov models (HMM)}\index{hidden Markov model}, which we introduce in the next section. \subsection{Coalescent hidden Markov models} \begin{figure}[t] \begin{center} \includegraphics[width=\textwidth]{Figure2} \end{center} \caption{\label{JD-fig2} Chronology of sequentially Markov coalescent (SMC) and coalescent hidden Markov models (CoalHMM). PSMC: pairwise SMC. MSMC: multiple SMC. ILS: incomplete lineage sorting. I: isolation model. IM: isolation with migration model. } \end{figure} Because of the SMC approximation, likelihood calculation under a coalescent with recombination process represents a classical bioinformatic problem where the probability of an observed state in the sequence depends on an unobserved state, which is then said to be hidden. In the case studied here, the observed states are sequence polymorphisms (between 2 or more individual sequences) and the hidden states are the underlying marginal genealogies. HMMs have been broadly used in sequence analysis \cite{JD-Durbin1998}. \emph{Coalescent hidden Markov models (CoalHMM)}\index{coalescent!hidden Markov model (CoalHMM)} refer to HMMs where the hidden states are genealogies. It was introduced by Hobolth et al \cite{JD-Hobolth2007} as a name of the first model developed, which we introduce later in this section, but was then extended to generally encompass a full class of models \cite{JD-Spence2018} (Figure \ref{JD-fig2}). We note as $\{\boldsymbol{\mathcal{A}}_i\}_{1\leq i \leq L}$ the site-specific random variable of observed states in a sample of $M$ sequences of length $L$. Such states (noted ${\{A_g\}}_{1 \leq g \leq S}$) are, in the general case, a combination of the four nucleotides $A$, $C$, $G$ and $T$ (one per modelled sequence), with the possibility to additionally account for missing data (coded as $N$), so that ${\{A_g\}}_{1\leq g \leq S} \in {\{A,C,G,T,N\}}^M$ and $S < 5^M$ because of symmetry relationships between trees making some of them unidentifiable. We note as $\{x_i\}_{1 \leq i \leq L}$ a particular realisation of $\{\boldsymbol{\mathcal{A}}_i\}_{1\leq i \leq L}$, that is, the sequence data. Furthermore, we note as $\{\boldsymbol{\mathcal{H}}_i\}_{1\leq i\leq L}$ the site-specific random variable describing the marginal genealogies at each position in the sequences. In the general case, such genealogies are rooted trees with $M$ leaves. In HMM terminology, the probabilities of observing the sequence data $x_i$ at a given position $i$ given a realisation of $\boldsymbol{\mathcal{H}}_i$, $\operatorname{Pr}(\boldsymbol{\mathcal{A}}_i \mid \boldsymbol{\mathcal{H}}_i )$, are called the \emph{emission probabilities}\index{emission probability}. $\boldsymbol{\mathcal{H}}_i$ is a random variable that has a continuous distribution. To make likelihood calculations tractable, this distribution is discretized, so that $\boldsymbol{\mathcal{H}}_i$ can take a finite number $n$ of hidden states, $\{H_j\}_{1\leq j \leq n}$. Under a discretised distribution of hidden states, the emission probabilities for each position $i$, hidden state $k$ can be more explicitly written as: \begin{equation} e^{}_{i,k}(x) = \operatorname{Pr}(\boldsymbol{\mathcal{A}}^{}_i = x \mid \boldsymbol{\mathcal{H}}^{}_i = H^{}_k). \end{equation} We further introduce the so-called \emph{transition probability} of a genealogy $H_j$ at position $i-1$ to a genealogy $H_k$ at position $i$ as \begin{equation} q^{}_{i,j,k} = \operatorname{Pr}(\boldsymbol{\mathcal{H}}^{}_i = H^{}_k \mid \boldsymbol{\mathcal{H}}^{}_{i-1} = H^{}_j). \end{equation} Given the set of emission and transition probabilities we can then write the likelihood of the data by recursion. We define $F_{i,k}$ the joint probability of the data (observed states) $x_1, \ldots, x_i$ at positions 1 to $i$ and the ancestral genealogy $H_k$ at position $i$ as: \begin{equation}\label{JD-eqn-forward} F^{}_{i,k} = \operatorname{Pr}(x^{}_1, \ldots, x^{}_i, H^{}_k) = \left\{ \begin{array}{ll} f_k & \mathrm{if}\, i = 0\\ e^{}_{i,k}(x^{}_i)\cdot \sum_j q^{}_{i, j, k}\cdot F^{}_{i-1,j} & \mathrm{if}\, i > 0\\ \end{array} \right., \end{equation} where $\{f_k\}_{1 \leq k \leq n}$ denotes some initial conditions. These conditions may be set to $1/n$, or to the stationary distribution of the Markov chain (providing it exists). Equation \eqref{JD-eqn-forward} is called the \emph{forward algorithm}\index{forward algorithm} and allows for the computation of the likelihood of the sequences as \begin{equation} \mathcal{L} = \sum_k F^{}_{L,k}. \end{equation} This recursion is an example of dynamic programming, allowing for the integration over all possible ARGs very efficiently, as it scales in $\mathcal{O}(L\cdot n^2)$. The symmetry relationships in the transition matrix and the relatively low frequency of the observed heterozygous states, however, allow for further improvement of the run time of the forward algorithm \cite{JD-Harris2014,JD-Terhorst2017,JD-Sand2013}. The likelihood function depends on a set of parameters $\Theta$, which includes the demographic model (effective population size and its variation) and the recombination rate. More complex models can be implemented, for instance allowing for population structure. These parameters can affect either the emission probabilities $e_{i,k}(x)$, the transition probabilities $q_{i,j,k}$, or both. The emission and transition probabilities define the type of model used. Importantly, most models assume that the process is homogeneous along the sequence, so that both $e_{i,k}(x)$ and $q_{i,j,k}$ are actually independent of $i$. In the following, we will review several examples of coalescent HMM models. \subsection{The two-genome case} \begin{figure}[t] \begin{center} \includegraphics[width=\textwidth]{Figure3} \end{center} \caption{\label{JD-fig3} Demographic models and hidden states for CoalHMM with two and three sequences. A: Pairwise SMC. Hidden states correspond to discretised divergence times between two sequences. Parameters of the model potentially contain a species divergence time $\tau$ and several epochs of constant effective population sizes $\theta_k$. The CoalHMM model of Mailund et al. \cite{JD-Mailund2011} uses only one epoch and $\theta$, the corresponding states $t_j$ being, therefore, drawn from the exponential distribution with mean $2\cdot\theta$, shifted by $\tau$. The PSMC model of Li and Durbin \cite{JD-Li2011}, assumes a skyline model of multiple epochs, yet with individuals from the same population ($\tau = 0$). B: CoalHMM with three sequences and ILS. The hidden states correspond to four genealogies that differ both in time and order of the coalescence events. The model assumes constant but distinct ancestral effective population sizes $\theta_{12}$ and $\theta_{123}$, as well as the two species divergence times $\tau_{12}$ and $\tau_{123}$. } \end{figure} When the genome sample consists only of two genomes, the marginal genealogies have a more simple encoding consisting of a single (continuous) number representing the time to the most recent common ancestor (TMRCA) of the two sequences. The TMRCA can be further discretised into $n$ hidden states, each represented by a mean value $(t_j)_{1\leq j \leq n}$. The transition probabilities between the hidden states can be calculated under the SMC. Variants of this model were developed independently by Li and Durbin \cite{JD-Li2011} and Mailund et al \cite{JD-Mailund2011}. In the latter, the two genomes come from two distinct populations that diverged at a time $\tau$ units ago (Figure \ref{JD-fig3}A). The common ancestral population is assumed to have a constant effective population size $\theta_\text{anc}$. The TMRCA $(t_j)_{1\leq j \leq n}$ follows an exponential distribution shifted by an amount of $\tau$. Mailund and collaborators applied this model to the newly sequenced genomes of two Orangutan subspecies in order to estimate their ancestral effective population size and the time of their last genetic exchange. They further extended this model to allow for a period of gene flow after the initial separation of the two populations \cite{JD-Mailund2012}. In the Li and Durbin model, named pairwise sequentially Markov coalescent (PSMC), the two genomes come from a single population. This approach was further improved by Schiffels and Durbin \cite{JD-Schiffels2014}, who used a more accurate recombination model. The authors consider a demographic model where the effective population size is piecewise constant over a given number of epochs (Figure \ref{JD-fig3}A). The parameters of the model consist of the set of ancestral sizes, as well as the recombination rate, presumed to be constant along the sequences. While the epochs of the demographic model and the discretisation scheme used for the divergence time are distinct aspects, it is convenient to have some overlap between the two, providing that there are at least as many hidden states as epochs (otherwise some parameters would become unidentifiable). Li and Durbin proposed to consider one hidden state per epoch, so that each segment is represented by one value of $t_{j}$ and one value of $\theta_j$ (Figure~\ref{JD-fig3}A). By estimating one $\theta$ per epoch, the PSMC model allows the reconstruction of a ``skyline'' plot where population size varies in time, from present to the distant past (Figure~\ref{JD-fig4}). This method was applied to data from the 1000 Genomes Project \cite{JD-1000G2010} in order to infer the demographic history of distinct populations, which show the signature of the out-of-Africa bottleneck. The two approaches of Li and Durbin and Mailund et al. further differ in their calculation of the emission probabilities. Focusing on the population level and a relatively short time span of $\sim 1$ Myr, Li and Durbin consider an \emph{infinite sites model}\index{infinite-sites!model} where only one mutation per site can happen. They further consider all types of mutations as equally probable and ignore the biochemical nature of the underlying nucleotides. This reduces the number of observed states to three types: homozygous (the two sequences are identical at a given position), heterozygous (the two sequences differ at a given position), and unknown (at least one sequence has an unresolved state at that position). The emission probabilities then take the simple form: \begin{eqnarray} e^{}_{i,j,\mbox{homozygous}} &=& \exp(-\theta\cdot t^{}_j)\\ e^{}_{i,j,\mbox{heterozygous}} &=& 1 - \exp(-\theta\cdot t^{}_j)\\ e^{}_{i,j,\mbox{unknown}} &=& 1, \end{eqnarray} where $\theta = 4\cdot N_e\cdot u$ denote the population mutation rate, and $u$ the per nucleotide, per generation molecular mutation rate. Comparing genomes from two distinct (sub)species, therefore potentially encompassing larger time scales, Mailund et al. used a fully parametrised substitution model as used in parametric phylogenetic reconstruction methods \cite{JD-Felsenstein2003}. The mutation process is then a continuous time, discrete-state Markov model with generator $U\!$, and the emission probabilities are given by $\exp(U\cdot t_j)$ for each hidden state $j$. In both models, the emission probabilities only depend on the observed states and are independent of the actual position in the sequence, assuming a homogeneous mutation process along the genome. \begin{figure}[t] \begin{center} \includegraphics[width=\textwidth]{Figure4} \end{center} \caption{\label{JD-fig4} Demographic inference under the PSMC. The MSMC2 software was used independently on 20 diploid individuals from the 1000 genomes project \cite{JD-1000G2010}, 10 from the CEU population (Utah residents with European ancestry) and 10 from the LWK population (Luhya in Webuye, Kenya). MSMC2 was run on data from chromosome 9 only, with default parameters. The results show that individuals with European ancestry underwent a stronger bottleneck between 50 and 100 ky ago, corresponding to the out-of-Africa event. } \end{figure} \subsection{The three-genome case} In 2007, Hobolth et al. introduced the first CoalHMM model \cite{JD-Hobolth2007}, by modelling the possible genealogical relationships between three species: ``$(A,B),C$'', ``$A,(B,C)$'' and ``$(A,C),B$'' (Figure~\ref{JD-fig3}B). Considering the two speciation events that separate first the ancestor of $A$ and $B$ from the ancestor of $C$, and then the ancestor of $A$ from the ancestor of $B$, the probability that an individual sequence from $A$ coalesces with a sequence from $B$ within the $AB$ ancestral species depends on the ancestral population size and the time between the two speciation events \cite{JD-Dutheil2012}. Backwards in time, if the two corresponding lineages do not coalesce until the most ancient speciation time, any of them can coalesce with a sequence from species $C$ before coalescing with each other. This phenomenon, which results in the marginal genealogy being incongruent with the phylogeny, is termed \emph{incomplete lineage sorting (ILS)}\index{incomplete lineage sorting}. Using coalescent theory, Hobolth et al. derived relationships between the transition probabilities and used them to infer ancestral effective population sizes as well as the dates of species divergence, the so-called speciation times. In this first model the hidden states differ in tree topology and divergence times. The first hidden state corresponds to the case where the two lineages A and B coalesce within the ancestral population of A and B, leading to a genealogy congruent with the phylogeny. The three other topologies denote cases where the A and B lineages did not coalesce within the AB ancestor, so that the three lineages A, B and C were already present within the ancestral population of the three species. These three states correspond to the cases where A and B, A and C, or B and C coalesce first, respectively (Figure~\ref{JD-fig3}B). The model assumes constant ancestral population sizes and the divergence times for each topology are reduced to the averages of the corresponding exponential distributions. The proportion of ILS topologies directly depends on the time separating the speciation events $\Delta_T$ and the effective size of the ancestral population $\theta_\text{anc}$ \cite{JD-Dutheil2012}: \begin{equation} \operatorname{Pr}(ILS) = \frac{2}{3}\exp \left(-2\cdot\frac{\theta^{}_\text{anc}}{\Delta^{}_T}\right), \end{equation} allowing the estimations of these parameters from the patterns of topology variation. The three-species CoalHMM model was applied to genome sequences of Great Apes: Orangutan \cite{JD-Hobolth2011}, Gorilla \cite{JD-Scally2012}, Bonobo \cite{JD-Prufer2012}, Baboons \cite{JD-Rogers2019}, in order to infer the patterns of ILS and the ancestral effective population sizes in this group of species (reviewed in \cite{JD-Mailund2014}). It was also applied to species of fungal pathogens where it was used to infer recombination rates \cite{JD-Stukenbrock2011}. \subsection{The multiple-genome cases} With the development of sequencing technologies and the increasing sample size of population genomic datasets, models able to extract the genealogical information contained in multiple genomes are needed. Building CoalHMM models with more than two or three sequences poses, however, a computational challenge because of the underlying combinatorics of marginal genealogies. The number of possible topologies increases hyper-exponentially with the number $M$ of sampled sequences, and there is an infinite number of possible genealogies with a given topology due to the continuous nature of branch lengths (divergence times). Further approximations are, therefore, required to scale CoalHMM approaches with larger datasets. \subsubsection{Using conditional sampling distributions} In a series of articles \cite{JD-Paul2011,JD-Steinrucken2013,JD-Sheehan2013,JD-Steinrucken2019}, Song and collaborators developed an approach based on the so-called \emph{conditional sampling distribution} (CSD) \index{sampling!distribution, conditional} introduced by Li and Stephens \cite{JD-Li2003}. This approach stems from the chain rule of conditional probabilities, allowing the expression of the likelihood of a sample of $M$ sequences $S_1, \ldots, S_M$ as a product of conditional likelihoods: \begin{multline} \operatorname{Pr}(S^{}_1, S^{}_2, \ldots, S^{}_M \mid \Theta) = \operatorname{Pr}(S^{}_1 \mid S^{}_2, \ldots, S^{}_M,\Theta) \cdot \operatorname{Pr}(S^{}_2, \ldots, S^{}_M \mid \Theta)\\ = \operatorname{Pr}(S^{}_1 \mid S^{}_2, \ldots, S^{}_M,\Theta) \cdot \operatorname{Pr}(S^{}_2 \mid S^{}_3, \ldots, S^{}_M \mid \Theta) \cdot \operatorname{Pr}(S^{}_3, \ldots, S^{}_M \mid \Theta)\\ = \operatorname{Pr}(S^{}_M \mid \Theta) \prod_{k=1}^{M-1} \operatorname{Pr}(S^{}_k \mid S^{}_{k+1}, \ldots, S^{}_M,\Theta), \end{multline} where $\Theta$ denotes the parameter vector. The conditional likelihoods, however, are approximated, so that the resulting likelihood is a product of approximate conditionals (PAC) \cite{JD-Li2003}, which depends on the order by which the sequences are treated in the product chain. This is usually accommodated by permutations and averaging \cite{JD-Li2003}, or by a composite likelihood approach such as the ``leave-one-out'' strategy \cite{JD-Sheehan2013}: \begin{equation} \operatorname{Pr}(S^{}_1, S^{}_2, \ldots, S^{}_M \mid \Theta) \simeq \prod_{i = 1}^M \operatorname{Pr}\big( S^{}_i \mid \left\{S^{}_j\right\}^{}_{j \neq i},\Theta\big). \end{equation} The CSD are computed under an SMC model, given a piecewise constant demographic model, as in the PSMC. The model was further extended to allow more complex demographic scenarios with population structure and migration \cite{JD-Steinrucken2019}. \subsubsection{Modelling the most recent coalescence events} Schiffels and Durbin \cite{JD-Schiffels2014} developed the \emph{multiple sequentially Markov coalescent (MSMC)}\index{sequential!Markov coalescent!multiple}, which models only the most recent coalescent event in the sample. The underlying rationale was that the PSMC is lacking resolution in the more recent past, due to the very small number of mutations and coalescences happening in the most recent epochs. Combining multiple samples, therefore, has the potential to compensate for the lack of information in a single pair of genomes. The MSMC approach is elegant as it reduces the combinatorics of the hidden states to one continuous variable (which is discretised, as in the PSMC): the time of coalescence, together with the index of the two genomes in the sample that are coalescing, bringing the number of hidden states to $n = {M\choose 2} \cdot K$, where $K$ is the number of discrete classes used for the distribution of divergence times. The efficiency of the MSMC approach is, however, paradoxical: by gaining resolution in the present as the sample size increases, the method progressively loses power as the number of modelled sequences becomes larger (see \cite{JD-Dutheil2017} for an illustration). In practice, the authors showed that for a human dataset, the maximum resolution is obtained for eight haploid genomes \cite{JD-Schiffels2014}. \subsubsection{Using a composite likelihood}\label{JD-subsubsection-composite} In the MSMC2 approach \cite{JD-Malaspinas2016, JD-Wang2019}, Schiffels and collaborators proposed to approximate the likelihood of a sample of $M$ genomes by independently considering all pairs of genomes. The likelihood of the sample is then approximated by the product of all pairwise likelihoods, each computed under the PSMC model. While the pairwise likelihoods are exact under the SMC, the likelihood of the sample is an example of \emph{composite likelihood}\index{likelihood!composite} \cite{JD-Larribe2011}: \begin{equation} \operatorname{Pr}(S^{}_1, S^{}_2, \ldots, S^{}_M \mid \Theta) \simeq \prod_{i = 1}^{M - 1} \prod_{j = i+1}^M \operatorname{Pr} (S^{}_i, S^{}_j \mid \Theta). \end{equation} The likelihood here is an approximation since the divergence times between pairs of sequences in a genealogy are not independent. The MSMC2 approach is therefore better described as a ``multiple pairwise SMC''. It was shown to display good resolution in both the past and present time, efficiently making use of the increasing quantity of signal as the sample size increases. \subsubsection{Augmenting the PSMC with site frequency spectra}\index{site-frequency spectrum} While approaches like diCal and MSMC2 allow for the efficient modelling of the evolution of multiple genomes, they are intrinsically limited as the computational cost become prohibitive for samples of more than one or two dozen genomes (at least for genomes with a size of the order of that of humans). Terhorst and colleagues introduced a hybrid approach combining the power of the SMC, which makes efficient use of linkage patterns, with that of classical site frequency spectrum (SFS) based approaches \cite{JD-Terhorst2017}. This modelling framework, termed SMC++, considers a ``focus'' diploid individual that is modelled with a PSMC approach. The observed states are then augmented by taking into account additional genomes to compute an SFS. The emission probabilities are calculated as the probability of observing the local SFS given the genealogy at the focus individual, and the authors proposed an approach to compute such a conditional site frequency spectrum (CSFS). The resulting SMC++ model can accommodate hundreds of individual genomes. Another innovation introduced in this approach is the abandonment of the ``skyline'' model of piecewise constant effective population size in favour of a spline model. While divergence times are still discretised, the corresponding times for each category are derived from a spline curve whose parameters are estimated. This reduces the number of parameters to estimate and ensures smoother inferred demographies. The SMC++ approach has been applied to human data as well as other species, including Drosophila and Zebra finch \cite{JD-Terhorst2017}. \section{Heterogeneity of processes along the genome} \label{JD-section-het} In all models that we evoked so far, evolutionary processes have been considered to be homogeneous along sequences. In this section, I review evidence that these assumptions are at odds with our current knowledge of the biology of genomes. \subsection{Variation of the recombination rate} Recombination rates can vary extensively between species \cite{JD-Stapley2017}, between sexes \cite{JD-Lenormand2005} and within genomes. At the molecular scale, multiple levels can be distinguished: recombination rate correlates negatively with chromosome size, a pattern attributed to the mechanism of meiosis and crossing-over interference \cite{JD-Kaback1996}. Given that the rate of crossing-over events is low, this leads to a higher recombination rate in small chromosomes. Recombination rates vary also within chromosomes: in Primates, it is generally higher at the start and end of the chromosomes (the so-called telomeric regions) \cite{JD-Stevison2016}, while in Drosophila the opposite pattern is observed \cite{JD-Comeron2012,JD-Chan2012}. In many species recombination events have an increased chance to occur in particular regions, called hotspots \cite{JD-Petes2001,JD-Myers2005,JD-Stukenbrock2018} (but see \cite{JD-Wallberg2015} for a counterexample). The variation of recombination rate has two types of consequences on the patterns of sequence diversity. Because the molecular mechanisms of recombination are tightly linked to DNA repair, recombination itself can be mutagenic and locally increase sequence variability \cite{JD-Lercher2002,JD-Alves2017}. Furthermore, in many species, the repair mechanisms involve gene conversion between homologous sequences, as one chromosome is used as a template to repair the other one. However, this mechanism is biased in many species: in the case of heterozygous positions, the ``C'' or ``G'' nucleotides are preferred over ``A'' and ``T'' nucleotides, potentially resulting in large scale variations of GC content \cite{JD-Duret2009} mirroring the variations in recombination rate. The recombination rate also has indirect effects on genetic diversity: because it breaks down genetic linkage, recombination counteracts the reduction of diversity at sites linked to loci under selection, both negative (background selection \cite{JD-Charlesworth1993}) and positive (genetic hitch-hiking \cite{JD-Barton2000}). By modulating the local effective population size, variation of recombination rate along the genome has a strong impact on the underlying genealogy. \subsection{Variation of the mutation rate} Finally, the rate at which mutations occur can vary extensively along the genome \cite{JD-Baer2007}. Mutations can occur via direct modification of the DNA or indirectly, via errors in the replication or repair mechanisms. Particular sequence motifs, such as CpG dinucleotides are known to undergo comparatively higher mutation rates, via the methylation of the cytosine, which is then deaminated into a thymine, leading to a TpG dinucleotide. In addition to the potentially mutagenic effect of recombination, which also plays a role in the repair of DNA damage, the replication machinery itself is error-prone. This error rate is position dependent: it increases with the replication time, being lower close to the origins of replication \cite{JD-Stamatoyannopoulos2009, JD-Agier2012, JD-Weber2012}. Under a neutral scenario, the mutation process is independent of the coalescent process \cite{JD-Hudson1983}, and, therefore, has no impact on the underlying genealogies. Yet, for inference models, mutation rate variation acts as a confounding factor, as a high sequence divergence can be either explained by an ancient coalescence time or a high mutation rate. In CoalHMM models, the mutation rate will have an impact on the emission probabilities, that is, the probability of observing the observed sequence diversity given a genealogy. \section[]{Existing approaches to account for spatial heterogeneity} In this section, I review the approaches that have been developed to cope with the heterogeneity of evolutionary processes acting along the genome. \subsection{Inferring sequential heterogeneity alone} A large body of work is built on the idea that, if a parameter affects certain patterns of genetic diversity, it should be possible to use these patterns to recover the underlying variation of the parameter. The most studied case in this respect is the recombination rate, via its impact on linkage disequilibrium. Given an a priori known demographic scenario, it is possible to compute the likelihood of the data for any given recombination rate, and use it to estimate the most likely recombination rate value. Due to the complexity of the underlying model, however, approximations are required to apply these methods to large genomic datasets. McVean, Awadalla and Fearnhead \cite{JD-McVean2002} introduced the use of a composite likelihood, approximating the full likelihood by the product of the likelihoods of all pairs of positions within a minimum distance of each other. This approach is the basis of several popular methods for recombination rate inference such as LDhat \cite{JD-Auton2012} and LDhelmet \cite{JD-Chan2012}. Further developments of these models allowed for the incorporation of variable population sizes \cite{JD-Kamm2016, JD-Spence2019}. The underlying demography, however, has to be estimated independently from the data. Li and Stephens \cite{JD-Li2003}, on the other hand, used the conditional sampling distribution and the product of approximate conditionals (PAC) to approximate the likelihood. An application of this method also includes the reconstruction of haplotypes from genotypic data, a problem known as \emph{phasing}\index{phasing} \cite{JD-Stephens2005}. \subsection{Inference using piecewise-homogeneous processes} The most simple approach to infer heterogeneous processes along the genome while jointly accounting for demography is to use a window-based approach, consisting of dividing the genome into segments of fixed sizes and estimating model parameters independently in each resulting window. This strategy was used by Stukenbrock et al. \cite{JD-Stukenbrock2011} to use the patterns of ILS and a CoalHMM model to estimate the recombination rate in 100 kb windows along the genome of the fungal pathogen \textit{Zymoseptoria tritici}. In most cases, however, SMC models require long genome sequences to be able to confidently estimate parameters, and cannot be run in windows of small sizes, in particular for models at the population level. Furthermore, window-based approaches raise the issue of the window size and boundaries to use. \subsection{Using sequentially heterogeneous simulation procedures} While the computation of the likelihood of the data under a sequentially heterogenous process is notoriously difficult, simulating under the corresponding model can be comparatively easy. Software like the Markovian coalescent simulator (MaCS) \cite{JD-Chen2009}, the sequential coalescent with recombination model (SCRM) \cite{JD-Staab2015}, fastsimcoal \cite{JD-Excoffier2011} and MSprime \cite{JD-Kelleher2016} allow the simulation of population genomic data sets under models with variable recombination rate. Owing to their high computational efficiency, they can be used within an approximate Bayesian computation (ABC) framework in order to estimate demographic parameters under realistic recombination models \cite{JD-Wegmann2010}. This possibility, however, has to date been underexploited, as demographic inference is so far conducted with data simulated under a homogeneous recombination landscape (see for instance \cite{JD-Li2012}). While no ABC method has been developed with the goal to infer the variation of population genomic parameters along the genome, Gao et al.~\cite{JD-Gao2016} introduced a machine learning approach to infer recombination rates. The underlying simulations, however, are conducted under a model with constant recombination rate. \subsection{A posteriori inference of heterogeneous processes} The HMM methodology allows, via the forward algorithm, to compute the likelihood of the data given a specified demographic model by efficiently integrating over the unknown underlying ARG. The HMM toolbox further allows for the computation of the a posteriori probability of each marginal genealogy for each position \cite{JD-Dutheil2017}: \begin{equation} \operatorname{Pr}(\boldsymbol{\mathcal{H}}^{}_i = H^{}_j \mid x^{}_1, \ldots, x^{}_L) = \frac{\operatorname{Pr}(x^{}_1, \ldots, x^{}_L, \boldsymbol{\mathcal{H}}^{}_i = H^{}_j)}{\operatorname{Pr} (x^{}_1, \ldots, x^{}_L)}. \end{equation} The denominator of the ratio is the likelihood of the data, $\mathcal{L}$. In order to compute the numerator, we need to introduce the so-called \emph{backward algorithm}\index{backward!algorithm} \cite{JD-Durbin1998}: \begin{equation}\label{JD-eqn-backward} B^{}_{i,j} = \operatorname{Pr}(x^{}_{i+1}, \ldots, x^{}_L \mid \boldsymbol{\mathcal{H}}^{}_i = H^{}_j) = \left\{ \begin{array}{ll} 1 & \mathrm{if}\, i = L\\ \sum_k e^{}_{i+1,k}(x^{}_{i+1})\cdot q^{}_{i+1, j, k}\cdot B^{}_{i+1,k} & \mathrm{if}\, i < L , \\ \end{array} \right. \end{equation} The posterior probability of hidden state $H_j$ can therefore be computed as \begin{equation} \operatorname{Pr}(\boldsymbol{\mathcal{H}}^{}_i = H^{}_j \mid x^{}_1, \ldots, x^{}_L) = \frac{F^{}_{i,j}\cdot B^{}_{i,j}}{\mathcal{L}}. \end{equation} This formula allows for the reconstruction of the most probable marginal genealogy at each position $i$ by taking the maximum posterior probability \begin{equation} \widehat{\boldsymbol{\mathcal{H}}}^{}_i = \underset{j}{\operatorname{arg\,max}}\left(\operatorname{Pr}(\boldsymbol{\mathcal{H}}^{}_i = H^{}_j \mid x^{}_1, \ldots, x^{}_L)\right), \end{equation} a procedure called \emph{posterior decoding}\index{posterior decoding}. The posterior decoding is performed after fitting the model parameters by maximizing the likelihood. It is therefore an example of \emph{empirical Bayesian}\index{empirical Bayesian} inference \cite{JD-Maritz2018}. Posterior probabilities of marginal genealogies can also be used to obtain posterior estimates of biological quantities of interest, accounting for the uncertainty on the underlying genealogy. The posterior mean estimate $\widehat{\lambda}_i$ at position $i$ of a property $\Lambda(H_j)$ can be obtained by \begin{equation}\label{JD-eqn-postav} \widehat{\lambda}^{}_i = \sum_j \operatorname{Pr} (\boldsymbol{\mathcal{H}}^{}_i = H^{}_j \mid x^{}_i, \ldots, x^{}_L) \cdot\Lambda(H^{}_j). \end{equation} If $\Lambda$ is the coalescence time between two sequences, this formula can be used to get posterior estimates of sequence divergence along the genome \cite{JD-Palamara2018}. More complex examples of functions include, for instance, whether $\boldsymbol{\mathcal{H}}_i$ is distinct from $\boldsymbol{\mathcal{H}}_{i-1}$, or, in other words, whether a recombination event occurred between positions $i$ and $i-1$. This allows for the reconstruction of a recombination map, integrating over the ARG. Such approach was notably used by Munch et al \cite{JD-Munch2014} to reconstruct the recombination map of the human-chimpanzee ancestor. Posterior estimates are rather robust to the specified input model and can therefore offer a powerful approach to infer aspects of the process that are not directly accounted for by the model. However, because some model properties are intrinsically confounded, such as local divergence and mutation rate, ignoring spatial heterogeneity might result in biased inference \cite{JD-Barroso2019}. \section{The integrative sequentially Markov coalescent} In order to account for heterogeneous processes along the genome, we recently developed the integrative sequentially Markov coalescent (iSMC) \cite{JD-Barroso2019}, an extension of the SMC. In this framework, parameters of the original SMC vary along the genome in a Markovian manner, allowing for the modelling of genome heterogeneity in addition to demographic processes. I illustrate this approach with results from a recent application of this framework to infer recombination landscapes and further discuss possible extensions. \subsection{The Markov-modulated sequentially Markov coalescent} Whilst the framework can be applied to cases where more than one parameter varies along the genome, for simplicity, we here consider the case where one parameter only varies, which we label $\boldsymbol{\mathcal{R}}$, $\boldsymbol{\mathcal{R}}_i$ denoting the values of $\boldsymbol{\mathcal{R}}$ at position $i$ in the sequences. We assume that $\boldsymbol{\mathcal{R}}$ follows an a priori known discrete distribution with $n^R$ categories, each with mean value $R_k$, with $1 \leq k \leq n^R$. In the iSMC framework, the transition and/or emission probabilities are functions of $\boldsymbol{\mathcal{R}}$ and are, therefore, noted as $e^\text{SMC}_{i,k}(x, R)$ and $q^\text{SMC}_{i,j,k}(R)$, respectively. The key assumption is then to consider that the variation of $\boldsymbol{\mathcal{R}}$ along the genome can be modelled as a Markov model, that is, there is a matrix of probabilities $q^R$ defined as \begin{equation} q^R_{i, j,k} = \operatorname{Pr}(\boldsymbol{\mathcal{R}}^{}_i = R^{}_k \mid \boldsymbol{\mathcal{R}}^{}_{i-1} = R^{}_j). \end{equation} The forward recursion of the CoalHMM can then be written as \begin{multline} F^\mathrm{SMC}_{i,j,k} = \operatorname{Pr}(x^{}_1, \ldots, x^{}_i, H^{}_j, R^{}_k) = \\ \left\{ \begin{array}{ll} f^{}_j \cdot f^R_k & \mathrm{if}\, i = 0\\[2mm] e^{\mathrm{SMC}}_{i,j}(x^{}_i, R^{}_k)\cdot\sum_u \sum_v q^{\mathrm{SMC}}_{i, u, j} (R^{}_k) \cdot q^R_{i, v, k}\cdot F^{\mathrm{SMC}}_{i-1,u,v} & \mathrm{if}\, i > 0 ,\\ \end{array} \right. \end{multline} where $f^R_k$ denotes the a priori probability $\operatorname{Pr}(\boldsymbol{\mathcal{R}} = R_k)$. Because the SMC now depends on a parameter that itself follows a Markov process, the resulting process can be described as a Markov-modulated Markov chain (MMMC). As an MMMC is itself a Markov process \cite{JD-Galtier2004}, we can rewrite the forward recursion as: \begin{equation}\label{JD-eqn-forward-ismc} F^{\text{iSMC}}_{i,k} = \operatorname{Pr}(x^{}_1, \ldots, x^{}_i, H^{\text{iSMC}}_k) = \left\{ \begin{array}{ll} f^{\text{iSMC}}_k & \mathrm{if}\, i = 0\\[2mm] e^{\text{iSMC}}_{i,k}(x^{}_i)\cdot\sum_j q^{\text{iSMC}}_{i, j, k}\cdot F^{\text{iSMC}}_{i-1,j} & \mathrm{if}\, i > 0 .\\ \end{array} \right. \end{equation} In the iSMC hidden Markov model, the hidden states $H^\text{iSMC}$ consist of all possible pairs of genealogies and $\boldsymbol{\mathcal{R}}$: $(R_a, H_b)$, with $1 \leq a \leq n^R$ and $1 \leq b \leq n$. The emission probabilities $e^\text{iSMC}_{i,j}(x)$ now depend on the pair $(R,H)_j$, and the initial probabilities of the hidden states are $f^\text{iSMC} = f^R \otimes f$. Similarly, the transition probabilities of the Markov-modulated SMC (MMSMC) can be written as a function of the transition probabilities of the two Markov chains: \begin{equation} q_i^{\text{iSMC}} = \left( \begin{array}{ccc} q^R_{i,1,1} \cdot q_i^{\text{SMC}}(R^{}_1) & \cdots & q^R_{i,1,n^R}\cdot q_i^{\text{SMC}}(R^{}_1) \\ \vdots & \ddots & \vdots \\ q^R_{i,n^R,1} \cdot q_i^{\text{SMC}}(R^{}_{(n^R)}) & \cdots & q^R_{i,n^R,n^R} \cdot q_i^{\text{SMC}}(R^{}_{(n^R)}) \end{array}\right) . \end{equation} (As we consider the process modelling the variation of $\boldsymbol{\mathcal{R}}$ to be itself homogeneous along the genome, we have $\forall i_1, i_2,\;q^{\text{iSMC}}_{i_1, j,k} = q^{\text{iSMC}}_{i_2, j,k} = q^{\text{iSMC}}_{j,k}$.) The iSMC model can therefore be analysed with standard HMM methodology, just like the homogeneous SMC. The number of hidden states, however, is now $n^R\cdot n$, meaning that the complexity of the likelihood calculation becomes $\mathcal{O}\big(L\cdot (n \cdot n^R)^2\big)$. The iSMC model adds relatively few extra parameters to the SMC: the transition probabilities $q^R$, which can be reduced to one parameter (see below), and parameters of the a priori distribution of $\boldsymbol{\mathcal{R}}$. While parameters of the distribution of $\boldsymbol{\mathcal{R}}$ are generally not of direct biological interest, the posterior decoding of the HMM allows for the inference of the underlying landscape of the heterogeneous parameter. Distinct decoding procedures can be performed in the case of Markov-modulated HMMs: \begin{enumerate} \item A full decoding, where the most likely pair $(R,H)$ at each position is reconstructed: \begin{equation} \widehat{\left(\boldsymbol{\mathcal{R}}, \boldsymbol{\mathcal{H}}\right)}^{}_i = \underset{j,k}{\operatorname{arg\,max}}\left(\operatorname{Pr} (\boldsymbol{\mathcal{H}}^{}_i = H^{}_j, \boldsymbol{\mathcal{R}}^{}_i = R^{}_k \mid x^{}_i, \ldots, x^{}_L)\right), \end{equation} \item A partial decoding of genealogies, where the most likely genealogy is inferred, summing over all heterogeneous parameters: \begin{equation} \hat{\boldsymbol{\mathcal{H}}^{}_i} = \underset{j}{\operatorname{arg\,max}}\Big(\sum_k\operatorname{Pr}(\boldsymbol{\mathcal{H}}^{}_i = H^{}_j, \boldsymbol{\mathcal{R}}^{}_i = R^{}_k \mid x^{}_i, \ldots, x^{}_L)\Big), \end{equation} \item A posterior mean estimation of the heterogeneous variable. Setting $\Lambda(H_j, R_j) = R_j$ and applying equation \ref{JD-eqn-postav}, we get: \begin{multline}\label{JD-eqn-post3} \hat{\boldsymbol{\mathcal{R}}^{}_i} = \sum_j \sum_k \operatorname{Pr} (\boldsymbol{\mathcal{H}}^{}_i = H^{}_j, \boldsymbol{\mathcal{R}}^{}_i = R^{}_k \mid x^{}_i, \ldots, x^{}_L)\cdot R^{}_k\\ = \sum_k R^{}_k \cdot\sum_j \operatorname{Pr}(\boldsymbol{\mathcal{H}}^{}_i = H^{}_j, \boldsymbol{\mathcal{R}}^{}_i = R^{}_k \mid x^{}_i, \ldots, x^{}_L).\\ \end{multline} \end{enumerate} The partial decoding of genealogies enables the reconstruction of the ARG while accounting for the heterogeneity of the SMC along the genome. The posterior estimates of the heterogeneous variable allows the reconstruction of the variation along the genome while accounting for the genealogy and its uncertainty. In the next section, we apply this framework to model the variation of the recombination rate along the genome. \subsection{A case study: inference of recombination rate variation} Recombination is the best documented heterogeneous process along the genome. It can be measured experimentally or indirectly using genomic approaches (reviewed in \cite{JD-Auton2012}). In the context of the sequential coalescent and the SMC approximation, the local recombination rate affects the probability of transition from one genealogy to another, which increases with higher recombination rates. To model variable recombination rates in iSMC, we considered that the local population recombination rate $\rho = 4\cdot N_e\cdot r$, where $r$ is the molecular recombination rate in cM / bp per generation, is the product of a genome average $\rho_G$ and a local modifier $r^\rho$. This modifier follows a prior discrete distribution of mean 1 and with $n^\rho$ categories, for instance a discretised Gamma distribution with shape parameter $\alpha$. We further considered a simple model for the transition probabilities between the $r^\rho$ classes, assuming equal probabilities of change, $\gamma$. The transition probability matrix $q^\rho$ takes the form: \begin{equation} q^\rho = \left(\begin{array}{cccc} 1 - \gamma & \gamma / (n^\rho - 1) & \cdots & \gamma / (n^\rho - 1)\\ \gamma / (n^\rho - 1) & 1 - \gamma & \ddots & \vdots \\ \vdots & \ddots & \ddots & \gamma / (n^\rho - 1) \\ \gamma / (n^\rho - 1) & \cdots & \gamma / (n^\rho - 1) & 1 - \gamma\\ \end{array}\right). \end{equation} Using the forward equation~\ref{JD-eqn-forward-ismc}, we can compute the likelihood of the parameters of the iSMC model. Using optimisation procedures, estimates of the $\alpha$ and $\gamma$ parameters together with the average $\rho_G$ and the demography parameters can be obtained by maximizing the likelihood function. The likelihood calculation can also be used to perform model comparisons and test for the heterogeneity of the coalescent process along the genome, for instance using Akaike's information criterion (AIC). \begin{figure}[t] \begin{center} \includegraphics[width=\textwidth]{Figure5} \end{center} \caption{\label{JD-fig5} Posterior estimates of recombination rates from a single diploid genome using iSMC. A 30 Mb region was simulated using the SCRM program \cite{JD-Staab2015} and a variable recombination rate, and then inferred with iSMC, as described in \cite{JD-Barroso2019}. Recombination rates were averaged in windows of 200 kb. } \end{figure} A posterior decoding approach (equation \ref{JD-eqn-post3}) can then be used to obtain estimates of site-specific recombination rates. Simulations under controlled recombination landscape and demography can be used to assess the accuracy of the iSMC inference \cite{JD-Barroso2019}. Figure \ref{JD-fig5} shows that iSMC recovers the underlying recombination landscape with good accuracy, despite generally underestimating high recombination rates. A possible explanation for this is the discretisation procedure, as the posterior mean estimate is bounded by the class with the highest mean recombination value. Allowing for more recombination classes allows for a wider range of values and can potentially reduce this bias, at the cost of increasing the running time and memory usage. Because it can recover the recombination landscape from a single diploid only, the iSMC model was used to generate recombination maps from extinct hominids from their ancient genome sequences \cite{JD-Barroso2019}. \subsection{Extension of iSMC: multiple genomes and multiple heterogeneous parameters} The Markov-modulated Markov model framework underlying the iSMC approach can be applied to other SMC models, such as the MSMC \cite{JD-Schiffels2014}. Hidden states of the resulting CoalHMM are combinations of TMRCA, pairs of genome indices undergoing the most recent coalescent event, and classes of heterogenous parameters such as the recombination rate. Extension to multiple genomes can also be achieved using a composite likelihood approach, as implementated in MSMC2 (see~\ref{JD-subsubsection-composite}). The likelihood of the dataset is then approximated by the product of the likelihoods of each pair of genomes, which are modelled separately with their own process. In the case of the iSMC approach, this implies considering that the heterogeneous parameters vary independently along each pair of genomes; for a model with variable recombination rate, this is equivalent to estimating a distinct recombination map for each pair of genomes. This assumption is clearly incorrect for the vast majority of positions within genomes from the same population. Extensions enforcing a common map while allowing the coalescent processes to be independent will, therefore, be instrumental in efficiently scaling the iSMC approach to larger sample sizes. The iSMC framework further allows the joint modelling of the variation of multiple parameters along the genome, such as the mutation and recombination rates. In such approach, the hidden states are a combination of TMRCA and classes for each discretised parameter. The addition of any additional heterogeneous parameter multiplies the complexity of the likelihood calculation by ${n^\phi}^2$, where $n^\phi$ is the number of discrete classes considered for the parameter distribution. Besides the increased complexity, identifiability issues may also arise, since local patterns of diversity may be equally explained by variation of demography, recombination rate or mutation rate. However, when these parameters vary at a scale larger than the variation of the TMRCA along the genome and when very large genome sequences are analyzed, increasingly complex models may be successfully fitted. \section{Conclusions} The availability of complete genome data opened the floodgates for the detailed inference of the demographic history of species. A new generation of coalescent-based models permits the extraction of demographic signal from the patterns of genetic linkage along sequences. Such models, however, largely ignore fundamental aspects of genome biology, that is, that processes such as recombination and mutation are highly heterogeneous along genomes. Extending these approaches to account for such heterogeneity not only potentially improves demographic inference, but also allows to reconstruct the underlying genomic landscape. \subsection*{Acknowledgement} I would like to thank Gustavo V.~Barroso for critical reading of this manuscript and for providing the simulation data plotted in Figure~\ref{JD-fig5}. I am deeply indebted to Ellen Baake, as well as Jeffrey~P.~Spence and an anonymous reviewer for their careful reading of the manuscript, for finding several mistakes and typos, and for their suggestions on how to improve its clarity.
{'timestamp': '2020-10-19T02:16:21', 'yymm': '2010', 'arxiv_id': '2010.08359', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08359'}
arxiv
\subsection{SEIR Model} We consider a compartmental SEIR model from which one can obtain trajectories of the epidemic, given the current state and epidemic-specific parameters. An SEIR model divides the population into \textit{Susceptible}, \textit{Exposed}, \textit{Infected} and \textit{Recovered} compartments and can be described in terms of ordinary differential equations (ODEs)~\cite{he2020seir}. While exposed refers to the latent infected but not yet infectious population, recovered contains the population that is no longer infectious (also referred as removed). While this has been popularly used to model influenza epidemics~\cite{mills2004transmissibility}, there have been several existing efforts that have utilized this model with great success in the case of the recent COVID-19 epidemic~\cite{lopez2020modified,roda2020difficult,yang2020modified}. Formally, an SEIR model is described as follows: \begin{equation} \begin{aligned} \frac{dS}{dt} &= -\beta S(t) I(t) \\ \frac{dE}{dt} &= \beta S(t) I(t) - \sigma E(t)\\ \frac{dI}{dt} &= \sigma E(t) - \gamma I(t) \\ \frac{dR}{dt} &= \gamma I(t). \end{aligned} \label{eqn:seir} \end{equation} Here, the the rate of changes in the compartments are parameterized by infectious rate $\beta$, incubation rate $\sigma$ and the recovery rate $\gamma$. The severity of an epidemic is characterized by the \textit{basic reproduction number} that quantifies the number of secondary infections from an individual in an entirely susceptible population as $R_0 = \frac{\beta}{\gamma}$. Following common parameter settings assumed by COVID-19 studies in different countries, we set $\gamma = 0.1$, $\sigma = 0.2$. Interestingly, even in this simple model, one can introduce the effects of different NPI choices through changes in the infectious rate $\beta$. While there are existing works that attempt to estimate the current value of $\beta$ using additional data sources (e.g. mobility), in order to better fit the observed trajectory~\cite{soures2020sirnet}, our focus is on choosing the optimal policy of intervention. In particular, we define the set of NPI choices through corresponding $\beta$ values $\mathcal{N}\coloneqq \{0.25,0.3,0.5,0.7,0.8,0.9\}$, where higher $\beta$ implies lower restrictions. \subsection{Agent-based EpiCast Model} EpiCast is an individual-based model, with daily contacts between people in household, workplace, school, neighborhood, and community settings. The primary data source is U.S. Census demographics at the tract level (the $\sim 65,000$ tracts are subsets of the $\sim 3000$ counties, with typically a few thousand people in each tract), and Census tract-to-tract workerflow data (i.e., how many people live in tract A and work in tract B). This is used to construct a model population with tract-level age and household size demographics, and realistic daily workflow pattern, which captures most of the short-range mobility. In addition, occasional long-distance travel is possible. A 12-hour timestep is used, so (unless on travel) individuals spend the night-time at home and day-time at school or workplace, if they belong to one (and they are open). Additional details are provided in the Supporting Information of~\cite{Germann2006}. In the original model~\cite{Germann2006,Halloran2008}, the individual age- and context-specific contact rates that account for the duration and closeness of interactions between pairs of individuals in different settings (home, school, workplace, neighborhood, community, etc.) were uniform across the US. In a recent school dismissal study~\cite{Germann2019}, different communities were allowed to close their schools at different times, depending upon the current local disease incidence. In adapting this model to COVID-19, these local policies have been extended to all community mitigation measures: school dismissal, workplace closure, shelter-in-place, and other social distancing. \input{algorithm} \section{Introduction} \label{sec:intro} \input{intro} \section{Problem Formulation} \input{setup} \section{Epidemiological Models} \input{epimodels} \section{Proposed Algorithm} \input{approach} \section{Case Studies} In this section, we use the proposed optimization algorithm to determine the NPI policy using both SEIR and EpiCast models. All our empirical studies are carried out using different scenarios, and we employ a simple reward assignment for each of the NPI choices. In both the models, we set the frequency of changing the NPI $d = 14$ days. As described earlier, while SEIR reflects the effects of NPI coarsely through the change in infectious rate $\beta$, EpiCast allows more fine-grained characterization of school or business restrictions. \subsection{Optimizing $\beta$ Switches in SEIR} \input{results-seir} \subsection{Optimizing Phase Switches in EpiCast} \label{sec:epi} \input{results-epi} \section{Conclusions} \input{conclusions} \section{Acknowledgements} This work was performed under the auspices of the U.S. Department of Energy by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344. Research was supported by the DOE Office of Science through the National Virtual Biotechnology Laboratory, a consortium of DOE national laboratories focused on response to COVID-19, with funding provided by the Coronavirus CARES Act.
{'timestamp': '2020-10-19T02:20:34', 'yymm': '2010', 'arxiv_id': '2010.08478', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08478'}
arxiv
\section{Introduction} To achieve a robust mmWave wireless backhaul with high network survivability, our work herein considers a distributed mmWave backhaul network architecture with relay nodes in urban environments. In this architecture, a number of mmWave dedicated relays in between small-cell base stations (SBSs) are deployed along urban streets, which naturally produces a mesh network structure. Note that such street-level deployment making use of lampposts has been suggested as a good choice in the 5G era [1]-[4], because it provides easy access to power, good access tier coverage for users and facilities, and ease of deployment in urban environments. The interference-free triangular-wave topology (IFTW) is very well suited to provide high data rate communications for relay-assisted mmWave backhaul in roadside environments [2], [5]-[8]. In the IFTW topology, BSs and relays ($N_k$) are deployed on equally-spaced lampposts on both sides of the road, where the topology angle $\theta$ and horizontal distance between adjacent nodes $d_{0}$ are the same everywhere along the topology (as depicted by the blue links of Fig.~\ref{block_topol}). One advantage of the IFTW topology is that the mutual interference along the path can be eliminated if $\theta$ is made large enough relative to the beamwidth $\phi$ of the directional antennas (Theorem 1 in [2]), i.e., if the interference-free condition in Eq. (1) is satisfied: \begin{equation} \theta - \arctan (\frac{{\tan \theta }}{3}) > \frac{\phi }{2}. \label{interf_free_eq} \end{equation} \begin{figure}[htbp] \vspace{-0.2cm} \setlength{\abovecaptionskip}{-0.1cm} \centerline{\includegraphics[width=115mm]{block_model_topology.pdf}} \caption{Original and alternative links in the IFTW topology.} \label{block_topol} \end{figure} Given a road width $d_{w}$ and length $d_{l}$, $d_0$ and the number of required nodes $N$ (including two BSs and several relays) in the IFTW topology are only determined by $\theta$ as ${d_0} = {d_w}/\tan \theta$ and $N = \left\lfloor {{d_l}/{d_0}} \right\rfloor + 1$, respectively. Another advantage of the IFTW topology is the ability to reconfigure mmWave paths to avoid obstacles that occur along the roadway. Through adaptive beam steering when an obstacle blocks one or more of the original links, alternative links (shown in Fig.~\ref{block_topol}) can be used to restore the connectivity of the topology. In our previous work [5], we identified the following four types of blockages that can occur from a single obstacle along the roadway with the IFTW topology: \textit{a) Type} I: An obstacle in $L_{k}$ region blocks only a original link of the topology, such as $P_{1}$ in Fig.~\ref{block_topol}. \textit{b) Type} II: An obstacle in $L_{k}$ region blocks an original link and an adjacent alternative diagonal link simultaneously, such as $\{P_{1}, P_{2}\}$ for $N_{k}$ or $\{P_{1}, P_{5}\}$ for $N_{k+1}$. \textit{c) Type} III: An obstacle in $L_{k}$ region blocks an original link and a crossing alternative diagonal link, such as $\{P_{1}, P_{4}\}$. \textit{d) Type} IV: An obstacle in $L_{k}$ region blocks all the TX/RX links of $N_{k}/N_{k+1}$, such as $\{P_{1}, P_{2}, P_{3}\}$ $/\{P_{1},P_{5},P_{6}\}$, which is equivalent to the failure of node $N_{k}/N_{k+1}$. Any blockages produced by randomly placed obstacles can be decomposed into one or a combination of the above four types (Theorem 1 in [5]). This model takes into account the correlation between blockages, for example, a single blockage close to a node could block multiple mmWave paths simultaneously, which has not been considered in most previous studies [9]-[10]. In what follows, we investigate a blockage-type detection scheme based on this blockage model in the IFTW topology, which can be exploited for both link-level reconfiguration [6] and joint link-network level reconfiguration approaches [7]-[8]. \section{Blockage type detection scheme} In general, the scheme has two phases: preparation phase and detection phase. The former aims to make every node in the topology know the occurrence of blockage and ready for coordination with others. The detection on link connectivity is conducted in the second phase. Since the durance of BTD and path reconfiguration is very short, we assume that no new blockage appears within this time period. \begin{figure}[htbp] \vspace{-0.2cm} \setlength{\abovecaptionskip}{+0.1cm} \centerline{\includegraphics[width=130mm]{original_figure.pdf}} \caption{The possible alternative paths and the adjacent node set of $N_{k}$.} \label{altern_path} \end{figure} \subsection{Preparation Phase} For arbitrary node $N_{k}$, it knows respective adjacent node set $\textit{Adj}$=\{$N_{k+i}$: -2$\le$$\textit{i}$$\le$3, $i$$\neq$0\}, alternative link set $\textit{Sub}$=\{$e_{k,k+j}$: 2$\le$$j$$\le$3\}, and TX link set $\textit{Tl}$=$Sub$ $\cup$ \{$e_{k,k+1}$\}. Note that \textit{Adj}, \textit{Sub} and \textit{Tl} of node $N_{k}$ may change according to different relay path reconfiguration algorithms. During this phase, the following steps describe how nodes negotiate with each other to make preparation for detection. \textbf{\textit{Step} 1.} Considering the possible packet transmission error through links, the packet would be retransmitted for at most two times if the transmitter received nothing or NACK from receiver. Therefore, when an obstacle occurs between $N_{k}$ and $N_{k+1}$, i.e. the original link $L_{k}$ is blocked (shown in Fig.~\ref{altern_path}), $N_{k+1}$ will not receive expected data with high rate from $N_{k}$ and then replied NACK, and if $N_{k}$ receives nothing back or three consecutive NACK (through possible NLOS paths) from $N_{k+1}$ during its own transmitting slot $T_{s}$, both $N_{k}$ and $N_{k+1}$ will know the occurrence of blockage between them by the end of $T_{s}$. We denote this time as $t_{0}$. \textbf{\textit{Step} 2.} Starting from $t_{0}$, $N_{k}$ waits for a period of time, which is called ``nodes preparation time" (NPT). Considering left-part and right-part nodes of $N_{k}$, NPT can be computed as follow: \begin{equation} NPT = \left\{ \begin{array}{l} \max \{ (\left\lceil {k/2} \right\rceil \cdot 2 - 1),N - k - 2\} \cdot {T_s},{\rm{~~~1}} \le k \le N{\rm{ - 2}} \\ (\left\lceil {k/2} \right\rceil \cdot 2 - 1) \cdot {T_s},{\rm{~~~~~~~~~~~~~~~~~~~~~~~~~~}}k{\rm{ = }}N{\rm{ - 1, }}N \\ (N - 2) \cdot {T_s},{\rm{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}k{\rm{ = 0}} \\ \end{array} \right. \end{equation} \noindent where \textit{k} is the node index of $N_{k}$ and \textit{N} is the number of nodes in the topology. This NPT is consumed for two reasons: \vspace{-0.3cm} \begin{enumerate} \item At the beginning of NPT, $N_{k+1}$ will send data as usual during its own transmitting time slot $T_{s}$, but appending a stop transmitting signal (STS) to $N_{k+2}$, then $N_{k+2}$ also transmits data and STS to next node in its time slot, therefore, after ($N$-$k$-$2$)$\cdot$$T_{s}$, all latter nodes of $N_{k+1}$, i.e. $N_{k+i}$ ($i$$\ge$2), will receive STS and know that one of previous original links is blocked, meanwhile switch their antennas to the omni-directional fashion from left to right once getting STS, which is convenient for receiving the following possible detection information. By the end of NPT, every node on the right side of $N_{k}$ completes the antenna switching process, and it could equip an additional omni-directional antenna, or adjust the beamwidth of its phase array antenna for this process. \item For the left side nodes of $N_{k}$, this NPT is not only used for avoiding BTD conflicts when multiple blockages occur concurrently, but also making these nodes stop transmitting data. As Fig.~\ref{time-diag} shows, after one $T_{s}$ from $t_{0}$, $N_{k}$ has received data from $N_{k-1}$, and it replied ACK appending STS, then $N_{k-1}$ would stop sending data to $N_{k}$ in next time slot and switch its antenna to omni-directional fashion for following possible detection. Meanwhile, $N_{k}$ could confirm that previous original links $e_{k-2,k-1}$ and $e_{k-1,k}$ are unblocked. After 2$T_{s}$, $N_{k-1}$ replied ACK appending STS after receiving data from $N_{k-2}$, then $N_{k-2}$ would stop sending data to $N_{k-1}$ in next time slot and switch its antenna to omni-directional fashion as well. After 3$T_{s}$, $N_{k}$ received the link-unblock sign (LUS) instead of data from $N_{k-1}$, so that it could know that $e_{k-4,k-3}$ and $e_{k-3,k-2}$ are also unobstructed. However, if $N_{k}$ did not receive data or received link-blocked sign (LBS) from $N_{k-1}$ by the end of $t_{0}+T_{s}$ or $t_{0}+3T_{s}$, that means another previous original link is blocked as well, so the previous node should first conduct the BTD process, and $N_{k}$ as the latter node will switch its antenna to the omni-directional fashion for possible coordination. If $N_{k}$ can still receive LUS from $N_{k-1}$ by the end of NPT, it will confirm that all previous original links are unobstructed, and it can continue the BTD process for this blockage on the link $L_{k}$. We can conclude previous original links information by Tab.~\ref{decision_NPT} from $N_{k}$'s perspective (``0" and ``1" denote the link is blocked or unblocked): \end{enumerate} \begin{figure}[htbp] \vspace{-0.2cm} \setlength{\abovecaptionskip}{+0.1cm} \centerline{\includegraphics[width=170mm]{NPTfig2.pdf}} \caption{Timing diagram of $N_{k}$ and its left-side nodes.} \label{time-diag} \end{figure} \vspace{-0.4cm} \begin{table}[htbp] \centering \caption{~~Decision of previous original link from $N_{k}$ during NPT.} \vspace{-0.1cm} \label{decision_NPT} \begin{tabular}{|p{2.0cm}|p{3.0cm}|p{3.0cm}|} \hline \multicolumn{1}{|c|}{Time after $t_{0}$} & \multicolumn{1}{c|}{Receive data/LUS from $N_{k-1}$} & \multicolumn{1}{c|}{Receive $1^{st}$ null/LBS from $N_{k-1}$} \\ \hline \multicolumn{1}{|c|}{$T_{s}$} & \multicolumn{1}{c|}{$e_{k-1,k}$=1 \&\& $e_{k-2,k-1}$=1} & \multicolumn{1}{c|}{$e_{k-1,k}$=0 ~~$\parallel$ $e_{k-2,k-1}$=0} \\ \hline \multicolumn{1}{|c|}{3$T_{s}$} & \multicolumn{1}{c|}{$e_{k-3,k-2}$=1 \&\& $e_{k-4,k-3}$=1} & \multicolumn{1}{c|}{$e_{k-3,k-2}$=0 $\parallel$ $e_{k-4,k-3}$=0} \\ \hline \multicolumn{1}{|c|}{5$T_{s}$} & \multicolumn{1}{c|}{$e_{k-5,k-6}$=1 \&\& $e_{k-6,k-7}$=1} & \multicolumn{1}{c|}{$e_{k-5,k-6}$=0 $\parallel$ $e_{k-6,k-7}$=0} \\ \hline \multicolumn{1}{|c|}{...} & \multicolumn{1}{c|}{...} & \multicolumn{1}{c|}{...} \\ \hline \multicolumn{1}{|c|}{($\left\lceil {k/2} \right\rceil$$\cdot$2-1)$\cdot$$T_{s}$} & \multicolumn{1}{c|}{$e_{1,2}$=1 \&\& $e_{0,1}$=1} & \multicolumn{1}{c|}{$e_{1,2}$=0 $\parallel$ $e_{0,1}$=0} \\ \hline \end{tabular} \end{table} \vspace{-0.0cm} From above, $N_{k}$ will get the link information of all previous node pairs according the reception from $N_{k-1}$ during NPT, and by the end of NPT, all previous nodes of $N_{k}$ will stop transmitting data and switch to the omni-directional antenna for possible detection process. Fig.~\ref{status_NPT} shows the status of nodes in the topology after NPT. \begin{figure}[htbp] \vspace{-0.1cm} \setlength{\abovecaptionskip}{+0.cm} \centerline{\includegraphics[width=160mm]{nodes_status_NPT.pdf}} \caption{The status of nodes after NPT.} \label{status_NPT} \end{figure} \textbf{\textit{Step} 3.} After waiting for the time period NPT, $N_{k}$ starts to send blockage type detection preparation information (BTDP) to $N_{k-1}$ at $t_{0}$$'$ ($t_{0}$$'$=$t_{0}$+NPT), then $N_{k-1}$ will also forward this BTDP to $N_{k-2}$ after the time durance of transmitting BTDP along the original link $T_{s}$$'$ ($T_{s}$$'$$\ll$$T_{s}$), therefore, all left-side nodes of $N_{k}$ would receive BTDP after (\textit{k}-1)$\cdot$$T_{s}$$'$. The format of BTDP is shown in Tab.~\ref{BTDP_format}: \begin{table}[htbp] \centering \caption{~~The format of BTDP.} \vspace{-0.1cm} \label{BTDP_format} \begin{tabular}{|p{2.0cm}|p{3.0cm}|p{3.0cm}|p{3.0cm}|p{3.0cm}|} \hline \multicolumn{1}{|c|}{NID} & \multicolumn{1}{c|}{BLID} & \multicolumn{1}{c|}{STD} & \multicolumn{1}{c|}{DTL} & \multicolumn{1}{c|}{DO} \\ \hline \multicolumn{1}{|c|}{$N_{k}$} & \multicolumn{1}{c|}{\textit{K}} & \multicolumn{1}{c|}{$t_{0}$$'$+2$\cdot$$T_{s}$$'$} & \multicolumn{1}{c|}{$T_{k}$} & \multicolumn{1}{c|}{\{$N_{k}$:$t_{1}$; $N_{k-2}$:$t_{2}$; $N_{k-1}$:$t_{3}$; $N_{k+1}$:$t_{4}$; $N_{k+2}$:$t_{5}$; $N_{k+3}$:$t_{6}$\}, interval:$\bigtriangleup$} \\ \hline \end{tabular} \end{table} \noindent where BID and BLID is the node ID and blocked link number, respectively, STD indicates start time of detection, DTL is the total length of this detection time, and DO represents the detection order of every participant appending respective starting time and interval. Before STD, the adjacent nodes $N_{k-1}$ and $N_{k-2}$ had received the BTDP and were ready for following detection process, and this is the end of the first phase. \subsection{Detection Phase} Blockage type detection process starts at STD. Note that, before sending detection signal (DS), the node will adjust its directional antenna to align the target node's and send BTDP firstly, so that the possible end nodes of substituted paths (i.e. right-part nodes of $N_{k}$) can get the detection information and switch to the direction antenna aligning with the source node's, then reply an ACK. After receiving the ACK from the intended node, the DS will be sent by detector node for checking if this substituted path is available. After replying ACK for DS, every target node would recover the omni-directional antenna for next possible detection. In addition, during this phase, the block-link table \textit{A} is updated and shared by $N_{k}$ and its adjacent nodes, which includes all possible paths $e_{k+i,k+j}$ (-2$\le$$i$$\le$3, $i$+1$\le$$j$$\le$$i$+3) for the nodes in DO and corresponding values (``0"-not checked, ``1"-not blocked, ``inf"-blocked). The detailed steps are listed as follow: \textbf{\textit{Step} 1}: At $t_{1}$, it is the turn of $N_{k}$ to check the available links in its $Sub_{k}$. $N_{k}$ first uses directional antenna to sends BTDP to $N_{k+2}$, and if receiving ACK from target node that has aligned the antenna to $N_{k}$ and is ready for detection, $N_{k}$ will send DS to check this substituted link $e_{k,k+2}$ (shown in Fig.~\ref{detec_proc}). When finishing detecting process with $N_{k+2}$, $N_{k}$ starts to checks the substituted link to $N_{k+3}$ in the same way. After checking every link in $Sub_{k}$, $N_{k}$ initializes the block-link table and sets the corresponding value for its checked links, then multicasts $A_{k}$ to adjacent nodes because each node in $Adj$ uses omni-directional antenna now. After that, $N_{k}$ switches its antenna to an omni-directional fashion for possible detection from other nodes. \begin{figure}[htbp] \vspace{-0.1cm} \setlength{\abovecaptionskip}{+0.cm} \centerline{\includegraphics[width=160mm]{fig4.pdf}} \caption{The detection process between $N_{k}$ and $N_{k+2}$ from $t_{1}$ to $t_{2}$.} \label{detec_proc} \end{figure} \vspace{-0.1cm} \textbf{\textit{Step} 2}: At $t_{2}$ or $t_{3}$, it is detection time for left side nodes $N_{k-2}$ or $N_{k-1}$. Similar to $N_{k}$, $N_{k-2}$ or $N_{k-1}$ will firstly send BTDP to target node such as $N_{k+1}$, and then send DS if receiving ACK and the alignment of their antennas is done. After checking all the substituted paths from its \textit{Sub}, $N_{k-2}$ or $N_{k-1}$ updates and multicasts $A_{k}$, then switches to the omni-directional antenna. \textbf{\textit{Step} 3}: From $t_{4}$ to $t_{6}$+$\bigtriangleup$ (i.e. the end of $N_{k+3}$'s detection time), the right-side nodes $N_{k+1}$, $N_{k+2}$ and $N_{k+3}$ will conduct detection process one by one in their respective time interval. After sending BTDP and receiving ACK, $N_{k+i}$ (1$\le$$i$$\le$3) starts to detect whether they can go to their latter hops, namely sending DS to check the available links from their $Tl$ (TX links set). If $N_{k+i}$ does not have any latter-hop links, it will reset all $e_{k+i-j,k+i}$ (1$\le$$i$$\le$3, 1$\le$$j$$\le$3) as $inf$ in $A_{k}$ for indicating that the possible alternative links into itself are actually not available, for example, if $N_{k+1}$ found that no available links for itself to go to next hops, it would update $e_{k-2,k+1}$ and $e_{k-1,k+1}$ as blocked status even if these two substituted links are available after checking by $N_{k-2}$ and $N_{k-1}$. After that, $N_{k+i}$ multicasts the new $A_{k}$ and switches antenna to omni-directional fashion. \textbf{\textit{Step} 4}: After $t_{6}$+$\bigtriangleup$, $N_{k}$ can get the full block-link table $A_{k}$, which contains all link information of adjacent nodes, and the link that was not checked in $A_{k}$ would be viewed as blocked status due to the possible failed-node cases. Then $N_{k}$ can judge the type of blockage according to Tab. I in [6]. For example, if just $e_{k,k+3}$ or $e_{k-2,k+1}$ in $A_{k}$ is $inf$, the blockage is in \textit{Type} II for $N_{k}$ or $N_{k+1}$; But if just $e_{k-1,k+2}$ in $A_{k}$ is $inf$, it is the \textit{Type} III blockage; When all $e_{k,k+i}$ (2$\le$$i$$\le$3) or $e_{k-i,k+1}$ (1$\le$$i$$\le$2) are $inf$, the blockage is in \textit{Type} IV for $N_{k}$ or $N_{k+1}$; And it is the \textit{Type} I blockage when just $e_{k,k+1}$ is \textit{inf} in $A_{k}$. In other cases, the blockage can be always decomposed into these four types or their combination according to \textit{Theorem} I in [6]. Until now, the second phase of BTD is finished, and the next steps about relay path selection are described detailedly in [6] (Section III). After that, the new substituted path for blockage avoidance is generated by $N_{k}$, eg. selecting $e_{k,k+3}$ instead of $e_{k,k+1}$. Then $N_{k}$ will multicast Path Reconfiguration Message (PRM) to its adjacent nodes, which contains the new selected path (eg. $e_{k,k+3}$), and each of them that received PRM is required to multicast as well in case some adjacent nodes did not get this information due to blockage effect. Once the start and end node of this new substituted path receive PRM, they will use their directional antennas to align with each other. Particularly, if one of nodes in \textit{Adj} did not receive PRM until STD+DTL, that means no available paths can reach this failed node, and it does not need to transmit data but stays in present status until one of paths into itself is available. Note that, if the new substituted path (eg. $e_{k,k+2}$) breaks the original scheduling, i.e. respective transmitting time slot of nodes after this new path, the information about rescheduled time slots is also required to add in PRM and transmit to the nodes after this new substituted path. \begin{figure}[htbp] \vspace{-0.1cm} \setlength{\abovecaptionskip}{+0.cm} \centerline{\includegraphics[width=160mm]{new_path.pdf}} \vspace{+0.15cm} \caption{The process of transmitting PRM from STD+DTL to STT.} \label{trans_PRM} \end{figure} As Fig.~\ref{trans_PRM} shows, at the time \textit{t}=STD+DTL, the start and end nodes of the new path ($N_{k}$ and $N_{k+3}$) will start to transmit PRM to previous node and latter node, respectively. Once receiving PRM, each node in the topology forwards PRM to previous or latter node as well, and switches its antenna to the directional fashion and aligns the TX/RX antenna to its latter/previous node. When the source node receives PRM, it starts transmitting data, and the latter nodes will recover data transmission process once receiving data from previous nodes. In summary, Algorithm 1 (a)-(c) in Appendix shows the pseudocode for the whole process from $t_{1}$ to the time that data transmission has been recovered, which contains respective works of the leader node $N_{k}$ and its adjacent nodes $N_{k-m}$ (1$\le$$m$$\le$2), $N_{k+n}$ (1$\le$$n$$\le$3) during this process. \vspace{+0.5cm} \noindent \textbf{\large References} \vspace{+0.2cm} \noindent [1] J. Du, E. Onaran, et al., ``Gbps user rates using mmWave relayed backhaul with high gain antennas", \textit{IEEE Journal on Selected Areas in Communications}, 2017: 1363-1372. \vspace{+0.1cm} \noindent [2] Q. Hu and D. Blough, ``Optimizing millimeter-wave backhaul networks in roadside environments", \textit{Proc. of IEEE International Conference on Communications}, 2018. \vspace{+0.1cm} \noindent [3] ``Terragraph: Solving the urban bandwidth challenge", Facebook Connectivity, 2019. \vspace{+0.1cm} \noindent [4] A. Dimas, D. Kalogerias, and A. Petropulu, ``Cooperative beamforming with predictive relay selection for urban mmWave communications", \textit{IEEE Access} (2019): 157057-157071. \vspace{+0.1cm} \noindent [5] Y. Liu and D. Blough, ``Analysis of Blockage Effects on Roadside Relay-assisted mmWave Backhaul Networks", \textit{Proc. of IEEE International Conference on Communications}, 2019. \vspace{+0.1cm} \noindent [6] Y. Liu, Q. Hu, and D. Blough, ``Blockage Avoidance in Relay Paths for Roadside mmWave Backhaul Networks", \textit{Proc. of IEEE Symposium on Personal, Indoor, and Mobile Radio Communications}, 2018. \vspace{+0.1cm} \noindent [7] Y. Liu, Q. Hu and D. Blough, ``Joint Link-level and Network-level Reconfiguration for mmWave Backhaul Survivability in Urban Environments", \textit{Proc. of Modeling, Analysis and Simulation of Wireless and Mobile Systems}, ACM, 2019. \vspace{+0.1cm} \noindent [8] Y. Liu, Q. Hu and D. Blough, ``Joint Link-level and Network-level Reconfiguration for Urban mmWave Wireless Backhaul Networks", \textit{Computer Communications}, 2020. \vspace{+0.1cm} \noindent [9] T. Bai, R. Vaze, H. Robert, ``Analysis of blockage effects on urban cellular networks", \textit{IEEE Transactions on Wireless Comm.}, 2014. \vspace{+0.1cm} \noindent [10] T. Bai, H. Robert, ``Coverage and rate analysis for millimeter-wave cellular networks", \textit{IEEE Transactions on Wireless Comm.}, 2015 \newpage \begin{center} \Large \textbf{\textbf{Appendix}} \end{center} \vspace{-0.2cm} \begin{algorithm}[h!] \caption{(a) The status of the leader node ($N_{k}$) for blockage detection process} \begin{algorithmic}[1] \STATE ~~~~~~~~~~~~\textbf{while}($t_{1}$$\le$$t$$<$$t_{2}$) \textbf{do} \STATE ~~~~~~~~~~~~~~~~~~\textbf{for} \textit{link} with \textit{end node i} in $Sub_{k}$ \textbf{do} \STATE ~~~~~~~~~~~~~~~~~~~~~~~AlignAntenna(\textit{i}); // align the antenna to node \textit{i} \STATE ~~~~~~~~~~~~~~~~~~~~~~~BTDPsend(\textit{i}); // send BTDP to node \textit{i} \STATE ~~~~~~~~~~~~~~~~~~~~~~~\textbf{if} (ACK) \textbf{do} //receive an ACK \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~DSsend(\textit{\textit{i}}); // send DS to node \textit{i} \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~$A_{k}$.\textit{init}; // initialize $A_{k}$ \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~\textbf{if}(ACK) \textbf{do} \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~$A_{k}.set(e_{k,i})$ = 1; // update $e_{k,i}$=1 in $A_{k}$ \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~\textbf{else} \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~$A_{k}.set(e_{k,i})$ = 0; \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~\textbf{endif} \STATE ~~~~~~~~~~~~~~~~~~~~~~~\textbf{else} \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~$A_{k}.set(e_{k,i})$ = 0; \STATE ~~~~~~~~~~~~~~~~~~~~~~~\textbf{endif} \STATE ~~~~~~~~~~~~~~~~~~\textbf{endfor} \STATE ~~~~~~~~~~~~~~~~~~mCast($A_{k}$); //multicast $A_{k}$ to its adjacent nodes \STATE ~~~~~~~~~~~~~~~~~~OmniAntenna($N_{k}$); // Switch to omni-directional antenna \STATE ~~~~~~~~~~~~~~~~~~\textbf{wait}; // as a listener \STATE ~~~~~~~~~~~~\textbf{endwhile} \STATE ~~~~~~~~~~~~\textbf{while}($t_{2}$$\le$$t$$<$$t_{6}$+$\bigtriangleup$) \textbf{do} // as a listener \STATE ~~~~~~~~~~~~~~~~~~\textbf{if}(\textit{recv} BTDP $\parallel$ DS from node \textit{j}) \textbf{do} \STATE ~~~~~~~~~~~~~~~~~~~~AlignAntenna(\textit{j}); \STATE ~~~~~~~~~~~~~~~~~~~~ACK(\textit{j}); \STATE ~~~~~~~~~~~~~~~~~~\textbf{endif} \STATE ~~~~~~~~~~~~~~~~~~\textbf{if} (\textit{recv} $A_{k}$) \STATE ~~~~~~~~~~~~~~~~~~~~~$A_{k}.update(A_{k})$; // replace old $A_{k}$ with received $A_{k}$ \STATE ~~~~~~~~~~~~~~~~~~\textbf{endif} \STATE ~~~~~~~~~~~~\textbf{endwhile} \STATE ~~~~~~~~~~~~\textbf{while}($t_{6}$+$\bigtriangleup$$\le$$t$$<$STD+DTL) \textbf{do} // as a blockage type detector \STATE ~~~~~~~~~~~~~~~~~~\textit{Type}=BTD($A_{k}$) // Detect Blockage Type \STATE ~~~~~~~~~~~~~~~~~~Reconf(\textit{Type}); // Reconfigure new path by HTPR algorithm in [6]) \STATE ~~~~~~~~~~~~~~~~~~mCast(PRM); \STATE ~~~~~~~~~~~~~~~~~~\textbf{if} (\textit{NodeIndex} in PRM) \textbf{do} // Prepare to transmission \STATE ~~~~~~~~~~~~~~~~~~~~~~DirectAntenna($N_{k}$); // Switch to directional antenna \STATE ~~~~~~~~~~~~~~~~~~~~~~AlignAntenna(\textit{PreNode} and \textit{LatterNode} in PRM); \STATE ~~~~~~~~~~~~~~~~~~\textbf{endif} \STATE ~~~~~~~~~~~~~~~~~~\textbf{wait}; // idle time if process has been finished \STATE ~~~~~~~~~~~~\textbf{endwhile} \end{algorithmic} \end{algorithm} \begin{algorithm}[h!] \setcounter{algorithm}{0} \caption{(b) The status of $N_{k-m}$ (1$\le$$m$$\le$2) for blockage detection process} \begin{algorithmic}[1] \STATE ~~~~~~~~~~~~\textbf{while}($t_{4-m}$$\le$$t$$<$$t_{5-m}$) \textbf{do} \STATE ~~~~~~~~~~~~~~~~~~\textbf{for} \textit{link} with \textit{end node i} in $Sub_{k-m}$ \textbf{do} \STATE ~~~~~~~~~~~~~~~~~~~~~~~AlignAntenna(\textit{i}); // align the antenna to node \textit{i} \STATE ~~~~~~~~~~~~~~~~~~~~~~~BTDPsend(\textit{i}); // send BTDP to node \textit{i} \STATE ~~~~~~~~~~~~~~~~~~~~~~~\textbf{if} (ACK) \textbf{do} //receive an ACK \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~DSsend(\textit{\textit{i}}); // send DS to node \textit{i} \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~\textbf{if}(ACK) \textbf{do} \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~$A_{k}.set(e_{k,i})$ = 1; // update $e_{k,i}$=1 in $A_{k}$ \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~\textbf{else} \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~$A_{k}.set(e_{k,i})$ = 0; \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~\textbf{endif} \STATE ~~~~~~~~~~~~~~~~~~~~~~~\textbf{else} \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~$A_{k}.set(e_{k,i})$ = 0; \STATE ~~~~~~~~~~~~~~~~~~~~~~~\textbf{endif} \STATE ~~~~~~~~~~~~~~~~~~\textbf{endfor} \STATE ~~~~~~~~~~~~~~~~~~mCast($A_{k}$); //multicast $A_{k}$ to its adjacent nodes \STATE ~~~~~~~~~~~~~~~~~~OmniAntenna($N_{k-m}$); // Switch to omni-directional antenna \STATE ~~~~~~~~~~~~~~~~~~\textbf{wait}; // as a listener \STATE ~~~~~~~~~~~~\textbf{endwhile} \STATE ~~~~~~~~~~~~\textbf{while}($t_{6}$+$\bigtriangleup$$\le$$t$$<$STD+DTL) \textbf{do} // as a broadcaster \STATE ~~~~~~~~~~~~~~~~~~\textbf{if} (\textit{recv} PRM) \textbf{do} \STATE ~~~~~~~~~~~~~~~~~~~~~mCast(PRM); \STATE ~~~~~~~~~~~~~~~~~~~~~\textbf{if} (\textit{k-m} in PRM) \textbf{do} // Prepare to transmission \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~DirectAntenna($N_{k-m}$); // Switch to directional antenna \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~AlignAntenna(\textit{PreNode} and \textit{LatterNode} in PRM); \STATE ~~~~~~~~~~~~~~~~~~~~~\textbf{endif} \STATE ~~~~~~~~~~~~~~~~~~\textbf{endif} \STATE ~~~~~~~~~~~~~~~~~~\textbf{wait}; // idle time if process has been finished \STATE ~~~~~~~~~~~~\textbf{endwhile} \STATE ~~~~~~~~~~~~\textbf{while}(other time) \textbf{do} \STATE ~~~~~~~~~~~~~~~~~~\textbf{if} (\textit{recv} $A_{k}$) \textbf{do} \STATE ~~~~~~~~~~~~~~~~~~~~~$A_{k}.update(A_{k})$; \STATE ~~~~~~~~~~~~~~~~~~\textbf{endif} \STATE ~~~~~~~~~~~~\textbf{endwhile} \end{algorithmic} \end{algorithm} \begin{algorithm}[h!] \setcounter{algorithm}{0} \caption{(c) The status of $N_{k+n}$ (1$\le$$n$$\le$3) for blockage detection process} \begin{algorithmic}[1] \STATE ~~~~~~~~~~~~\textbf{while}($t_{n+3}$$\le$$t$$<$$t_{n+4}$) \textbf{do} \STATE ~~~~~~~~~~~~~~~~~~\textbf{for} \textit{link} with \textit{end node i} in $Tl_{k+n}$ \textbf{do} ~~// check all TX links \STATE ~~~~~~~~~~~~~~~~~~~~~~~AlignAntenna(\textit{i}); // align the antenna to node \textit{i} \STATE ~~~~~~~~~~~~~~~~~~~~~~~BTDPsend(\textit{i}); // send BTDP to node \textit{i} \STATE ~~~~~~~~~~~~~~~~~~~~~~~\textbf{if} (ACK) \textbf{do} //receive an ACK \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~DSsend(\textit{\textit{i}}); // send DS to node \textit{i} \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~\textbf{if}(ACK) \textbf{do} \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~$A_{k}.set(e_{k,i})$ = 1; // update $e_{k,i}$=1 in $A_{k}$ \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~\textbf{else} \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~$A_{k}.set(e_{k,i})$ = 0; \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~\textbf{endif} \STATE ~~~~~~~~~~~~~~~~~~~~~~~\textbf{else} \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~$A_{k}.set(e_{k,i})$ = 0; \STATE ~~~~~~~~~~~~~~~~~~~~~~~\textbf{endif} \STATE ~~~~~~~~~~~~~~~~~~\textbf{endfor} \STATE ~~~~~~~~~~~~~~~~~~\textbf{if} (all links in $Tl_{k+n}$ equal to zero) \textbf{do} // reset values of unavailable links in $A_{k}$ \STATE ~~~~~~~~~~~~~~~~~~~~~\textbf{for} \textit{j}=1 to 3 \textbf{do} \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~$A_{k}.set(e_{k+n-j,k+n})$ = 0; \STATE ~~~~~~~~~~~~~~~~~~~~~\textbf{endfor} \STATE ~~~~~~~~~~~~~~~~~~\textbf{endif} \STATE ~~~~~~~~~~~~~~~~~~mCast($A_{k}$); //multicast $A_{k}$ to its adjacent nodes \STATE ~~~~~~~~~~~~~~~~~~OmniAntenna($N_{k+n}$); // Switch to omni-directional antenna \STATE ~~~~~~~~~~~~~~~~~~\textbf{wait}; // as a listener \STATE ~~~~~~~~~~~~\textbf{endwhile} \STATE ~~~~~~~~~~~~\textbf{while}($t_{1}$$\le$$t$$<$$t_{k+n}$ $\parallel$ $t_{k+n+1}$$\le$$t$$<$$t_{6}$+$\bigtriangleup$) // as a listener \STATE ~~~~~~~~~~~~~~~~~~\textbf{if} (\textit{recv} BTDP $\parallel$ DS from node \textit{a}) \textbf{do} \STATE ~~~~~~~~~~~~~~~~~~~~~~AlignAntenna(\textit{a}); \STATE ~~~~~~~~~~~~~~~~~~~~~~ACK(\textit{a}); \STATE ~~~~~~~~~~~~~~~~~~\textbf{endif} \STATE ~~~~~~~~~~~~~~~~~~\textbf{if} (\textit{recv} $A_{k}$) \textbf{do} \STATE ~~~~~~~~~~~~~~~~~~~~~$A_{k}.update(A_{k})$; \STATE ~~~~~~~~~~~~~~~~~~\textbf{endif} \STATE ~~~~~~~~~~~~\textbf{endwhile} \STATE ~~~~~~~~~~~~\textbf{while}($t_{6}$+$\bigtriangleup$$\le$$t$$<$STD+DTL) \textbf{do} // as a broadcaster \STATE ~~~~~~~~~~~~~~~~~~\textbf{if} (\textit{recv} PRM) \textbf{do} \STATE ~~~~~~~~~~~~~~~~~~~~~mCast(PRM); \STATE ~~~~~~~~~~~~~~~~~~~~~\textbf{if} (\textit{k}+\textit{n} in PRM) \textbf{do} // Prepare to transmission \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~DirectAntenna($N_{k+n}$); // Switch to directional antenna \STATE ~~~~~~~~~~~~~~~~~~~~~~~~~AlignAntenna(\textit{PreNode} and \textit{LatterNode} in PRM); \STATE ~~~~~~~~~~~~~~~~~~~~~\textbf{endif} \STATE ~~~~~~~~~~~~~~~~~~\textbf{endif} \STATE ~~~~~~~~~~~~~~~~~~\textbf{wait}; // idle time if process has been finished \STATE ~~~~~~~~~~~~\textbf{endwhile} \end{algorithmic} \end{algorithm} \end{document}
{'timestamp': '2020-10-27T01:17:20', 'yymm': '2010', 'arxiv_id': '2010.08430', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08430'}
arxiv
\section{Introduction} \begin{sidewaysfigure} \includegraphics[width=\columnwidth]{figures/main_figure.PNG} \label{fig:main_figure} \caption{Column 1 are the original figures. Column 2 are the figures with top20 target-object-ACE units ablated. Column 3 represents the ACE-distribution of target-object-related units, where chair(Type-1 entangled) has flat ACE-distribution and is difficult to remove, while painting(Type-2 entangled) and light(disentangled) has concentrated ACE-distribution thus are easy to remove. Column 4 shows the change of ratio and rank of ACE for different objects after ablate top20 target-object-ACE units. The increase of ACE for some objects after ablating painting-ACE units is so large that they emerge after paintings are removed. Column 5 presents how ablated figure is changed by adding the top-20 target-object-ACE units. Where red frames and blank mean disappearance while yellow frames mean appearance. Column 6 presents how original figure is changed by ablating the top-20 ACE units back when pixel normalization coefficient is fixed to before-ablation level. Column 7, which is the difference between column 5 and column 6, presents the effect of pixel normalization: preservation and substitution.} \end{sidewaysfigure} Understanding the entanglement stands on the stage center of the deep learning research because entanglement is deeply rooted in the complex computational process of neural network models \citep{karpathy2015visualizing,kulkarni2015deep,higgins2016beta} while indicating non-predicable biases. Therefore, developing an output-disentangle neural network model has attracted a significant amount of attention from deep-learning society. However, the absence of analytical understanding about the mechanism causing output entanglement prevents us from discussing whether and when a neural network’s architecture can systematically avoid relative biases. On the other hand, it is a challenge to examine the mechanism causing GAN \citep{goodfellow2014generative,radford2015unsupervised,zhang2019self,chen2016infogan} entanglement. GAN’s deep neural network structure obstructs the progress of theoretical analyses, while the experimental approach proposed by the most recent studies \citep{zhou2018interpretable,selvaraju2017grad,simonyan2013deep,olah2018building,schwab2019cxplain} is incapable of enlightening GAN’s inside structure. Current experimental approaches in the literature are designed for generating counterfactual scenarios \citep{imbens2015causal,pearl2009causality} with and without the input changes \citep{bau2017network,represent}. In contrast, understanding GAN’s internal mechanism causing entanglement asks for an experimental design that can generate counterfactual scenarios with and without GAN’s functioning. Thus, a new experimental design is necessary for studying the mechanism of GAN entanglement. We in this research develop a difference-in-difference (DID) \citep{2018Dif,goodman2018difference,abadie2005semiparametric,athey2006identification} experiment to analyze the entanglement mechanism originated in the pixel-normalization operation of the Progressive-growing generative adversarial network (PG-GAN) \citep{karras2017progressive}. We select to research PG-GAN because of two reasons. First, PG-GAN is an approach of generating a high-resolution figure including various objects that can entangle with each other. Second, the recent progress in literature has well prepared for applying DID to study PG-GAN’s entanglement. (\cite{besserve2018counterfactuals}) rigorously defined the concept of operation-based object disentanglement in a figure generated by GAN. (\cite{bau2018gan}) has developed an approach to clarify the causal ties between input units and output objects. Based on these two studies, we design a DID experiment to examine how pixel normalization causes object entanglement during a unit-ablating transformation. Our results conclude that pixel normalization causes entanglement by in-painting the area belonging to ablated objects. Once the in-painted objects are different from those surrounding the in-painted area, an entanglement effect occurs. Entanglement caused by pixel normalization can be further clustered according to the types of in-painted objects. If the in-painted objects are from the same types as the ablated one, the entanglement effect deactivates the ablating transformation. We refer to this type of entanglement as the “deactivating-ablation entanglement" or Type-1 entanglement. Otherwise, the entanglement effect causes unwanted objects’ appearance associated with ablating, referred to as the “mis-ablation entanglement” or Type-2 entanglement by this research. The difference-in-difference experiment also clarifies that the characteristics of unit-object causal relation determine the types of in-painted objects. We summarize our three contributions in this research: \begin{itemize} \item We explain the internal mechanism of how pixel normalization causes object entanglement under ablating transformation. Because of our insights into the black-box of PG-GAN, we also clarify the necessary conditions when objects are disentangled. \item We clarify the mechanism how unit-object causal relation determine whether and how disentanglement occurs. \item We propose an experimental approach to analyze PG-GAN’s functioning mechanism based on the DID counterfactual framework, which can be generalized for broader deep neural network studies. Designing appropriate DID experiments to examine the functioning mechanism of neural network deserves further discussion. \end{itemize} Our understanding about entanglement provide a new perspective on entanglement research, which can enable of a sequence further research. For instance, it is possible to design an ablation method rather than modifying PG-GAN to avoid entanglement according to the understanding about how pixel normalization causes entanglement over objects. The understanding the deactivating-ablation entanglement also allows us to examine the robustness of objects in a figure once some input units are unexpected losses. \section{Preliminary: PG-GAN and Disentanglement} \label{sec:pg-gan} \begin{wrapfigure}{r}{5cm} \centering \includegraphics[width=2in]{figures/progan_block.PNG} \caption{The architecture of a layer in the PG-GAN.} \label{fig:progan_architecture} \end{wrapfigure} In this work, we are studying what the disentanglement properties are in the ablation transformation of PG-GAN~(\cite{karras2017progressive}). PG-GAN is good at producing versatile objects with details while preserving the model efficiency. It adopts a progressive layer-growing strategy for fine-grained details and pixel normalization for training robustness. Figure \ref{fig:progan_architecture} shows the architecture of a layer in PG-GAN which includes several different functions. Given a low-resolution input from upstream layers, we do upsampling, convolutions~(\cite{krizhevsky2012imagenet}), and weighted residual connection~\cite{he2016deep}. Finally, a pixel normalization~\cite{kurach2019large} which is a type of avoids the competing gradient magnitudes spiraling out of control is imposed on the output as \begin{gather} b_{p,q} = \frac{a_{p,q}}{\beta_{p,q}} = \frac{a_{p,q}}{\gamma(a_{p,q})} = \frac{a_{p,q}}{\sqrt{\frac{1}{M}\sum_{j=0}^{M-1}(a_{p,q}^j)^2+\epsilon}} \label{eq:normalization} \end{gather} where $M$ is the number of channels, $a_{p,q}$ and $b_{p,q}$ are the original and normalized feature vector at pixel $(p,q)$ and $\epsilon=10^{-8}$. And $\beta_{p,q}=a_{p,q}/\gamma(a_{p,q})$ refers to normalizing coefficients which implements the pixel normalization. The progressive growing strategy gradually appends new layers to the network, organizing layers into different granularity levels. Given a random input $\boldsymbol{z}$ and the PG-GAN generator $G=h\cdot f$, we have the generated image $\boldsymbol{x}=G(\boldsymbol{z})$ and $\boldsymbol{u}=f(\boldsymbol{z})$ is a set of units (i.e., channels in convolution operations) in a given middle layer which are closely related to classes of objects respectively. Literature shows that while units in the middle layers (layer4 to layer7 in PG-GAN) relate to object-level concepts (e.g. chairs, painting), they in layers ahead relate to background concepts (e.g. ceiling, sky) and in latter layers focus on abstract concepts (e.g. color, texture). In this work, to enable detailed analysis over objects' disentanglement properties, we constrain our training and following experiments of PG-GAN on the LSUN~(\cite{yu2015lsun}) conference room dataset. PG-GAN's ability to yield various fine-grained objects is critical for analyzing disentanglement between different objects. In the literature, researchers conduct a wide range of experiments to primarily show that PG-GAN exhibits both disentangled and entangled properties in different scenarios. Especially in~(\cite{bau2018gan}), the authors present a series of qualitative unit-level experiments to show that in the unit-ablation transformation, while in some cases the PG-GAN shows disentanglement (such as ablating paintings on the wall), in other cases, entangled phenomena are observed, mainly categorized into two types including \textit{unsuppressible} and \textit{emerged} objects after ablation. In this work, we try to provide deeper thoughts about the disentanglement caused by function-level and mutual relationships between objects and eventually explain the above unexpected entanglement. \section{Problem Definition} \label{sec:problem} Intuitively, the disentanglement of deep models denotes the scenario that a transformation operating on a local component does not disturb other components in the same figure. A rigorous definition of transformation disentanglement is proposed by~\cite{besserve2018counterfactuals}, which is presented as below: \begin{citeDef}[Counterfactual-based Disentanglement] Given a transformation $T$ on the data manifold, it is disentangled on a generative model $G$ with respect to a subset $\mathcal{E}$ of the generated outcome, if there is a transformation $T^\prime$ acting on internal representation units such that for any endogenous value $\boldsymbol{u}$ \begin{gather} \boldsymbol{x}^\prime=T(G(\boldsymbol{u}))=G(T^\prime(\boldsymbol{u})), \end{gather} where $T^\prime$ only affects variables indexed by $\mathcal{E}$. \end{citeDef} This definition points out that a transformation $T$ is disentangled if and only if $T$'s effect corresponds to an internal transformation $T^\prime(\boldsymbol{u})$ which only causes changes on $\mathcal{E}$, a specific outcome subset. In this research, we specify $T$ in the above definition as the unit-ablation transformation, which is denoted by $T_a$. Therefore, $T_a$ denotes the transformation directly ablating objects, while $T^\prime_a$ is the transformation ablating input units. We further define $\mathcal{E}$ to the area of a specific object class $\mathcal{E}_c$ on the generated image. We also notice that $T_a$ is disentangled if and only if there is $T^\prime_a$ disentangled. Therefore, in the rest of the paper, we use ``disentanglement'' for short to represent the disentangled property of the ablation transformation $T^\prime_a$. The above definition allows us to examine whether a type of objects are disentangled under the unit-ablation transformation on PG-GAN generated figures. For example, given a GAN $G$, if the $T_a$ on chair objects area $\mathcal{E}_c$ is disentangled, we expect to find a internal transformation $T^\prime_a$ acting on units $\boldsymbol{u}$ leading to only and sufficient disappearance of chair objects in the generated image. Therefore, we have the following definition of the disentanglement of a class of objectives. \begin{myDef}[The Disentanglement of a Set of Objects] A class of objectives $\mathcal{C}$ is disentangled under the ablation transformation $T_a$, if the unit-ablation transformation $T^\prime_a$ acting on $\boldsymbol{u}$ satisfies \begin{gather} \boldsymbol{x}^\prime=T_a(G(\boldsymbol{u}))=G(T^\prime_a(\boldsymbol{u})), \end{gather} where $T_a^\prime$ only affects variables indexed by $\mathcal{C}$. \end{myDef} The above definition also suggest that the disentanglement of an object is influenced by several factors, among which the features of units $\boldsymbol{u}$ have the most direct and apparent effect because $T^\prime_a$ directly acts on $\boldsymbol{u}$. To quantitatively identify units $\boldsymbol{u}$'s impact on the appearance of a specific class of objects, following~(\cite{bau2018gan}) and \citep{holland1988causal}, we leverage a standard causal metric---the average causal effect (ACE) to reflect a unit's effect on disentanglement. \begin{myDef}[Unit's Effect on Disentanglement] For any possible $\boldsymbol{z}$ and $\boldsymbol{x}=G(\boldsymbol{z})$, the ACE of unit set $U\in\boldsymbol{u}$ on object class $c$ is defined as \begin{gather} \delta_{U\rightarrow c}=\mathbb{E}_{\boldsymbol{z}}[\boldsymbol{S}_c(\boldsymbol{x}_i)]-\mathbb{E}_{\boldsymbol{z}}[\boldsymbol{S}_c(\boldsymbol{x}_a)] \label{equ:gan-dissection} \end{gather} where $\boldsymbol{x}_a=h(T^\prime_a(\boldsymbol{u}_{U}))=f(0,\boldsymbol{u}_{\overline{U}})$ is the image with $U$ ablated at $P$ and $\boldsymbol{x}_i=f(k,\boldsymbol{u}_{\overline{U}})$ is the image with $U$ inserted at $P$. \end{myDef} Note that the $\delta_{U\rightarrow c}$ is the expectation over all the possible $\boldsymbol{z}$, which reflects the average effect of units on the object class $c$ in any scenarios. In Figure \ref{fig:problem}, we exhibit the three types of disentangled and entangled phenomena caused by ablating units $U$ with top-$\delta_{U\rightarrow c}$. The first sample shows a fully disentangled behavior (as the paintings on the wall disappear), but the second and third exhibit entangled phenomena. In the second one, although top-$\delta$ chair units are ablated, the chair objects are \textit{not ablated} in the outcome, with only sizes shrinking a little bit. In the third one, while paintings are removed, new objects such as doors unexpectedly \textit{emerge}. Literature has suggested that in the internal components of neural networks may have roles in causing entanglement \citep{besserve2018intrinsic,chen2018isolating}. In this work, we propose to study the pixel normalization function's effect on disentanglement $T^\prime_a$ via experimental designs. We define it as follows: \begin{myDef}[Pixel Normalization's Effect on Disentanglement] Given an input $\boldsymbol{z}$, let $\boldsymbol{u}^\prime=T^\prime_a(\boldsymbol{u})$ denote ablated units, $\varphi(\beta,\boldsymbol{u})$ denote pixel normalization function's effect, and $\theta(\boldsymbol{u})$ denote other functions' effect, there is \begin{gather} Y(\beta,\boldsymbol{u})=\varphi(\beta,\boldsymbol{u}) + \theta(\boldsymbol{u}) \label{equ:Y} \end{gather} where $Y$ refers to the functions and units' joint effect on $\boldsymbol{x}$. Consequently, the effect of pixel normalization given the ablation transformation $T^\prime_a$ could be represented by \begin{gather} \Delta Y_{\beta\to\beta^\prime} \text{,\ where\ }\beta^\prime=\gamma(\boldsymbol{u}^\prime)=\gamma(T^\prime_a(\boldsymbol{u}))=T^\prime_a(\gamma(\boldsymbol{u}))=T^\prime_a(\beta) \end{gather} \end{myDef} Since the pixel normalization acts on the units, $\varphi$'s behavior is probably influenced by the aggregating properties of the input $\boldsymbol{u}$ and corresponding $\delta_{\boldsymbol{u}\rightarrow c}$. More specifically, \begin{myDef}[Distribution and Ranking (Informal)] With a set of object classes $\mathcal{C}$ and the set of units $\boldsymbol{u}$, we informally define: 1) \textbf{distribution of} $\delta_{u\rightarrow c}$: given an object class $c\in\mathcal{C}$ and for every unit $u_i\in\boldsymbol{u}$, the density distribution of $\delta_{u_i\rightarrow c}$ 2) \textbf{ranking of} $\delta_{u\rightarrow c}$: for every $c\in\mathcal{C}$, the ranking sequence of their $\sum_i \delta_{u_i\rightarrow c}$ \end{myDef} \hide{ \begin{enumerate} \item All units causally contribute to more than one object class respectively. Some units have a dominant impact on only one object class, and others could have strong contributions to multiple classes.\xiao{yu: incorrect arrangement} \item Given a class of objects to remove, it is usually sufficient to make it by ablating units with dominant influence. But we also observe entangled phenomena including \textit{unsuppressible} (minimal effect on $\mathcal{E}$) and \textit{emerged} (significant effect beyond $\mathcal{E}$) objects after ablation. \end{enumerate} \xiao{from definition induces why this is Figure 2 disentangled. no (a) (b), leave (c)(d)(e)} } \begin{figure}[t] \centering \begin{subfigure}[t]{1.8in} \includegraphics[width=1.8in]{figures/48-ablate-light.PNG} \caption{ablate light units} \end{subfigure} \begin{subfigure}[t]{1.8in} \includegraphics[width=1.8in]{figures/66-ablate-chair.PNG} \caption{ablate chair units} \end{subfigure} \begin{subfigure}[t]{1.8in} \includegraphics[width=1.8in]{figures/83-ablate_painting.PNG} \caption{ablate painting units} \end{subfigure} \caption{(a) Disentangled case: ablating top-20 light-ACE units eliminates the light objects on ceiling. (b) Deactivating-ablation entanglement: ablating chair-ACE units cannot eliminate the chairs. (c) Mis-ablation entanglement/emerge case: ablating top-20 painting-ACE units leads to both elimination of paintings on the wall and unexpected emergence of doors and windows} \label{fig:problem} \end{figure} \hide{ In Section \ref{sec:pg-gan}, we introduce the architecture and inner functions of PG-GAN including convolutions, residual connections, pixel normalization and etc. It is thus important to clarify their potential functionalities on the disentanglement. We propose to start with a simple function with no trainable parameters---the pixel normalization $N$---and discuss how we can systematically design experiments to investigate its role in the disentanglement problem under the transformation of ablation $T^\prime_a$. First, the counterfactual experimental design for the pixel normalization's effect on the disentanglement should be different from that for unit $\bold$. For a unit, the ablation of unit itself is sufficient for constructing the counterfactual as shown in Equation \ref{equ:gan-dissection}. For a function, however, besides the removal of the function itself, at the same time we also have to ablate the units as the definition of disentanglement requires, which leads to two treatment variables in the experiments. In this situation, we need Difference-in-Difference (DID) experiment design to ensure that we are computing the real effect of the function. Second, further experiment should be made between different scenarios based on first-step DID experiments. In the first-step DID experiment, we are only answering how pixel normalization functioning, but not why it leads to different results between entanglement and disentanglement that both being influenced. We will show that disentanglement happens, when the pixel normalization interacts with different distributions inner a class of units and rankings across different classes. To sum up, in this work, we concentrate on the disentanglement under a specific type of transformation---ablation---to cast some light on the disentanglement properties of GAN black-box. We want to ask, besides units, how the function we use in the model have an impact on the disentanglement. More specifically, we want to identify the \textit{pixel normalization}'s functionality and how it interacts with different units distribution and ranking to form disentanglement in PG-GAN. } \section{Method: Difference-in-Difference experiment design} To bridge the pixel normalization to disentanglement, in Section \ref{sec:problem} we propose to identify $\Delta Y_{\beta\to\beta^\prime}$ which represents pixel normalization's universal effect, and then to explore how the properties of $\boldsymbol{u}$ will influence $\Delta Y_{\beta\to\beta^\prime}$'s form of expression. For the first problem, we introduce a counterfactual-based Difference-in-Difference (DID) \citep{2018Dif} experiment framework; for the second, based on the different-in-different approach, we compare $\Delta Y_{\beta\to\beta^\prime}$ under four scenarios with different unit distributions and rankings. \subsection{Counterfactual DID experiments for identifying function's effect} \label{sec:beta-design} We argue that the pixel normalization's transformation $\beta\rightarrow\beta^\prime$ has a significant impact on disentanglement of the $\boldsymbol{u}\rightarrow\boldsymbol{u}^\prime$. The intuition is that, from Equation \ref{eq:normalization}, we know that $\beta_{p,q}$ will increase when there are units ablated (i.e. $a^j_{p,q}=0$), leading to augmentations on un-ablated units. In previous study, researcher show the object-level generation of PG-GAN is determined by the 4-layer to 13-layer in PG-GAN. Therefore, in order to investigate how the $\beta\rightarrow\beta^\prime$ affects the transformation $\boldsymbol{u}\rightarrow\boldsymbol{u}^\prime$, we propose to control the $\beta$ in these 10 layers for constructing counterfactuals. Naturally, we have a factual experiment $Y(\beta,\boldsymbol{u})$ as shown in Equation \ref{eq:exp_design}. To show $\beta$'s effect on the transformation $\boldsymbol{u}\rightarrow\boldsymbol{u}^\prime$, we construct a counterfactual case where $\boldsymbol{u}\rightarrow\boldsymbol{u}^\prime$ and $\beta$ remains controlled. Technically speaking, this control is performed by enforcing normalizing coefficients $\beta$ in 4-layer to 13-layer to be the same as the original situation with $\boldsymbol{u}$. For another factual experiment $Y(\beta^\prime,\boldsymbol{u}^\prime)$, we conduct the same control as enforcing coefficients to be the same to reveal $\beta^\prime$'s impact on $\boldsymbol{u}\rightarrow\boldsymbol{u}^\prime$. As a result, we construct two pairs of counterfactual experiments for difference in difference analysis as follow: \begin{gather}\label{eq:exp_design} \text{Original case:}\qquad\qquad\qquad\qquad\qquad\qquad\qquad\ \ Y(\beta,\boldsymbol{u})=\varphi(\beta,\boldsymbol{u}) + \theta(\boldsymbol{u}) \\ \text{Ablated~} \boldsymbol{u}^\prime \text{~and~} \beta\text{:}\qquad\qquad\qquad\qquad\qquad\quad\quad\ Y(\beta,\boldsymbol{u}^\prime)=\varphi(\beta,\boldsymbol{u}^\prime) + \theta(\boldsymbol{u}^\prime) \notag\\ \text{Ablated~} \boldsymbol{u}^\prime \text{~and~} \beta^\prime \text{:\qquad\qquad\qquad\qquad\qquad\quad\ \ } Y(\beta^\prime,\boldsymbol{u}^\prime)=\varphi(\beta^\prime,\boldsymbol{u}^\prime) + \theta(\boldsymbol{u}^\prime) \notag\\ \boldsymbol{u} \text{~and ablated~} \beta^\prime\text{:}\qquad\qquad\qquad\qquad\qquad\qquad\quad Y(\beta^\prime,\boldsymbol{u})=\varphi(\beta^\prime,\boldsymbol{u}) + \theta(\boldsymbol{u}) \notag \end{gather} and therefore the real effect could be computed as: \begin{align} \Delta Y_{\beta\to\beta^\prime} &=[Y(\beta^\prime,\boldsymbol{u}^\prime)-Y(\beta^\prime,\boldsymbol{u})]-[Y(\beta,\boldsymbol{u}^\prime)-Y(\beta,\boldsymbol{u})]\\ &=[\varphi(\beta^\prime,\boldsymbol{u}^\prime)-\varphi(\beta^\prime,\boldsymbol{u})] -[\varphi(\beta,\boldsymbol{u}^\prime)-\varphi(\beta,\boldsymbol{u})]+ [\theta(\boldsymbol{u})-\theta(\boldsymbol{u})] + [\theta(\boldsymbol{u}^\prime)-\theta(\boldsymbol{u}^\prime)]\notag\\ &=[\varphi(\beta,\boldsymbol{u}^\prime)-\varphi(\beta,\boldsymbol{u})]-[\varphi(\beta^\prime,\boldsymbol{u}^\prime)-\varphi(\beta^\prime,\boldsymbol{u})]\notag \end{align} which indicates the real effect of pixel normalization effect function $\varphi$ imposed on the image. Noted that this effect is also unbiased because the unrelated effect $\theta$ has been offset in the difference. \subsection{Scenario-conditioned experiments for unit distribution and ranking} Difference-in-Difference experiments enable us to systematically analyze pixel normalization's effects on disentanglement of any given objects on given images. But we may still not explain the unexpected evidences in Figure \ref{fig:problem}, that with the same application of pixel normalization, different object classes, or the same object class in different scenarios show significant entangled properties. Therefore, in this step of experiment, we design to compare the DID experiment results conditioned on its distribution of $\delta_{u\rightarrow c}$ and ranking of $\delta_{u\rightarrow c}$. More specifically, we categorized them into $2\times2=4$ types: \begin{enumerate} \item distribution of $\delta_{u\rightarrow c}$: 1) units symmetrically locate in both high-ACE and low-ACE area, 2) units concentrate in high-ACE area. \item ranking of $\delta_{u\rightarrow c}$: 1) the top ranking object's ACE overwhelms the second one, 2) the top ranking object marginally surpasses the second one. \end{enumerate} Although theoretically we have 4 scenarios, in fact we will show that given the symmetrical distribution condition, the ranking of $\delta_{u\rightarrow c}$ does not take effect, leaving only 3 meaningful cases. \hide{In the Section \ref{sec:beta-design}, we provide a systematic approach for computing a function's causal effect on the generated output. Ideally, $\varphi$ has the same functional effect on all object classes. However, this is given the homogeneous condition that the unit distribution is the same for all target object classes. In fact, our preliminary experiments exhibit that there are at least two typical types of unit distribution, or in other words, the distribution of units $U$ could be \textit{heterogeneous} across different object classes and therefore influence the form of normalizing coefficient $\beta=f(U)$. As a result, although the pixel normalization function $\varphi$ has only one essence, its behavior could be drastically different in accordance with different unit distributions. For notations, let $\mathcal{F}_N(U)$ denote the units distribution after pixel normalization. Notice that this is a ``normalized'' distribution because the pixel normalization has already influenced the distribution as early as in the training. Given two different units sets $U_1$ and $U_2$, on the basis of Section \ref{sec:beta-design}, the third treatment we are considering is exactly the $\mathcal{F}_N(U)$. Formally speaking, in this task we are studying the difference of difference of difference \beq{ \Delta Y_{\varphi|\mathcal{F}_N(U_1)} - \Delta Y_{\varphi|\mathcal{F}_N(U_2)} } However, since the distribution $\mathcal{F}_N(U)$ is not differentiable, we can only qualitatively research into its related properties. Detailed discussion see Section \ref{sec:ud-result} As we have shown in Section \ref{sec:pg-gan}, except for the pixel normalization, many other functions may have potential relation with the disentangle properties. To study the pure effects of the pixel normalization first asks us to control other functions in this black box as usual. Moreover, contrary to units, the modification of function itself for effect identification makes no sense; instead, the effect of a function is actually reflected by the change of outcomes when inputs vary. Therefore, for experiment design to unveil the effect of the pixel normalization, it must have at least two treatments to control, making it necessarily a DID experiment design. In the case of pixel normalization, recall Equation \ref{eq:normalization}, it is the normalizing coefficients $\beta$ that implements the reweighing. Interestingly, $\beta$ is jointly determined by the use of normalization $N$ and input units $U$, and a local transformation $T^\prime$ imposed on $U$ could also change the $\beta$. For a formal description of this problem, let $U$ be the input units, $Y$ be the area of a target object class in the generated outcome, effect function $\varphi(\beta,U)$ refers to the causal effect that pixel normalization has on the outcome and $\theta(U)$ refers to unrelated effect caused by other functions. Theoretically we can have the equation } \section{Preservation: Entanglement on unsuppressbile objects} In this section, we will discuss the first type of entangled phenomenon: deactivating-ablation entanglement. Compared to \xiao{} in Figure , in Figure \ref{ablate_chair}, ablating units related to chairs with top ACE effects can not remove or eliminate chairs, only causing them to reduce sizes and density, or change color. In literature, researchers conduct a number of experiments and qualitatively exhibit that the ease of removing a class of objects varies with the scene type, such as windows in bedroom are as hard as chairs in conference room to be removed~(\cite{bau2018gan}), which implies that GAN has learned some scene-specific knowledge. Our quantitative experiments also support the conclusion (see Figure \ref{fig:segarea_ablate20_variousobjects}). Given an object class (such as chair or painting), we rank units by its causal contributions from strong to weak, and sequentially ablate them to observe a decline in area of the object class. As the diagram demonstrated, there is an apparent contrast between chair and others, showing the existence of a strong entanglement between chair objects and the environment. However, this entanglement is substantially diminished when we fix the normalizing coefficients $\beta$ as shown in Figure \ref{fig:segarea_ablate20_fix}, in which the pixel normalization $N$ should be playing a critical role. To some extend, this difference could be explained by the distribution of units according to ACE (Figure \ref{fig:ace-distribution}), where units of removable class almost locate at high-ACE but unsuppressible ones lie at low-ACE. \section{Result} \subsection{Pixel normalization's effect: entangle objects by in-painting} \label{sec:beta-result} Our experiments demonstrate a strong tie between pixel normalization and the entanglement in the object ablation transformation $T^\prime_a$. Supported by difference-in-difference counterfactual experiments, we discover that the pixel normalization's effect $\Delta Y_{\beta\rightarrow\beta^\prime}$, informally, is to in-paint objects to ablated areas on the generated image caused by the internal ablation of corresponding units, which consequently leads to entanglement in PG-GAN. In Figure 4, we present the mechanism of how pixel normalization causes entanglement. Recall the difference-in-difference definition of pixel normalization's effect as: \begin{gather} \Delta Y_{\beta\rightarrow\beta^\prime}=[Y(\beta^\prime,\boldsymbol{u}^\prime)-Y(\beta^\prime,\boldsymbol{u})]-[Y(\beta,\boldsymbol{u}^\prime)-Y(\beta,\boldsymbol{u})] \end{gather} of which the first term $Y(\beta^\prime,\boldsymbol{u}^\prime)-Y(\beta^\prime,\boldsymbol{u})$ describes the in-painting effect produced by $\beta^\prime$ (first two columns of Row 1) and the second term $Y(\beta,\boldsymbol{u})-Y(\beta,\boldsymbol{u}^\prime)$ depicts an ablation effect (first two columns of Row 2). As a consequence of their difference, the in-painted area will cover the ablation area and presents a joint effect of in-painting. In order to well present the in-painting effect and ablation effect, we present the two effects on a background figure $\mathcal{B}$. The background figure presents the areas that do not significantly change by both effects. The background figure is presented on the third column of Figure 4. \vpara{In-painting effect under $\beta^\prime$ (after ablation)} When $\beta^\prime$ is controlled, from $Y(\beta^\prime, \boldsymbol{u})$ to its counterfactual $Y(\beta^\prime, \boldsymbol{u}^\prime)$, pixel normalization shows its in-painting functionality by inserting door objects on the original wall and wall objects on where the paintings are. \vpara{Ablation effect under $\beta$ (before ablation)} When $\beta$ is controlled, pixel normalization's response is to ablate the area of all objects related to the removed units. For example, in Figure 4's lower row where we ablated units mainly contribute to the paintings, from the original case $Y(\beta,\boldsymbol{u})$ to the counterfactual case $Y(\beta, \boldsymbol{u}^\prime)$, the PG-GAN removes all paintings away together with surrounding wall areas and turning them into a yellow background. \vpara{Joint DID effect of the pixel normalization} Combining the above two effects of in-painting and ablation, we present the final DID joint effect as in the rightmost subfigure in Figure 4, which clearly illustrates that the pixel normalization in-paints not only walls at where the paintings are ablated, unexpected door objects are also inserted to places where should have been wall. Without the rigorous DID experimental design, one may only notice the effect from the original case $Y(\beta, \boldsymbol{u})$ to the natural ablation case $Y(\beta^\prime, \boldsymbol{u}^\prime)$, and thus ignore the complicated mechanisms behind the pixel normalization. \begin{figure}[t] \label{fig:equation} \centering \includegraphics[width=5.2in]{figures/equation.pdf} \caption{The mechanism of how pixel normalization causes entanglement. The first row represents the mechanism of how ablated figure is changed by adding the top 20 related units back when pixel normalization coefficient is fixed to the after-ablation level. The second row represents the mechanism of how original figure is changed by ablating the top 20 related units back when pixel normalization coefficient is fixed to the before-ablation level. The right large figure represents the effect of pixel normalization. \vspace{-0.7cm} } \end{figure} \subsection{What to in-paint: unit distribution and ranking} In Section \ref{sec:beta-result}, we have answered the universal effect of pixel normalization, that to in-paint the area affected by the ablation transformation. But what objects the pixel normalization will in-paint to the area and how intensive this in-painting will remain unclear. We argue that the form of in-painting the pixel normalization will present in an ablation transformation could be identified according to the properties of units' ACE $\delta_{u\rightarrow c}$, namely the distribution and the ranking. First, the distribution of $\delta_{u\rightarrow c}$ determines whether an object class could be ablated. In Figure 5, we select three typical types of object classes, including chair, painting and light, to illustrate how the ACE distribution directly determines an object's ability to be disentangled. We ablate the units with ACE ranking from top to down, and observe an apparent gap between chair (categorized as Type-1) objects and painting \& light (categorized as Type -2 \& disentangled). While the chairs' area remains stubborn with top-80 ACE units ablated, the painting and light objects take no more than 20 of the top ACE units ablated to be eliminated. This confusing phenomenon could be explained when we look into their distribution of ACE. We observe that Type-1 classes distribution is flat, with high-ACE units explains for no more than 50\% of the total effect. Therefore, when we removing high-ACE units, the loss of their effects could be compensated by those lower-ACE units with $\beta^\prime$'s augmentation. However, on the contrary, Type-2 and disentangled classes have a concentrated distribution where influential units dominantly locate at the high-ACE part and thus make the most contributions to the object generation. To conclude, with such flat distribution, Type-1 classes are not disentangled at all with the ablation transformation. Second, given the Type-2 and disentangled object classes, ablation on corresponding units could eliminate them. But for Type-2 classes, when we compare it with those disentangled ones, we observe mis-ablation phenomena in which other unexpected objects would emerge. To explain this, based on the concentrated unit distribution we consider the influence of the ranking of units as shown in Figure \ref{33-ranking}. When we operate ablation on the red point and examine its unit ranking, before ablation ACE for painting is the largest, but ACE for window, curtain and door are also quite large. After ablation, the decrease of painting ACE and the increase of wall ACE make painting removed and replaced with wall. Moreover, ACE for curtain, door and window become the largest and they indeed appear in the area around the operation point, which successfully explains the mis-ablation. For the disentangled classes, such as the lights we display in the summary plot Figure 1, they actually share a similar ranking of units with those of Type-2. The only difference is that the second candidate unit just behind the ablated one happens to be the original surrounding. \begin{figure}[t] \centering \begin{minipage}[t]{0.55\textwidth} \centering \includegraphics[width=7.5cm]{figures/seg_area_change-3type.png} \setcaptionwidth{2.8in} \caption{ACE Distribution determines whether and how entanglement occurs. } \label{segarea-3typre} \end{minipage} \begin{minipage}[t]{0.35\textwidth} \centering \includegraphics[width=5.0cm]{figures/33-rank-change.PNG} \setcaptionwidth{2.0in} \setlength{\abovecaptionskip}{0cm} \caption{ The changes in ACE ranking and ratio determine what types objective are used to in-painted} \label{33-ranking} \end{minipage} \end{figure} \section{Substitution: Entanglement on emerged object} This section focus on another strange phenomenon: although we can successfully remove an object that is not so important in the scenario by ablating several top-ACE related units, sometime there will be some other strange objects appear. For example, in Figure. \ref{33-seg}, after we ablate top-20 painting-ACE units, paintings are totally disappear. However, some door-like things appear on the wall while what we expect to see is that we can get clean wall after removing these paintings. To explain why other things will appear after removing painting, we first do semantic segmentation on the image after ablating top-20 painting-ACE units. (Figure. \ref{33-seg}) using the same segmenter as in GAN Dissecion. The result shows that things that come up are some mixture of window, door, cabinet and fabric similar to curtain. \begin{figure}[htbp] \begin{center} \includegraphics[width=4in]{figures/33-seg-compare.PNG} \caption{After ablating top-20 painting-ACE units in layer 4, the painting totally disappear, but there are some other door-like objects appear. The segmenter thinks the things that come up are some mixture of window, door, cabinet and fabric like curtain.} \label{33-seg} \end{center} \end{figure} Above phenomenon shows that although painting has highly concentrated ACE distribution, it may be not totally disentangled with other objects thus they would appear after it is removed. And except painting-ACE units, there must be plenty of units in the same layer that have ACE for the objects that emerges on the wall, but their effect are covered up by painting-ACE units so only if we ablating top painting-ACE units and under the enhancement caused by pixel normalization, can these units' effect be represented. Based on this idea, we choose several objects that might appear on the wall and then get top-50 units in layer 4 that have the max activation value on the point door appears (Figure \ref{33-ranking}). We calculate and normalize the sum of these units' ACE for each particular object. We find that before ablation, the ACE for painting is the largest and there are also large ACE for window, curtain, and door, which implies that they are very likely to appear after removing paintings. As expected, after ablating top-20 painting-ACE units, ACE for curtain, door and window becomes the largest three and curtain-like fabric, door and window indeed appear at this point. Moreover, these remain units' absolute activation value at this point increases by about 9\% because of pixel normalization, which helps the appearance of fabric and door. This shows that GANs generate images by stacking many different features but may only show the most activated feature at last. If we remove some objects with high degree of disentangle, other objects with relatively smaller activated value may appear, and further fill the image under the enhancement of pixel normalization. \begin{figure}[htbp] \centering \includegraphics[width=5.0in]{figures/33-rank-change.PNG} \caption{We choose top-50 units with max activation on the point where door appears (red point) and calculate and normalize their ACE for different objects that are likely appear on the wall. Before ablation, ACE for painting is the largest ACE-related units, but ACE for window, curtain and door are also quite large. After ablation, the decrease of painting ACE and increase of wall ACE also make painting removed and replaced with wall. Moreover, ACE for curtain, door and window become the largest and they indeed appear in the area around the red point.} \label{33-ranking} \end{figure} Therefore, after removing painting, if we want to get clean wall, we still need continue to ablate several top door-, curtain-, window-ACE units, or can also ablating the remaining units with max-activation at the position where other things emerge (Fig. \ref{33-clean}). \begin{figure}[htbp] \centering \begin{subfigure}[t]{1.0in} \includegraphics[width=1.0in]{figures/33-ablate_top20.jpg} \caption{} \label{} \end{subfigure} \begin{subfigure}[t]{1.0in} \includegraphics[width=1.0in]{figures/33-ablate_related.jpg} \caption{} \label{} \end{subfigure} \begin{subfigure}[t]{1.0in} \includegraphics[width=1.0in]{figures/33-ablate-maxactivation.jpg} \caption{} \label{} \end{subfigure} \caption{After ablating top-20 painting-ACE units, we continue to (b) ablate several top door-, curtain-, window-ACE units or (c) ablate remaining units with max activation value at the positions where other things appear and get the image with clean wall at last.} \label{33-clean} \end{figure} \begin{table}[htbp] \centering \begin{tabular}{|c|c|c|} \hline object & frequency & Average area ratio\\ \hline\hline chair & 75.8\% & 14.95\%\\ \hline table & 69.4\% & 10.16\%\\ \hline person & 28.7\% & 21.01\%\\ \hline painting & 29.0\% & 3.65\%\\ \hline window & 50.7\% & 5.52\%\\ \hline curtain & 16.7\% & 5.75\%\\ \hline door & 26.8\% & 2.19\%\\ \hline silver screen & 9.05\% & 2.98\%\\ \hline cabinet & 7.89\% & 2.44\%\\ \hline \end{tabular} \caption{The occurrence frequency and average area ratio in the image of different objects in LSUN conference room dataset.} \label{LSUN} \end{table} Finally, we want to find the causes of different degree of disentangle of different objects. A direct thought is that this is caused by the bias of dataset. Table \ref{LSUN} shows the occurrence frequency and average area ratio in the image of different objects in LSUN conference room dataset. Compared with other objects, chair and table have higher frequency and relative larger area ratio in the dataset. Therefore, they may be thought by the generator as the inherent attribute of conference room, thus have lower degree of disentangle and many related units with relatively average lower ACE to prevent themselves been removed easily from the images, which improves the robustness of the network. While objects like painting may be thought as variable elements thus have high degree of disentangle and have less, but more influential units with high ACE, which also improves the diversity of the network. And among the objects that would like to appear on the wall (painting, window, curtain, door...), window and door have high frequency. This also explain to some extent that why they are more likely to appear after removing painting from the image and been enhanced by the pixel normalization. \section{Conclusion}We in this research propose a difference-in-difference (DID) counterfactual framework to design experiments for acquiring insights into the black box of PG-GAN transformation and analyzing the entanglement mechanism in one of the Progressive-growing GAN (PG-GAN). Our experiment clarifies the mechanism of how pixel normalization causes PG-GAN entanglement during an input-unit-ablation transformation. We discover that pixel normalization causes object entanglement by in-painting the area occupied by ablated objects. We also discover the unit-object relation determines whether and how pixel normalization causes object entanglement. Our DID framework theoretically guarantees that the mechanisms that we discover is solid, explainable, and comprehensive. \section{Experiment} \subsection{x/x' and $\beta/\beta'$} In this section, we use a difference-in-difference experiment to reveal the real effect of pixel normalization in image generation of GAN. We choose layer4 for this and following experiments, because the scale of details in layer4 is suitable for investigating main object classes -- previous layers focus more on the whole scene, lacking enough details, while following layers focus on too small details, such as texture. Then we choose to ablate top-20 causal units, since most main objects in the scene can disappear when we ablate corresponding top-20 causal units (Figure \ref{segarea_ablate20_variousobjects}). \begin{figure}[htbp] \centering \includegraphics[width=3.0in]{figures/seg_ablate20.png} \caption{To remove a kind of object, we can usually get good result by ablating top-20 units with highest ACE for this objects (e.g. painting, window, light, curtain and person); However, ablating top-20 chair-ACE units only results in a drop of $20\%$ on chairs' area, and we need to ablate at least top-80 chair-ACE units to get a noticeable effect.} \label{segarea_ablate20_variousobjects} \end{figure} In this experiment, we use a coefficient-fixing generator: when ablating units in layer 4, we keep the pixel normalization coefficients of all layers not changed, as if there were no ablation. In this way, pixel normalization cannot adjust the weights of different units, compared with the original procedure, which increases some units’ weights after ablating others. We also use a units-fixing generator, which does not ablate any units but applies the same pixel normalization coefficients as if we ablated some units. For $Y$, we use the original image generated by the conference room generator; for $Y'$, we ablate top-20 chair-causal units in layer 4; for $\underline{Y}$, we apply coefficient-fixing generator and ablate top-20 chair-causal units in layer 4; for $\overline{Y}$, we apply units-fixing generator and set the normalization coefficients as if we ablated top-20 chair-causal units in layer 4. The results are shown in Figure \ref{diff-in-diff}.From the results, we observe that the bright area of (c) is roughly the area of chair class in the original image while the bright area in (a) is around the chairs, such as the area of table class and floor. This indicates the real effect of normalization and ablation separately. \begin{figure}[htbp] \centering \includegraphics[width=3.0in]{figures/chair_sc_fix_beta.png} \caption{After fixing $\beta$, the drop of chair area is almost proportional to the number of ablated units, which is much better than the case not fix $\beta$.} \label{segarea_ablate20} \end{figure} \subsection{x/x' and different disentanglement of units} In this experiment, we mainly study the influence of pixel normalization and ablation on objects with different degree of disentanglement and explain why some other objects will appear after removing certain objects. To explain why some objects can be easily removed while others cannot, we first compare the distribution of ACE to chair with that to painting in layer 4. The results are shown below (Figure \ref{ace-distri}). We find that ACE to painting is more concentrated: most units either have great impact on painting class (ACE $\geq$ 0.5) or have a little impact on painting class (ACE around 0.15), while only a few units have ACE in [0.25,0.50). This concentrated distribution is in contrast to the evenly distributed chair-causal units. For chair-causal units, a relatively large proportion of units have ACE in [0.25,0.50), and the proportion of units having ACE around 0.15 is higher than that of painting-causal units. This difference suggests that the painting generation is more specialized than chair generation in layer 4. When we ablate top-20 painting-causal units, most units having great impact on painting class are ablated, and other units only account for a little effect to painting. But when we ablate top-20 chair-causal units, other units still have great impact on chair class. This explains why paintings can be easily removed while chairs cannot. \begin{figure}[htbp] \centering \includegraphics[width=3.0in]{figures/distplot.png} \caption{The distribution of units from layer 4 over chair-ACE and painting-ACE is shown. A unit is counted if it has ACE $\geq$ 0.15, since we focus on the units with observable effect on chair or painting. Since the units with ACE $\geq$ 0.6 all have great impact on the corresponding object class but are relatively few and distributed, we treat them as units with ACE $=$ 0.6.} \label{ace-distri} \end{figure} \Li {The text needs modifying.} Next, we show the degree of disentanglement between different objects based on the former observations, the specialization of units. We investigate the disentanglement between chair and table and between painting and wall by plotting ACE to them of units in layer 4. Since in conference rooms, chairs almost always appear close to the table, and the paintings are always on the wall, the degree of disentanglement of these two groups reflects the easiness of ablating chairs or paintings from the image without affecting the backgrounds. The scatter plots are shown in Figure \ref{scatter-plots}. We also calculate the average ACE to wall of all painting-causal units and the average ACE to table of all chair-causal units. From the results, we observe that the degree of disentanglement of painting and wall is higher than that of chair and table. So when we ablate painting-causal units, the wall is less affected; when we ablate chair-causal units, the table is more likely to change. Therefore, it is easier to ablate painting class from the image without influencing the wall. \begin{figure}[htbp] \begin{center} \begin{subfigure}[t]{2.5in} \vspace{0pt} \centering\begin{tikzpicture} \begin{axis}[ xlabel={ACE to window}, ylabel={ACE to wall}, ylabel absolute, ylabel style={yshift=-0.6cm}, xlabel absolute, xlabel style={yshift=0.35cm}, width=6.1cm, height=6.1cm, label style={font=\tiny}, ticklabel style={font=\tiny}, legend style={at={(1,0.35)}, anchor=south east} ] \pgfplotstableread{data/window-wall.txt}\mydata; \addplot[ scatter,only marks,scatter src=explicit symbolic, scatter/classes={ 2={mark=*,mark size=1,blue} } ] table [x=x,y=y,meta=set]{\mydata}; \end{axis} \end{tikzpicture} \centering \caption{ACE to window and wall} \label{chair-table} \end{subfigure} \begin{subfigure}[t]{2.5in} \vspace{0pt} \centering\begin{tikzpicture} \begin{axis}[ xlabel={ACE to door}, ylabel={ACE to wall}, ylabel absolute, ylabel style={yshift=-0.6cm}, xlabel absolute, xlabel style={yshift=0.35cm}, width=6.1cm, height=6.1cm, label style={font=\tiny}, ticklabel style={font=\tiny}, legend style={at={(1,0.35)}, anchor=south east} ] \pgfplotstableread{data/door-wall.txt}\mydata; \addplot[ scatter,only marks,scatter src=explicit symbolic, scatter/classes={ 2={mark=*,mark size=1,blue} } ] table [x=x,y=y,meta=set]{\mydata}; \end{axis} \end{tikzpicture} \centering \caption{ACE to door and wall} \label{painting-wall} \end{subfigure} \caption{The scatter plot of ACE to window and wall of all 512 units and the scatter plot of ACE to door and wall of all 512 units in layer 4. } \label{scatter-plots} \end{center} \end{figure} \jie{@Li chair and painting ACE distribution. Explain why painting can be easily removed.} \Li{Done.} To explain why other things will appear after removing painting, we first do semantic segmentation on the image after ablating top-20 painting-ACE units. (Figure. \ref{33-seg}) using the same segmenter as GAN Dissecion. The result shows that things that come up are some mixture of window, door, cabinet and fabric similar to curtain. Next, we choose several objects that might appear on the wall and get top-100 units in layer 4 that have the max activation value on the point door appears (Figure \ref{33-ranking}). We calculate and normalize the sum of their ACE for each particular object. We can see before ablation, the ACE for painting is the largest and there are also large ACE for window, curtain, and door, which implies that they are very likely to appear after removing paintings. As expected, after ablating top-20 painting-ACE units, ACE for curtain and door becomes the largest and curtain-like fabric and door indeed appear at this point. Moreover, these remain units' absolute activation value at this point increases by about 9\% because of pixel normalization, which helps the appearance of fabric and door. This shows that GANs generate images by stacking many different features but may only show the most activated feature at last. If we remove some objects with high degree of disentangle, other objects with relatively smaller activated value may appear, and further fill the image under the enhancement of pixel normalization. And if we continue to ablating these remain units with max-activation, we can get clean wall at last (Fig. \ref{33-clean}). \begin{figure}[htbp] \begin{center} \begin{subfigure}[t]{0.8in} \includegraphics[width=0.8in]{figures/33-original.jpg} \label{} \setlength{\abovecaptionskip}{0cm} \caption{original} \end{subfigure} \begin{subfigure}[t]{0.8in} \includegraphics[width=0.8in]{figures/33-ablate_top20.jpg} \label{} \setlength{\abovecaptionskip}{0cm} \caption{ablate top20} \end{subfigure} \begin{subfigure}[t]{0.8in} \includegraphics[width=0.8in]{figures/33-ablate-seg.png} \label{} \setlength{\abovecaptionskip}{0cm} \caption{Seg1} \end{subfigure} \begin{subfigure}[t]{0.8in} \includegraphics[width=0.8in]{figures/33-segment_of_material.PNG} \label{} \setlength{\abovecaptionskip}{0cm} \caption{Seg2} \end{subfigure} \hspace{2in} \begin{subfigure}[t]{0.8in} \includegraphics[width=0.8in]{figures/33-window.PNG} \label{} \setlength{\abovecaptionskip}{0cm} \caption{window} \end{subfigure} \begin{subfigure}[t]{0.8in} \includegraphics[width=0.8in]{figures/33-door.PNG} \label{} \setlength{\abovecaptionskip}{0cm} \caption{door} \end{subfigure} \begin{subfigure}[t]{0.8in} \includegraphics[width=0.8in]{figures/33-cabinet.PNG} \label{} \setlength{\abovecaptionskip}{0cm} \caption{cabinet} \end{subfigure} \begin{subfigure}[t]{0.8in} \includegraphics[width=0.8in]{figures/fabric.PNG} \label{} \setlength{\abovecaptionskip}{0cm} \caption{fabric} \end{subfigure} \caption{(a) The original picture. (b) After ablating top-20 painting-ACE units in layer 4, the painting totally disappear, but there are some other door-like objects appear. (c)Segmentation of objects. (d)Segmentation of materials. The segmenter thinks the things that come up are some mixture of window, door, cabinet and fabric like curtain.} \label{33-seg} \end{center} \end{figure} Finally, we want to find the causes of different degree of disentangle of different objects. A direct thought is that this is caused by the bias of dataset. Table \ref{LSUN} shows the occurrence frequency and average area ratio in the image of different objects in LSUN conference room dataset. Compared with other objects, chair and table have higher frequency and relative larger area ratio in the dataset. Therefore, they may be thought by the generator as the inherent attribute of conference room, thus have lower degree of disentangle and many related units with relatively average lower ACE to prevent themselves been removed easily from the images, which improves the robustness of the network. While objects like painting may be thought as variable elements thus have high degree of disentangle and have less, but more influential units with high ACE, which also improves the diversity of the network. And among the objects that would like to appear on the wall (painting, window, curtain, door...), window and door have high frequency. This also explain to some extent that why they are more likely to appear after removing painting from the image and been enhanced by the pixel normalization. \begin{table}[htbp] \centering \begin{tabular}{|c|c|c|} \hline object & frequency & Average area ratio\\ \hline\hline chair & 75.8\% & 14.95\%\\ \hline table & 69.4\% & 10.16\%\\ \hline person & 28.7\% & 21.01\%\\ \hline painting & 29.0\% & 3.65\%\\ \hline window & 50.7\% & 5.52\%\\ \hline curtain & 16.7\% & 5.75\%\\ \hline door & 26.8\% & 2.19\%\\ \hline silver screen & 9.05\% & 2.98\%\\ \hline cabinet & 7.89\% & 2.44\%\\ \hline \end{tabular} \caption{The occurrence frequency and average area ratio in the image of different objects in LSUN conference room dataset.} \label{LSUN} \end{table} \newpage \begin{table}[htbp] \centering \begin{tabular}{|m{2.0cm}<{\centering}|m{1.8cm}<{\centering}|m{2.4cm}<{\centering}|m{1cm}<{\centering}|m{1cm}<{\centering}|m{1cm}<{\centering}|} \hline \multicolumn{6}{|c|}{chair}\\ \hline example & ACE rank & ACE distribution & $\underline{Y}-Y$ & $Y'-\overline{Y}$ & $\Delta$ \\ \hline \includegraphics[width=0.8in]{figures/1-ablate-chair.PNG} & \includegraphics[width=0.7in]{figures/1-rank-before.png} & \includegraphics[width=0.7in]{figures/chair-ace-distribution.png} & \fbox{\includegraphics[width=0.3in]{figures/1-y-yu_1.2.png}} & \fbox{\includegraphics[width=0.3in]{figures/1-ybar-yprime_0.15.png}} & \fbox{\includegraphics[width=0.3in]{figures/1-delta_1.1.png}}\\[15pt] \hline \multicolumn{6}{|c|}{painting}\\ \hline example & ACE rank & ACE distribution & $\underline{Y}-Y$ & $Y'-\overline{Y}$ & $\Delta$ \\ \hline \includegraphics[width=0.8in]{figures/33-ablate-painting.PNG} & \includegraphics[width=0.7in]{figures/33-rank-before.png} & \includegraphics[width=0.7in]{figures/painting-ace-distribution.png} & \fbox{\includegraphics[width=0.3in]{figures/33-y-yu.PNG}} & \fbox{\includegraphics[width=0.3in]{figures/33-ybar-yprime.PNG}} & \fbox{\includegraphics[width=0.3in]{figures/33-delta_1.1.png}}\\[15pt] \hline \multicolumn{6}{|c|}{light}\\ \hline example & ACE rank & ACE distribution & $\underline{Y}-Y$ & $Y'-\overline{Y}$ & $\Delta$ \\ \hline \includegraphics[width=0.8in]{figures/112-ablate-light.PNG} & \includegraphics[width=0.7in]{figures/48-rank_before.png} & \includegraphics[width=0.7in]{figures/light-ace-distribution.png} & \fbox{\includegraphics[width=0.3in]{figures/112-y-yu0.8.png}} & \fbox{\includegraphics[width=0.3in]{figures/112-ybar-yprime.PNG}} & \fbox{\includegraphics[width=0.3in]{figures/112-delta0.8.png}}\\[15pt] \hline \end{tabular} \caption{experiment summary} \label{main_fig} \end{table} \section{Submission of conference papers to ICLR 2021} ICLR requires electronic submissions, processed by \url{https://openreview.net/}. See ICLR's website for more instructions. If your paper is ultimately accepted, the statement {\tt {\textbackslash}iclrfinalcopy} should be inserted to adjust the format to the camera ready requirements. The format for the submissions is a variant of the NeurIPS format. Please read carefully the instructions below, and follow them faithfully. \subsection{Style} Papers to be submitted to ICLR 2021 must be prepared according to the instructions presented here. Authors are required to use the ICLR \LaTeX{} style files obtainable at the ICLR website. 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 ICLR and other conference information are available online at: \begin{center} \url{http://www.iclr.cc/} \end{center} The file \verb+iclr2021_conference.pdf+ contains these instructions and illustrates the various formatting requirements your ICLR paper must satisfy. Submissions must be made using \LaTeX{} and the style files \verb+iclr2021_conference.sty+ and \verb+iclr2021_conference.bst+ (to be used with \LaTeX{}2e). The file \verb+iclr2021_conference.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 of 11~points. Times New Roman is the preferred typeface throughout. Paragraphs are separated by 1/2~line space, with no indentation. Paper title is 17~point, in small caps and left-aligned. All pages should start at 1~inch (6~picas) from the top of the page. Authors' names are set in boldface, and each name is placed above its corresponding address. The lead author's name is to be listed first, and the co-authors' names are set to follow. Authors sharing the same address can be on the same line. Please pay special attention to the instructions in section \ref{others} regarding figures, tables, acknowledgments, and references. There will be a strict upper limit of 8 pages for the main text of the initial submission, with unlimited additional pages for citations. Note that the upper page limit differs from last year!Authors may use as many pages of appendices (after the bibliography) as they wish, but reviewers are not required to read these. During the rebuttal phase and for the camera ready version, authors are allowed one additional page for the main text, for a strict upper limit of 9 pages. \section{Headings: first level} \label{headings} First level headings are in small caps, flush left and in point size 12. One line space before the first level heading and 1/2~line space after the first level heading. \subsection{Headings: second level} Second level headings are in small caps, flush left and in point size 10. One line space before the second level heading and 1/2~line space after the second level heading. \subsubsection{Headings: third level} Third level headings are in small caps, flush left and in point size 10. One line space before the third level heading and 1/2~line space after the third level heading. \section{Citations, figures, tables, references} \label{others} These instructions apply to everyone, regardless of the formatter being used. \subsection{Citations within the text} Citations within the text should be based on the \texttt{natbib} package and include the authors' last names and year (with the ``et~al.'' construct for more than two authors). When the authors or the publication are included in the sentence, the citation should not be in parenthesis using \verb|\citet{}| (as in ``See \citet{Hinton06} for more information.''). Otherwise, the citation should be in parenthesis using \verb|\citep{}| (as in ``Deep learning shows promise to make progress towards AI~\citep{Bengio+chapter2007}.''). The corresponding references are to be listed in alphabetical order of authors, in the \textsc{References} section. As to the format of the references themselves, any style is acceptable as long as it is used consistently. \subsection{Footnotes} 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).\footnote{Sample of the second footnote} \subsection{Figures} All artwork must be neat, clean, and legible. Lines should be dark enough for purposes of reproduction; art work should not be hand-drawn. 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 is lower case (except for first word and proper nouns); figures are numbered consecutively. Make sure the figure caption does not get separated from the figure. Leave sufficient space to avoid splitting the figure and figure caption. You may use color figures. However, it is best for the figure captions and the paper body to make sense if the paper is printed either in black/white or in color. \begin{figure}[h] \begin{center} \fbox{\rule[-.5cm]{0cm}{4cm} \rule[-.5cm]{4cm}{0cm}} \end{center} \caption{Sample figure caption.} \end{figure} \subsection{Tables} All tables must be centered, neat, clean and legible. Do not use hand-drawn tables. 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. \begin{table}[t] \caption{Sample table title} \label{sample-table} \begin{center} \begin{tabular}{ll} \multicolumn{1}{c}{\bf PART} &\multicolumn{1}{c}{\bf DESCRIPTION} \\ \hline \\ Dendrite &Input terminal \\ Axon &Output terminal \\ Soma &Cell body (contains cell nucleus) \\ \end{tabular} \end{center} \end{table} \section{Default Notation} In an attempt to encourage standardized notation, we have included the notation file from the textbook, \textit{Deep Learning} \cite{goodfellow2016deep} available at \url{https://github.com/goodfeli/dlbook_notation/}. Use of this style is not required and can be disabled by commenting out \texttt{math\_commands.tex}. \centerline{\bf Numbers and Arrays} \bgroup \def1.5{1.5} \begin{tabular}{p{1in}p{3.25in}} $\displaystyle a$ & A scalar (integer or real)\\ $\displaystyle {\bm{a}}$ & A vector\\ $\displaystyle {\bm{A}}$ & A matrix\\ $\displaystyle {\tens{A}}$ & A tensor\\ $\displaystyle {\bm{I}}_n$ & Identity matrix with $n$ rows and $n$ columns\\ $\displaystyle {\bm{I}}$ & Identity matrix with dimensionality implied by context\\ $\displaystyle {\bm{e}}^{(i)}$ & Standard basis vector $[0,\dots,0,1,0,\dots,0]$ with a 1 at position $i$\\ $\displaystyle \text{diag}({\bm{a}})$ & A square, diagonal matrix with diagonal entries given by ${\bm{a}}$\\ $\displaystyle {\textnormal{a}}$ & A scalar random variable\\ $\displaystyle {\mathbf{a}}$ & A vector-valued random variable\\ $\displaystyle {\mathbf{A}}$ & A matrix-valued random variable\\ \end{tabular} \egroup \vspace{0.25cm} \centerline{\bf Sets and Graphs} \bgroup \def1.5{1.5} \begin{tabular}{p{1.25in}p{3.25in}} $\displaystyle {\mathbb{A}}$ & A set\\ $\displaystyle \mathbb{R}$ & The set of real numbers \\ $\displaystyle \{0, 1\}$ & The set containing 0 and 1 \\ $\displaystyle \{0, 1, \dots, n \}$ & The set of all integers between $0$ and $n$\\ $\displaystyle [a, b]$ & The real interval including $a$ and $b$\\ $\displaystyle (a, b]$ & The real interval excluding $a$ but including $b$\\ $\displaystyle {\mathbb{A}} \backslash {\mathbb{B}}$ & Set subtraction, i.e., the set containing the elements of ${\mathbb{A}}$ that are not in ${\mathbb{B}}$\\ $\displaystyle {\mathcal{G}}$ & A graph\\ $\displaystyle \parents_{\mathcal{G}}({\textnormal{x}}_i)$ & The parents of ${\textnormal{x}}_i$ in ${\mathcal{G}}$ \end{tabular} \vspace{0.25cm} \centerline{\bf Indexing} \bgroup \def1.5{1.5} \begin{tabular}{p{1.25in}p{3.25in}} $\displaystyle {a}_i$ & Element $i$ of vector ${\bm{a}}$, with indexing starting at 1 \\ $\displaystyle {a}_{-i}$ & All elements of vector ${\bm{a}}$ except for element $i$ \\ $\displaystyle {A}_{i,j}$ & Element $i, j$ of matrix ${\bm{A}}$ \\ $\displaystyle {\bm{A}}_{i, :}$ & Row $i$ of matrix ${\bm{A}}$ \\ $\displaystyle {\bm{A}}_{:, i}$ & Column $i$ of matrix ${\bm{A}}$ \\ $\displaystyle {\etens{A}}_{i, j, k}$ & Element $(i, j, k)$ of a 3-D tensor ${\tens{A}}$\\ $\displaystyle {\tens{A}}_{:, :, i}$ & 2-D slice of a 3-D tensor\\ $\displaystyle {\textnormal{a}}_i$ & Element $i$ of the random vector ${\mathbf{a}}$ \\ \end{tabular} \egroup \vspace{0.25cm} \centerline{\bf Calculus} \bgroup \def1.5{1.5} \begin{tabular}{p{1.25in}p{3.25in}} $\displaystyle\frac{d y} {d x}$ & Derivative of $y$ with respect to $x$\\ [2ex] $\displaystyle \frac{\partial y} {\partial x} $ & Partial derivative of $y$ with respect to $x$ \\ $\displaystyle \nabla_{\bm{x}} y $ & Gradient of $y$ with respect to ${\bm{x}}$ \\ $\displaystyle \nabla_{\bm{X}} y $ & Matrix derivatives of $y$ with respect to ${\bm{X}}$ \\ $\displaystyle \nabla_{\tens{X}} y $ & Tensor containing derivatives of $y$ with respect to ${\tens{X}}$ \\ $\displaystyle \frac{\partial f}{\partial {\bm{x}}} $ & Jacobian matrix ${\bm{J}} \in \mathbb{R}^{m\times n}$ of $f: \mathbb{R}^n \rightarrow \mathbb{R}^m$\\ $\displaystyle \nabla_{\bm{x}}^2 f({\bm{x}})\text{ or }{\bm{H}}( f)({\bm{x}})$ & The Hessian matrix of $f$ at input point ${\bm{x}}$\\ $\displaystyle \int f({\bm{x}}) d{\bm{x}} $ & Definite integral over the entire domain of ${\bm{x}}$ \\ $\displaystyle \int_{\mathbb{S}} f({\bm{x}}) d{\bm{x}}$ & Definite integral with respect to ${\bm{x}}$ over the set ${\mathbb{S}}$ \\ \end{tabular} \egroup \vspace{0.25cm} \centerline{\bf Probability and Information Theory} \bgroup \def1.5{1.5} \begin{tabular}{p{1.25in}p{3.25in}} $\displaystyle P({\textnormal{a}})$ & A probability distribution over a discrete variable\\ $\displaystyle p({\textnormal{a}})$ & A probability distribution over a continuous variable, or over a variable whose type has not been specified\\ $\displaystyle {\textnormal{a}} \sim P$ & Random variable ${\textnormal{a}}$ has distribution $P$\\% so thing on left of \sim should always be a random variable, with name beginning with \r $\displaystyle \mathbb{E}_{{\textnormal{x}}\sim P} [ f(x) ]\text{ or } \mathbb{E} f(x)$ & Expectation of $f(x)$ with respect to $P({\textnormal{x}})$ \\ $\displaystyle \mathrm{Var}(f(x)) $ & Variance of $f(x)$ under $P({\textnormal{x}})$ \\ $\displaystyle \mathrm{Cov}(f(x),g(x)) $ & Covariance of $f(x)$ and $g(x)$ under $P({\textnormal{x}})$\\ $\displaystyle H({\textnormal{x}}) $ & Shannon entropy of the random variable ${\textnormal{x}}$\\ $\displaystyle D_{\mathrm{KL}} ( P \Vert Q ) $ & Kullback-Leibler divergence of P and Q \\ $\displaystyle \mathcal{N} ( {\bm{x}} ; {\bm{\mu}} , {\bm{\Sigma}})$ & Gaussian distribution % over ${\bm{x}}$ with mean ${\bm{\mu}}$ and covariance ${\bm{\Sigma}}$ \\ \end{tabular} \egroup \vspace{0.25cm} \centerline{\bf Functions} \bgroup \def1.5{1.5} \begin{tabular}{p{1.25in}p{3.25in}} $\displaystyle f: {\mathbb{A}} \rightarrow {\mathbb{B}}$ & The function $f$ with domain ${\mathbb{A}}$ and range ${\mathbb{B}}$\\ $\displaystyle f \circ g $ & Composition of the functions $f$ and $g$ \\ $\displaystyle f({\bm{x}} ; {\bm{\theta}}) $ & A function of ${\bm{x}}$ parametrized by ${\bm{\theta}}$. (Sometimes we write $f({\bm{x}})$ and omit the argument ${\bm{\theta}}$ to lighten notation) \\ $\displaystyle \log x$ & Natural logarithm of $x$ \\ $\displaystyle \sigma(x)$ & Logistic sigmoid, $\displaystyle \frac{1} {1 + \exp(-x)}$ \\ $\displaystyle \zeta(x)$ & Softplus, $\log(1 + \exp(x))$ \\ $\displaystyle || {\bm{x}} ||_p $ & $L^p$ norm of ${\bm{x}}$ \\ $\displaystyle || {\bm{x}} || $ & $L^2$ norm of ${\bm{x}}$ \\ $\displaystyle x^+$ & Positive part of $x$, i.e., $\max(0,x)$\\ $\displaystyle \bm{1}_\mathrm{condition}$ & is 1 if the condition is true, 0 otherwise\\ \end{tabular} \egroup \vspace{0.25cm} \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 \textsc{References} section; see below). Please note that pages should be numbered. \section{Preparing PostScript or PDF files} Please prepare PostScript or PDF files with paper size ``US Letter'', and not, for example, ``A4''. The -t letter option on dvips will produce US Letter files. Consider directly generating PDF files using \verb+pdflatex+ (especially if you are a MiKTeX user). PDF figures must be substituted for EPS figures, however. Otherwise, please generate your PostScript and PDF files with the following commands: \begin{verbatim} dvips mypaper.dvi -t letter -Ppdf -G0 -o mypaper.ps ps2pdf mypaper.ps mypaper.pdf \end{verbatim} \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 graphicx package. Always specify the figure width as a multiple of the line width as in the example below using .eps graphics \begin{verbatim} \usepackage[dvips]{graphicx} ... \includegraphics[width=0.8\linewidth]{myfile.eps} \end{verbatim} or \begin{verbatim} \usepackage[pdftex]{graphicx} ... \includegraphics[width=0.8\linewidth]{myfile.pdf} \end{verbatim} for .pdf graphics. See section~4.4 in the graphics bundle documentation (\url{http://www.ctan.org/tex-archive/macros/latex/required/graphics/grfguide.ps}) A number of width problems arise when LaTeX cannot properly hyphenate a line. Please give LaTeX hyphenation hints using the \verb+\-+ command. \subsubsection*{Author Contributions} If you'd like to, you may include a section for author contributions as is done in many journals. This is optional and at the discretion of the authors. \subsubsection*{Acknowledgments} \section{Related Work} \subsection{Generative Adversarial Network (GAN)} GAN~\cite{goodfellow2014generative} is a sort of deep learning models with convolutional neural networks (CNN) as the backbone that learns to generate highly realistic images in an unsupervised or self-supervised manner. Early GANs like DCGAN or WGAN trained on simple datasets only generate low resolution images, losing details and diversity of the scenario. Later, sophisticated techniques including normalization and regularization are adopted as modules into larger GAN model such as PG-GAN and BigGAN to generate high fidelity images. \subsection{Theoretical analysis on GAN} \subsection{Experimental analysis on GAN}
{'timestamp': '2020-10-19T02:17:44', 'yymm': '2010', 'arxiv_id': '2010.08402', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.08402'}
arxiv