\section{Introduction}
Recently, dialogue systems have achieved significant improvement in many areas thanks to the plethora of publicly available conversational data and the rapid advance of deep learning techniques~\cite{GaoGL19,gao2021advances,lei2020conversational}.  One of the critical challenges to enhancing the systems is generating more human-like conversation~\cite{lei2018sequicity,poria2019emotion,serban2016building}.  Hence, a system should perceive users' emotion states and express the content in an empathetic manner, e.g., by selecting suitable responses from the database or automatically generating human-like responses~\cite{DBLP:journals/tois/HuangZG20,DBLP:journals/inffus/MaNXC20}.  

\begin{figure}[t]
  \label{introduction}
  \centering
  \includegraphics[width=1\columnwidth]{introduction}  
  \caption{An example of conversations with emotion dynamics \label{fig:ex}}
\end{figure}

In the literature, Emotion Recognition in Conversation (ERC) is a sub-field of emotion recognition and aims to automatically identify human emotions in conversational scenarios~\cite{abdul2017emonet,poria2019emotion}. A critical task in this field is to model emotion dynamics in conversation~\cite{hazarika2018conversational}.  The emotion dynamics explain the conversational emotion behaviors from two dependencies, i.e., the inter-interlocutor dependency and intra-interlocutor dependency.   In a dialogue, the \textbf{inter}-interlocutor dependency describes the emotional influence \textbf{among} different interlocutors.  That is, one interlocutor tries to coerce other interlocutors changing their emotions~\cite{morris2000emotions}.  For example, as illustrated in Fig.~\ref{fig:ex}, Person B's emotion at timestamp 6 changes from \textit{Neutral} to \textit{Fear} due to the consecutive impact of Person A's strong emotion of \textit{Surprise} at timestamp 3 and 5.  Meanwhile, the \textbf{intra}-interlocutor dependency describes the emotional inertia \textbf{within} individual interlocutors.  That is, one interlocutor tries to resist the change of their own emotion against external influence~\cite{kuppens2010emotional}.  For instance, in Fig.~\ref{fig:ex}, though Person A has changed the emotion to \textit{Surprise} at timestamp 3, Person B remains the original emotion of \textit{Neutral}.

To model emotion dynamics in conversation, researchers have explored various methods based on the Recurrent Neural Networks (RNNs)~\cite{DBLP:conf/naacl/JiaoYKL19,ghosal-etal-2019-dialoguegcn,hazarika2018icon,DBLP:conf/aaai/JiaoLK20,li2020bieru,majumder2019dialoguernn,poria2017context}.  Some studies have adopted the flat structured Recurrent Neural Networks (RNNs), i.e., concatenating utterances of different interlocutors in a single sequence, for context modeling~\cite{li2020bieru,poria2017context}.  Meanwhile, other studies have established variants of hierarchically structured RNNs for context modeling~\cite{DBLP:conf/naacl/JiaoYKL19,ghosal-etal-2019-dialoguegcn,hazarika2018icon,DBLP:conf/aaai/JiaoLK20,majumder2019dialoguernn}, e.g., lining up a sequence of features extracted from a sub-sequence of utterances spoken by the same interlocutor.  However, existing approaches contain the following limitations: (1) the flat structure cannot distinguish the interlocutors because they are blended in the same sequence during temporal modeling; (2) the hierarchical structure cannot distinguish the emotional influence among interlocutors because it applies a flat structure on the extracted sub-sequence features; (3) RNNs can hardly fulfill the power of pre-training language models on large-scale data~\cite{peters2017semi,peters2018ELMo} than recently-developed Transformer-based models~\cite{liu2019roberta,vaswani2017attention,lei2021have}, e.g., BERT~\cite{devlin2019bert}. 

In this paper, we propose a series of BERT-based models to tackle the above challenges.  More specifically, we apply a Flat-structured BERT (F-BERT) to directly link up utterances in a conversation and extend the structure to a Hierarchically-structured BERT  (H-BERT) to distinguish different interlocutors in a conversation.  Both F-BERT and H-BERT can facilitate the power of BERT and can learn better representations by fulfilling pre-training strategies than RNN counterparts.  More importantly, we propose a Spatial-Temporal-structured BERT, namely ST-BERT, to further distinguish emotional influence among interlocutors by first independently capturing the intra-interlocutor and inter-interlocutor emotional influence and then unifying those emotional influence via fusion strategies.

We highlight the contributions of our work as follows: 
\begin{itemize}
\item We develop a series of BERT-based models to explore the potential of applying Transformer-based pre-training models to capture the inter-interlocutor and intra-interlocutor dependencies of the conversational emotion dynamics.  
\item We propose two basic models, F-BERT and H-BERT, as the baselines of their RNN counterparts to exploit the effect of BERT with pre-training strategies.  More importantly, we develop ST-BERT to overcome the weakness of existing work in distinguishing the emotional influence among interlocutors when modeling the emotion dynamics.
\item We conduct extensive experiments on two ERC benchmark datasets to illustrate the effectiveness of our proposed models and observe that we attain  averaged accuracy of about 5\% and 10\% improvement on IEMOCAP and MELD, respectively, over the state-of-the-art (SOTA) baselines.
\end{itemize}

\section{Related Work}

Emotions are hidden mental states associated with human thoughts and feelings~\cite{poria2019emotion}.  Emotion recognition is an interdisciplinary field that spans psychology, cognitive science, machine learning, and natural language processing~\cite{picard2010affective}. The aim is to identify correct emotions from multi-modal expressions~\cite{tsai2019multimodal,tsai2019learning,tzirakis2017end,wang2015constructing}.


\textbf{Emotion recognition in conversation} (ERC) is to predict the emotion in conversational scenarios. Rather than treating emotions as static states, ERC involves emotion dynamics in a conversation.  By comparing with the recent proposed ERC approaches~\cite{hsu2018emotionlines,majumder2019dialoguernn}, Poria et al.~\cite{poria2019emotion} discover that traditional emotion recognition methods~\cite{colneric2018emotion,kratzwald2018decision,mohammad2010emotions,shaheen2014emotion} fail to perform well because the same utterance within different context may exhibit different emotions.  Mao et al.~\cite{mao2020dialoguetrm} indicate that emotion expressions in different modalities exhibit different dependence on conversational context, where emotion dynamics mainly affect emotion expressions in textual modality.  Recently, various methods have been proposed to tackle ERC in the natural language processing community.  For example, the bi-directional Long Short-Term Memory (LSTM)~\cite{poria2017context} has been applied to capture the intra-interlocutor dependency.  The intra-interlocutor and inter-interlocutor dependencies between dyadic interlocutors have been distinguished by leveraging the hierarchical Gated Recurrent Unit (GRU) and memory networks~\cite{hazarika2018icon,hazarika2018conversational}.  Multiple GRUs with global attention mechanism have been designed and further developed in multi-party ERC~\cite{majumder2019dialoguernn}.  Graph Convolutional Networks (GCNs) have also been employed to mine complex interactions between interlocutors~\cite{ghosal-etal-2019-dialoguegcn,zhang2020generalized}.  GRU-based attention gated hierarchical memory networks have been proposed for ERC~\cite{DBLP:conf/aaai/JiaoLK20}.  However, these methods are mainly based on RNNs and do not sufficiently distinguish the emotional influence among interlocutors.



\textbf{Transformer-based pre-training language models} have applied the Transformer architecture~\cite{vaswani2017attention} to promote language understanding by a two-staged training strategy, i.e., a self-supervised pre-training on a general-domain text corpus and a fine-tune training on the downstream application data.  Pioneers~\cite{peters2017semi,peters2018ELMo} conduct pre-training on bi-directional RNNs to obtain the contextualized representation of each token.  However, RNN-based models are inefficient for long-term modeling and have limited lifting power when stacking more layers due to the limitation of the recurrent connections.  Recently, due to the power of parallel computation and deep-model construction, Transformer-based models, e.g., GPT~\cite{radford2019language}, BERT~\cite{devlin2019bert}, and ELECTRA~\cite{Clark2020ELECTRA}, have been deployed and achieved the SOTA performance in many downstream NLP applications.  Several pieces of work, e.g., transfer learning ERC~\cite{hazarika2019emotion}, utterance-level dialogue understanding~\cite{ghosal2020utterance}, and contextualized emotion sequence tagging~\cite{wang2020contextualized}, have employed pre-training models as a feature extractor in the task of ERC.  However, the potential of the Transformer-based models is less explored and does not address the problem of modeling emotion dynamics yet.


\section{Task Definition}
\label{sec:tf}
We first define the task of utterance-level emotion recognition in conversation.  
\begin{definition}[Emotion Recognition in Conversation]
Let $\mathcal{D}=\{\mathcal{D}_i|i\in[1,N]\}$ be a corpus of $N$ conversations, where $\mathcal{D}_i=\{(u^{\lambda_\tau}_\tau, y_\tau)|\tau\in[1,{L_i}],\lambda_\tau\in[1,S]\}$ is the $i$-th conversation consisting of a sequence of $L_i$ utterances.   $u^{\lambda_\tau}_\tau=w_1\cdots w_{T_\tau}$ is the $\tau$-th utterance of $T_\tau$ words spoken by the ${\lambda_\tau}$-th interlocutor from one of the total $S$ interlocutors. The corresponding emotion type is $y_\tau\in\mathcal{Y}$, where the emotion set $\mathcal{Y}$ consists of all emotions, such as anger, joy, and neutral. The goal is to train a model that can tag each utterance in a new conversation with a emotion label as accurately as possible.
\end{definition}   

In our work, we aim to capture emotion dynamics in conversations and need the following preliminary notions:
\begin{definition}[Contexts\footnote{In this paper, the notion of context denotes the preceding utterances of the target in a conversation.} in Conversation]
Let $u^{\lambda_i}_i$ be the target utterance in a conversation session 
$U=\{ u^{\lambda_\tau}_\tau|\tau\in[1,L],{\lambda_\tau}\in[1,S] \}$. According to the interlocutors that are involved, we define three types of context utterances within a sliding window of $K$ as follows:
\begin{compactitem}
\item {\bf intra-context:} the preceding utterances of the $i$-th utterance from the interlocutor $\lambda_i$ in $U$ within the window size of $K$: 
\[
\varphi(u^{\lambda_i}_i,U,K)=\{u^{\lambda_\tau}_\tau|\tau\in[\max(i-K, 1), i),{\lambda_\tau}= \lambda_i\},
\]
\item {\bf inter-context:} the preceding utterances of the $i$-th utterance from the interlocutors, except $\lambda_i$, in $U$ within the window size of $K$:  
\[
\phi(u^{\lambda_i}_i,U,K)=\{u^{\lambda_\tau}_\tau|\tau\in[\max(i-K, 1), i),{\lambda_\tau}\neq \lambda_i\}
\] 
\item {\bf conv-context:} the preceding utterances of the $i$-th utterance in $U$ within the window size of $K$:  
\[
\psi(u^{\lambda_i}_i,U,K)=\{u^{\lambda_\tau}_\tau|\tau\in[\max\{i-K,1\},i),{\lambda_\tau}\in [1,S]\}.
\]
\end{compactitem}
\end{definition}

Table~\ref{tab:example} presents an example of the three types of contexts in a conversation.

\begin{table}[h]
\scriptsize
\centering
  \caption{An example of context utterances in a conversation when $L=8$, $S=3$, and $K=5$.
  }
  \small
  \label{tab:example}
  \begin{tabular}{p{3cm}|p{4cm}}
    \toprule
    conversation                       & $U= u^1_1\, u^2_2\,u^1_3\,u^1_4\,u^3_5\,u^2_6\,u^1_7\,u^2_8$\\
    \midrule
    target utterance                   & $u^1_7$\\
    \midrule
    intra-context                      & $\varphi(u^1_7,U,5)=u^1_3\,u^1_4$\\
    \midrule
    inter-context                      & $\phi(u^1_7,U,5)=u^2_2\,u^3_5\,u^2_6$\\
    \midrule
    conv-context                       & $\psi(u^1_7,U,5)=u^2_2\,u^1_3\,u^1_4\,u^3_5\,u^2_6$\\
    \bottomrule
  \end{tabular}
\end{table}




\section{BERT}
\begin{figure}[h]
  \centering
  \includegraphics[width=1\columnwidth]{transformer}  
  \caption{Architecture of the temporally unfolded Transformer blocks\label{fig:TB}}
\end{figure}
BERT is a powerful Transform-based language model and performs exceptionally well in many downstream NLP tasks~\cite{devlin2019bert}.  A standard BERT model consists of a stack of $L$ identical Transformer blocks expanding in a sequence mode as illustrated in Fig.~\ref{fig:TB} to naturally exploit the temporal information.  Each Transformer block consists of two sublayers, i.e., a multi-head self-attention sublayer and a position-wise fully connected feed-forward sublayer.  Residual connection with layer normalization is employed on each of the two sublayers to avoid the problem of gradient vanishing in training.  The final output is then computed by $\mbox{LayerNorm}(x + \mbox{Sublayer}(x))$, where $\mbox{Sublayer}(x)$ is one of the above mentioned sublayers~\cite{vaswani2017attention}.  In the following, we briefly elucidate the three main layers in BERT.



\textit{Embedding layer:} given utterance-context pairs, BERT has 5 key operations in dealing with the input pairs: (1) packing the utterance and its context into a sequence of tokens by WordPiece tokenization; (2) adding $[\mbox{CLS}]$ as the classification token at the head of a sequence; (3) adding the special token $[\mbox{SEP}]$ and token type embeddings to differentiate the utterance and its context; (4) applying WordPiece embeddings~\cite{WuSCLNMKCGMKSJL16} on the tokens; (5) adding position embeddings to maintain the order information in a sequence. 

\textit{Multi-head attention sublayer:} the output of embedding layer is fed to the multi-head self-attention sublayer (the orange blocks in Fig.~\ref{fig:TB}) to model temporal dependency.  A multi-head attention independently applies attention mechanism $H$ times along with the query $Q\in\mathbb{R}^{d_k}$, key $K\in\mathbb{R}^{d_k}$, and value $V\in\mathbb{R}^{d_v}$, respectively, and concatenates them together:
\begin{align}
& \mbox{MultiHead}(Q, K, V) = \mbox{Concat}(head_1,...,head_H)W^O,\\\nonumber
& head_h = \mbox{Attention}(QW_h^Q, KW_h^K, VW_h^V), \\\nonumber
&\qquad~~ = \mbox{softmax}(\frac{QW_h^Q(KW_h^K)^T}{\sqrt[]{d_k}})VW_h^V,~~ h=1,\ldots, H,
\end{align}
where $\frac{1}{\sqrt{d_k}}$ is a scaling factor to avoid pushing the softmax function into small gradients regions when $d_k$ is large~\cite{vaswani2017attention}.  $head_h$ is the $h$-th output of attention operation.  $W_h^Q\in\mathbb{R}^{d_{model}\times d_k}, W_h^K\in\mathbb{R}^{d_{model}\times d_k}, W_h^V\in\mathbb{R}^{d_{model}\times d_v},W^O\in\mathbb{R}^{Hd_v\times d_{model}}$ are the weights of the projection matrices for computing the $h$-th attention operations.  Practically, we set the dimension $d_k=d_v=d_{model}/H$.
\if 0
\begin{align}
head_h &= \mbox{Attention}(QW_h^Q, KW_h^K, VW_h^V)\\
       &= \mbox{softmax}(\frac{QW_h^Q(KW_h^K)^T}{\sqrt[]{d_k}})VW_h^V
\end{align}
\fi 

\textit{Fully connected feed-forward sublayer:} after applying the multi-head attention, a two-layer fully connected feed-forward network is computed by a RELU on the hidden state:
\begin{equation}
    \max(0, xW_1 + b_1)W_2 + b_2,
\end{equation}
where $x$ is the output from the multi-head attention sublayer, $W_1\in\mathbb{R}^{d_{model}\times d_{hidden}}$, $W_2\in\mathbb{R}^{d_{hidden}\times d_{model}}$, and $b_1\in\mathbb{R}^{d_{hidden}}$, $b_2\in\mathbb{R}^{d_{model}}$ are the projection matrices and biases for the fully-connected networks, respectively. 



\section{Our Proposal}
In the following, we present our proposed series of BERT-based models. 
\subsection{F-BERT}
{The Flat-structured BERT (F-BERT), as illustrated in Fig.~\ref{fs}, is to directly {concatenate} the target utterance with the conv-context while applying BERT afterwards.} The input is a sequence of utterance-context pair, i.e., the {target utterance} of $T$ sub-words, $u^{\lambda_i}_i=w_1\cdots w_{T}$, and the  {conv-context} of $\mathcal{T}_\psi$ sub-words, $\psi(u^{\lambda_i}_i, U, K)=\omega_1\cdots \omega_{\mathcal{T}_\psi}$. We pack the pairs into a sequence of tokens:
\begin{equation}
X_i=  [\mbox{CLS}]\,u^{\lambda_i}_i\,[\mbox{SEP}]\,\psi(u^{\lambda_i}_i, U, K)\,[\mbox{SEP}].  
\end{equation}
Hence, $X_i$ includes the information of the target utterance with the conversation context, but does not distinguish the identity of interlocutors.

After pre-processing, $X_i$ is fed to BERT and represented by the last hidden layer at the $[\mbox{CLS}]$ token, denoted by
\begin{equation}
r_i=\mbox{BERT}(X_i),
\end{equation}
where $r_i$ is the output representation of $u^{\lambda_i}_i$ for emotional predictions.

\begin{figure}[t]
  \centering
  \subfigure[Flat Structure]{\includegraphics[width=0.31\columnwidth]{model_a}\label{fs}}     
  \subfigure[{Hierarchical Structure}]{\includegraphics[width=0.645\columnwidth]{model_b}\label{hs}}
  \subfigure[{Spatial-Temporal Structure}]{\includegraphics[width=1\columnwidth]{model_c}\label{sts} }
  \caption{Architecture of the proposed BERT-based models given inputs of table~\ref{introduction}}
\end{figure}

\subsection{H-BERT}
\label{sec:HS}

{The Hierarchically-structured BERT (H-BERT), as illustrated in Fig.~\ref{hs}, first applies BERT to wrap up an utterance with its intra-context to capture the intra-interlocutor dependency as the branch feature.  Next, it lines up the branch features in conversational order by the backbone Transformer to produce the final output representation.}  More specifically, the input of a branch BERT is a sequence of utterance-context pair, i.e., the target utterance of $T$ sub-words, $u^{\lambda_i}_i=w_1\cdots w_T$, and the intra-context of $\mathcal{T}_\varphi$ sub-words, $\varphi(u^{\lambda_i}_i,U,K)=\omega_1\cdots \omega_{\mathcal{T}_\varphi}$. After packing, we compute the input sequence by 
\begin{equation}
X^{\lambda_i}_i =  [\mbox{CLS}]\,u^{\lambda_i}_i\,[\mbox{SEP}]\,\varphi(u^{\lambda_i}_i,U,K)\,[\mbox{SEP}].
\end{equation}
Thus, $X^{\lambda_i}_i$ includes the information of the target utterance with historical utterances only spoken by the target interlocutor. By feeding $X^{\lambda_i}_i$ to BERT, we obtain 
\begin{equation}
f^{\lambda_i}_i=\mbox{BERT}(X^{\lambda_i}_i),
\end{equation}
we can obtain $f^{\lambda_i}_i$, the intra-interlocutor dependency of the $\lambda_i$-th interlocutor, which maintains the $i$-th emotion influence in a conversation.

{Let $F=f^{\lambda_1}_1\cdots f^{\lambda_L}_L$ be the sequence of the branch features of the entire conversation. The input of the backbone Transformer is a sliding window of $K+1$ in $F$:
\begin{equation}
F_i =f^{\lambda_{i-K}}_{i-K}\cdots f^{\lambda_{i-1}}_{i-1}f^{\lambda_i}_i.
\end{equation}
where $f^{\lambda_i}_i$ is the target feature at the last position.  $f^{\lambda_{i-K}}_{i-K}\cdots f^{\lambda_{i-1}}_{i-1}$ are the preceding $K$ features that may produce emotional influence to the target.  $F_i$ is fed to the backbone Transformer and represented by the last hidden layer at the target position.  The computation of the Transformer is
\begin{equation}
r_i=\mbox{Transformer}(F_i),
\end{equation}
where $r_i$ is the representation of $u^{\lambda_i}_i$ conditioned on the temporally wrapped emotion influence for making predictions.}



\subsection{ST-BERT}

The Spatial-Temporal-structured BERT (ST-BERT), as illustrated in Fig.~\ref{sts}, first applies BERT to individually wrap up the inter-context and intra-context of the target utterance as two types of temporally captured emotion influence.  After that, different fusion strategies are applied to combine the two temporally captured emotional influence into a single spatial representation.

\textbf{Temporal Construction.} 
Given the target utterance $u^{\lambda_i}_i=w_1\cdots w_T$ of $T$ sub-words, we construct two individual sequences of utterance-context pairs: 
\begin{align}
& X^\varphi_i = [\mbox{CLS}]\,u^{\lambda_i}_i\,[\mbox{SEP}]\,\varphi(u^{\lambda_i}_i,U,K)\,[\mbox{SEP}],\\
& X^\phi_i = [\mbox{CLS}]\,u^{\lambda_i}_i\,[\mbox{SEP}]\,\phi(u^{\lambda_i}_i,U,K)\,[\mbox{SEP}],
\end{align}
where $X^\varphi_i$ includes the information, which maintains the emotion inertia of the $\lambda_i$-th interlocutor by incorporating the intra-context $\varphi(u^{\lambda_i}_i,U,K)=\omega^\varphi_1\cdots \omega^\varphi_{\mathcal{T}_\varphi}$. $X^\phi_i$ includes the information, which produces emotional influence from the non-$\lambda_i$ interlocutor by incorporating the inter-context $\phi(u^{\lambda_i}_i,U,K)=\omega^\phi_1\cdots \omega^\phi_{\mathcal{T}_\phi}$. The two types of token sequences are then fed to the BERT, 
\begin{equation}
f^\varphi_i=\mbox{BERT}(X^\varphi_i), \quad
f^\phi_i=\mbox{BERT}(X^\phi_i ),
\end{equation}
we can directly and explicitly capture the intra-interlocutor and inter-interlocutor dependencies in $f^\varphi_i\in\mathbb{R}^{d_{model}}$ and $f^\phi_i\in\mathbb{R}^{d_{model}}$, respectively. The two temporally contextualized features are fused vertically in different spatial fusion strategies.  

\textbf{Spatial Fusion.} 
We explore three types of spatial fusion strategies, including direct concatenation, gate operation, and attention mechanism.  

\textit{Direct concatenation} is a simple but effective strategy.  It does not involve interactions between features and can be computed by a fully-connected network: 
\begin{equation}
r_i=W^C[f^\varphi_i; f^\phi_i] + b^C,
\end{equation}
where $[\cdot;\cdot]$ is the concatenation. $r_i\in\mathbb{R}^{d_{hidden}}$ is the output representation for emotional predictions. $W^C$ and $b^C$ are the projection matrix and bias, respectively.

\textit{Gate operation} is a neuron-level interactive weighting strategy.  The computation can be formulated as
\begin{align}
& h^\varphi_i=\tanh(W^\varphi f^\varphi_i + b^\varphi),\\
&h^\phi_i=\tanh(W^\phi f^\phi_i + b^\phi),\\
&z_i=\sigma(W^Z [f^\varphi_i; f^\phi_i] + b^Z),\\
&r_i=z_i * h^\varphi_i + (1-z_i)*h^\phi_i,
\end{align}
where $h^\varphi_i\in\mathbb{R}^{d_{hidden}}$ and $h^\phi_i\in\mathbb{R}^{d_{hidden}}$ are the projections of $f^\varphi_i$ and $f^\phi_i$, respectively. $*$ refers to the Hadamard product whose function is to use neurons in one vector to weight the neurons of its counterpart at the same position. Here, $z_i\in\mathbb{R}^{d_{hidden}}$ is to weight neurons in $h^\varphi_i$ and $1-z_i$ is to weight neurons in $h^\phi_i$, where $z_i$ is computed by feature interactions between $f^\varphi_i$ and $f^\phi_i$, $\sigma$ is to maps the $z_i$ to $(0,1)$. Note that the impact of ``$1-z_i$" on $h^\phi_i$ is critical  because it allows to learn the weights of the neurons in $h^\varphi_i$ and $h^\phi_i$ contrastively~\cite{arevalo2020gated}.  $W^\varphi$ and $b^\varphi$, $W^\phi$ and $b^\phi$, and $W^Z$ and $b^Z$, are the corresponding projection matrices and biases, respectively.  $r_i$ is the final output representation.   

\textit{Attention mechanism} is a vector-level interactive weighting strategy.  The insight is identical to that of the gate operation. The major difference is that gate operation allocate different weights to neurons in a vector while attention operation allocate the same weight to neurons in a vector.  The attention operation can be computed by
\begin{align}
&\alpha_i=\sigma(\frac{f^\varphi_i (f^\phi_i)^T}{\sqrt{d_{model}}}),\\
\label{eq:ST-BERT-att}
&r_i=\alpha_i * h^\varphi_i + (1-\alpha_i)*h^\phi_i,
\end{align}
where $\frac{1}{\sqrt[]{d_{model}}}$ is the scaling factor. $d_{model}$ is the dimention of  $f^\varphi_i, f^\phi_i$. $\alpha_i$ is the attention weight and a scalar computed by dot-product between $f^\varphi_i$ and $f^\phi_i$.  Again, the operation of ``$1-\alpha_i$" plays a trade-off on the weight for contrastive learning~\cite{cho2014learning}. $r_i$ is the final output representation.

\subsection{Discriminator}
The discriminator is a two-layer perceptron with the hidden layer activated by the $\tanh$ function, which can be trained by minimizing the cross-entropy loss.  Given the representation $r_i$, the discriminator output emotion distributions computed by the softmax function:
\begin{align}
&o_i=\tanh(W^O \cdot r_i),\\
&\mathcal{P}_i=\mbox{softmax}(W^{\mathcal{P}_i}\cdot o_i),\\
&\hat{y}_i=\mathop{\arg \max}\limits_k\mathcal{P}_i[k],
\end{align}
where $\hat{y}_i$ is the predicted emotion. $W^O$ and $W^{\mathcal{P}_i}$ are the corresponding projection matrices.

\section{Experiments}
In this section, we present the experiments with detailed analysis.
\subsection{Datasets}
Two popular ERC datasets, IEMOCAP~\cite{busso2008iemocap} and MELD~\cite{poria2019meld}, are adopted to evaluate our proposed models. Statistics on the two datasets are presented in Table~\ref{fig:stat}.

{IEMOCAP} consists of dyadic conversation videos between pairs of 10 speakers. Each utterance is annotated with one of the six emotion types, including happy, sad, neutral, angry, excited, and frustrated. Following~\cite{majumder2019dialoguernn}, we apply the first four sessions in training and use the last session for test.  The validation conversations are randomly selected from the training set with a ratio of 0.1.

{MELD} consists of multi-party conversation videos collected from the Friends TV series. Each utterance is annotated with one of the seven emotion types, including anger, disgust, sadness, joy, neutral, surprise, and fear. We apply the official splits for training, validation, and test in this dataset.


\begin{table}[htp]
\centering
\caption{Statistics of the two datasets}
\label{fig:stat}
\begin{tabular}{l|P{20pt}|P{20pt}|P{20pt}|P{25pt}|c}
\toprule
\multirow{2}{*}{Dataset} & \multicolumn{3}{c|}{\# Utterances} & \multirow{2}{*}{Classes} & \multirow{2}{*}{Avg. conv. length} \\
                         & train      & val       & test     &                           &                                           \\
\midrule
IEMOCAP                  & 5,663      & 647       & 1,623    & 6                         & 50                                        \\
MELD                     & 9,989      & 1,109     & 2,610    & 7                         & 8                                         \\
\bottomrule
\end{tabular}
\end{table}

\subsection{Implementation Details}
In the experiment, BERT$_{\tiny\mbox{Base}}$ is adopted as the fundamental sequential module, where it consists of 12 Transformer blocks, 12 self-attention heads, and 768 hidden-units.  We employ the off-the-shelf implementation of BERT$_{\tiny\mbox{Base}}$ model in ``\textit{Transformers}"\footnote{https://github.com/huggingface/transformers}. The pre-trained parameters are deployed for initializing BERT. Other parameters are randomly initialized. All the hyperparameters are keeping default. The backbone of the H-BERT is a 6-layer, 12-head-attention, and 768 hidden-unit Transformer encoder implemented using \textit{torch.nn.TransformerEncoder}\footnote{https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html} in PyTorch. The parameters of the backbone Transformer are randomly initialized. We use AdamW~\cite{loshchilov2018fixing} as the optimizer with the following setup: an initial learning rate of $6e-6$, $\beta_1=0.9$, $\beta_2=0.999$, L2 weight decay of $0.01$, learning rate warms up steps being $0$, and linear decay of the learning rate. All the results are based on an average of 5 runs. 

\begin{table*}[htp]
\small
\centering
\begin{threeparttable}
  \caption{Main Results on IEMOCAP and MELD.\label{tab:rs}}
  \begin{tabular}{l|p{16pt}p{16pt}|p{16pt}p{16pt}|p{16pt}p{16pt}|p{16pt}p{16pt}|p{16pt}p{16pt}|p{16pt}p{16pt}|p{16pt}p{16pt}|p{16pt}p{16pt}}
    \toprule
    \multirow{3}{*}{Model} & \multicolumn{14}{c|}{IEMOCAP} & \multicolumn{2}{c}{MELD}\\
    \cline{2-17}
    & \multicolumn{2}{c|}{happy} & \multicolumn{2}{c|}{sad} & \multicolumn{2}{c|}{neutral} & \multicolumn{2}{c|}{angry} & \multicolumn{2}{c|}{excited} & \multicolumn{2}{c|}{frustrated} & \multicolumn{2}{c|}{\textbf{Avg.(w)}} & \multicolumn{2}{c}{\textbf{Avg.(w)}}\\
                 & ACC   & F1    & ACC   & F1    & ACC   & F1    & ACC   & F1    & ACC   & F1    & ACC   & F1    & ACC   & F1 & ACC & F1        \\
    \midrule\midrule
    scLSTM       & 37.5  & 43.4  & 67.7  & 69.8  & 64.2  & 55.8  & 61.9  & 61.8  & 51.8  & 59.3  & 61.3  & 60.2  & 59.2  & 59.1& 57.5  & 55.9 \\
    TL-ERC       & -    & -     & -     & -     & -     & -     & -     & -     & -     & -     & -     & -     & -     & 58.8& -        & -    \\  
   
   
    DRNN*        & 25.7 & 33.2 & 75.1   & 78.8  & 58.6 & 59.2 & 64.7 & 65.3 & \textbf{80.3} & 71.9 & 61.2 & 59.0 & 63.4  & 62.8& 56.1  & 55.9 \\
    DRNN$\dag$*  & - & - & -   & - & - & - & - & -& - & - & - & - & - & 64.1  & -        & - \\
    DGCN*        & 40.6 & 42.8 & \textbf{89.1}   & \textbf{84.5} & 61.9 & 63.5 & 67.5 & 64.2 & 65.5 & 63.1 & 64.2 & \textbf{67.0} & 65.3 & 64.2  & -        & 58.1 \\
    
    AGHMN        & 48.3 & \textbf{52.1} & 68.3   & 73.3  & 61.6  & 58.4  & 57.5  & 61.9  & 68.1  & 69.7  & 67.1  & 62.3  & 63.5  & 63.5& 59.5  & 57.5 \\
    CESTa*       & -    & 47.7 & -      & 80.8  & -    & 64.8 & -    & 63.4 & -    & \textbf{76.0} & -   & 62.7 & - & 67.1 & -      & 58.4 \\
    \midrule\midrule
    F-BERT       & \textbf{52.8} & 50.8 & 77.6 & 77.6 & 65.1 & 64.1 & \textbf{71.2} & 61.9 & 65.6 & 69.4 & 58.5 & 61.9 & 65.1 & 65.2 & 63.0 & 62.5\\
    H-BERT       & 30.8 & 33.2 & 68.4 & 73.9 & 69.2 & 68.7 & 66.0 & 59.0 & 70.3 & 70.0 & 65.1  & 64.6 & 65.1 & 65.1 & 63.2 & 62.6\\
    \midrule\midrule
    ST-BERT-ATT  & 37.5 & 41.7 & 80.0 & 77.2 & 72.1 & 66.3 & 54.7 & 57.6 & 63.2 & 68.6 & 64.6 & 64.0 & 65.0 & 64.7 & 64.4 & 62.7 \\
    ST-BERT-CON  & 46.5 & 49.1 &81.2 & 80.4 &\textbf{76.3} & \textbf{68.6}& 61.2 & 62.7 & 68.2 & 71.7& 60.4 & 63.6 & 67.6 & 67.4 & 65.5 & 63.5 \\
    ST-BERT-GAT  & 45.1 & 48.5 & 80.0 & 82.2 & 72.4 & 68.6 & 66.5 & \textbf{65.6} & 66.9 & 69.9 & \textbf{67.2} & 66.6 & \textbf{68.5} & \textbf{68.4} & \textbf{65.7} & \textbf{63.8} \\
    \bottomrule 
  \end{tabular}
  \begin{tablenotes}
      \scriptsize
      \item Symbol * indicate that models are fed with succeeding context. DRNN$\dag$*~\cite{ghosal2020utterance} is fed with RoBERTa~\cite{liu2019roberta} features. -ATT, -CON, and -GAT denote the attention, concatenation, and gate mechanism in ST-BERT.
  \end{tablenotes}
\end{threeparttable}
\end{table*}

\subsection{Comparing Methods and Metrics}
We investigate previous ERC methods based only on the textual modality:
\begin{compactitem}
\item {scLSTM}~\cite{poria2017context} is the earliest study that we can track in the task of ERC. It makes predictions by only considering intra-interlocutor dependency.

\item {TL-ERC}~\cite{hazarika2019emotion} applies BERT as a transfer learning module for context modeling. That is, it simply employs BERT as a feature extractor and applies RNN for modeling emotion dynamics in conversation afterwards.



\item {DRNN}~\cite{majumder2019dialoguernn} is DialogueRNN, a hierarchical attention-based model with three GRUs to capture the emotion dynamics.  In the experiment, we compare both DRNN with the CNN and DRNN with the RoBERTa features~\cite{liu2019roberta,ghosal2020utterance}, denoted by DRNN$\dag$.

\item {DGCN}~\cite{ghosal-etal-2019-dialoguegcn} applies GCN to model utterance interactions among interlocutors by considering speaker positions in the historical conversation.

\item {AGHMN}~\cite{DBLP:conf/aaai/JiaoLK20} finetunes sentence representation and uses GRU to wrap the attention-weighted representations rather than summing them up.

\item {CESTa}~\cite{wang2020contextualized} is the SOTA ERC method.  It first applies a flat Transformer at the bottom layer to obtain contextualized representation for each utterance in the conversation.  Next, it cascades a hierarchical LSTM upon the Transformer to distinguish contextualized representations of interlocutors.
\end{compactitem}

Following~\cite{ghosal-etal-2019-dialoguegcn,majumder2019dialoguernn}, we use the weighted accuracy (ACC)  and weighted average F1 (F1) as the evaluation metrics:
\begin{align}
    \mbox{ACC} = \sum_{c=1}^{|\mathcal{C}|}p_c\cdot a_c,\quad
    \mbox{F1} &= \sum_{c=1}^{|\mathcal{C}|}p_c\cdot \mbox{F1}_c,
\end{align}
where $p_c$ is the percentage of the class $c$ in the testing set, $a_c$ and $F1_c$ are the corresponding accuracy and F1 score for the class $c$, respectively.  It is worth mentioning that we mainly focus on the average scores because all the methods have trade-off among individual emotion types. 
\subsection{Main Results}
Table~\ref{tab:rs} reports the main results.  We can observe that  
\begin{compactitem}[--]
\item The Transformer-based models, i.e., {CESTa} and our proposed models, achieve better performance than RNN-based models on IEMOCAP.  Notice that, the results of F-BERT and H-BERT are competitive.  By observing the average conversation length on IEMOCAP is 50, we can note that Transformer-based models can effectively capture information for long sentences.
\item The average ACC and F1 of our {ST-BERT-GAT} significantly ($p<0.05$ in $t$-test) outperforms the SOTA baselines and attains 5\% and 2\% improvement on IEMOCAP in terms of ACC and F1 metrics, respectively, while achieving 10\% and 8\% improvement on MELD in terms of ACC and F1, respectively.  By examining more details, we notice that  
\begin{compactitem}
\item ST-BERT outperforms {TL-ERC} (applying BERT), {DRNN$\dag$} (using the RoBERTa features), and {CESTa} (applying Transformer), which exhibits the superiority of our model structure rather than simply using the pre-training models. 
\item ST-BERT also outperforms models using the succeeding context, i.e., {DRNN}, {DRNN$\dag$}, {DGCN}, and {CESTa}.  This implies that our model is more practical in real conversations.
\end{compactitem}
\item ST-BERT also attains the best scores in many individual emotion types, especially ``neutral".  The type of ``neutral" is hard to distinguish because the ``neutral" utterances often contain emotional words.  For example, the word ``excited" colored in blue of Table~\ref{tab:case} may mislead the recognition.  On the contrary, if the model can distinguish the emotional influence among interlocutors, it could easily discover the ``frustrated" emotion from the single word utterance ``Yeah." because most of the time, the emotions of ``frustrated" and ``excited" do not appear simultaneously in a conversation.  The ST-BERT can distinguish the emotional influence through independent temporal modeling and different types of fusion. 
\item By comparing different fusion mechanisms in ST-BERT, we notice that the gate mechanism outperforms others.  Surprisingly, the attention mechanism performs worse than the one by direct concatenation.  We conjecture that the linear combination may not  sufficient absorb the two representations defined in Eq.~(\ref{eq:ST-BERT-att}).  Though the attention mechanism in the Transformer can learn the complex interactions between interlocutors, the hierarchical structure does not provide more information gain than the Flat structure. 
\end{compactitem}


\begin{table}[htp]
\small
\centering
  \caption{Ablation study on IEMOCAP.}
  \label{tab:ab}
  \begin{tabular}{cccc|c}
    \toprule
    target & intra-context & inter-context & pre-train & Avg.(w) F1 \\
    \midrule
    $\surd$       & $\times$      & $\times$      & $\times$  & 49.2    \\
    $\surd$       & $\surd$       & $\times$      & $\times$  & 56.2    \\
    $\surd$       & $\times$      & $\surd$       & $\times$  & 55.5    \\
    $\surd$       & $\surd$       & $\surd$       & $\times$  & 60.8    \\
    \midrule
    $\surd$       & $\times$      & $\times$     & $\surd$   & 55.6    \\
    $\surd$       & $\surd$       & $\times$     & $\surd$   & 63.5    \\
    $\surd$       & $\times$      & $\surd$      & $\surd$   & 61.5    \\
    $\surd$       & $\surd$       & $\surd$      & $\surd$   & 68.4    \\
    \bottomrule
\end{tabular}
\end{table}

\subsection{Ablation Study}
Table~\ref{tab:ab} shows the ablation study on IEMOCAP to test the effect of the components in ST-BERT, including target utterance, intra-context, inter-context, and pre-training.  The first four cases are based on BERT without pre-training, i.e., randomly initializing the parameters. The first case is to test the vanilla BERT$_{\tiny\mbox{Base}}$ without including any context information. The following three cases are to test ST-BERT with intra-context, ST-BERT with inter-context, and ST-BERT with both intra-context and inter-context, respectively.  Similarly, the last four cases are to test the above four cases by the pre-training BERT$_{\tiny\mbox{Base}}$ initialization.  The average F1 scores reported in Table~\ref{tab:ab} clearly show that
\begin{compactitem}
\item Without pre-training, our ST-BERT performs even worse than some baselines in Table~\ref{tab:rs}.  We conjecture that because IEMOCAP is a small dataset, the deep structure of BERT cannot be well-trained in this dataset.
\item Though the models perform poorly when applying randomly initialization, our ST-BERT still beats {TL-ERC} (applying pre-trained BERT). This implies that ST-BERT indeed sufficiently capture emotion dynamics to improve the model performance.
\item When we apply pre-trained BERT on our models, we can obtain significant improvement in all four compared cases. Especially, in ST-BERT, we attain 68.4 F1 score and outperforms {DRNN$\dag$*}, which has applied more advanced pre-training techniques, e.g., RoBERTa.  By comparing other cases, we observe that by including intra-context, more gains can be obtained than by including inter-context.
\end{compactitem}






\begin{figure}[htp]
  \centering
  \subfigure[{BERT$_{\tiny\mbox{Base}}$}] {  
  \label{bs_rs}
  \includegraphics[width=0.445\columnwidth]{BS_CM.png}  
  } 
  \subfigure[F-BERT] {  
  \label{fs_rs}
  \includegraphics[width=0.445\columnwidth]{FS_CM.png}  
  }     
  \subfigure[{H-BERT}]{
    \label{hs_rs}
  \includegraphics[width=0.445\columnwidth]{HS_CM.png}  
  }
  \subfigure[{ST-BERT}]{
    \label{sts_rs}
  \includegraphics[width=0.445\columnwidth]{ST_CM.png} 
  }
  \caption{Heat map of confusion matrix of four BERT-based models.\label{fig:cm}}
\end{figure}

\subsection{Case Study}
We depict the confusion matrices in the form of heat maps to better understand our proposed BERT-based models. The confusion matrices are based on the results of BERT$_{\tiny\mbox{Base}}$, F-BERT, H-BERT, and ST-BERT on IEMOCAP as shown in Fig.~\ref{fig:cm}.  Notice that the types of ``happy", ``excited", and ``neutral" comprise more  easy-to-confuse cases in the positive emotion group while the types of ``sad", ``angry", ``frustrated", and ``neutral"  comprises more easy-to-confuse cases in the negative emotion group.  The ``neutral" type belongs to both groups and is thus particularly hard for recognition.  However, our proposed F-BERT, H-BERT, and ST-BERT perform better than BERT$_{\tiny\mbox{Base}}$ in recognizing ``neutral".  By comparing Fig.~\ref{hs_rs} and Fig.~\ref{sts_rs}, we can notice that ST-BERT exhibits more power in distinguishing the negative emotions and obtain higher performance. 

Table~\ref{tab:case} illustrates a conversation snippet classified by our proposed BERT-based models. There are two challenges in predicting the four utterances.  One is to predict the emotion of a short utterance at the second turn.  The other is to predict the emotion of an utterance with the misleading word ``excited" at the fourth turn.  The results show that ST-BERT correctly predicts the emotion in all four  utterances.  H-BERT cannot distinguish the emotion when there is a misleading word.  Meanwhile, F-BERT fails in predicting both cases.

\begin{table}[htp]
\small
\centering
\caption{A conversation snippet classified by F-BERT (F), H-BERT (H), and ST-BERT (ST). GT stands for ground truth of the emotion types in neutral (Neu.), frustrated (Fru.), and excited (Exc.) .  \label{tab:case}}
\begin{tabular}{|m{6pt}|m{0.7cm}|m{3.4cm}|m{8pt}m{8pt}m{8pt}m{12pt}|}
\hline
&&&&&&\\[-1ex]
 &  A &  B & GT & F  & H    & ST    \\[1.25ex]
\hline\hline
&&&&&&\\[-1.25ex]
\#1    &                        & There's like mystery here, there's magic. It's like a little bit of the unexplainable. I just can't see how you're not interested.                    & Neu.     & Neu. & Neu.    & Neu.    \\[3.5ex]
\hline\hline
&&&&&&\\[-0.75ex]
\#2  & Yeah.                  &                                                                                                                                                       & Fru.   & \red{Neu.} & Fru. & Fru. \\[1.75ex]
\hline\hline
&&&&&&\\[-1.25ex]
\#3  &                        & God, I don't get it. you know the first time we came here, you said it was the best night of your life?                                               & Neu.     & Neu. & Neu.    & Neu.    \\[3.5ex]
\hline\hline
&&&&&&\\[-1.25ex]
\#4  &                        & And last year, I remember distinctly you said, you were so \blue{excited} to get here that you don't remember you stubbed your toe until we were in the car. & Neu.      & \red{Exc.} & \red{Exc.}    & Neu.    \\[4.5ex]
\hline
\end{tabular}
\end{table}

\section{Conclusion}
In this paper, we develop a series of BERT-based models to model emotion dynamics in conversation.  Two basics, a flat-structured and a hierarchically-structured BERT, are proposed to model the preceding utterance information and the direct dependencies in intra-interlocutors and inter-interlocutors.  More importantly, a  spatial-temporal-structured BERT is proposed to specifically distinguish emotional influence among interlocutors, so that we can effectively capture the emotion dynamics.  We conduct extensive experiments on two popular ERC datasets and demonstrate that our proposed BERT-based models can significantly outperform the SOTA baselines.  Detailed ablation study and case study have provided to verify our observations.

\bibliographystyle{plain}
