{'fraction_non_alphanumeric': 0.03463580882935722, 'fraction_numerical': 0.0072124910834588255, 'mean_word_length': 5.001189060642092, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Neural Text Classification by Jointly Learning to Cluster and Align

Distributional text clustering delivers semantically informative representations and captures the relevance between each word and semantic clustering centroids. We extend the neural text clustering approach to text classification tasks by inducing cluster centers via a latent variable model and interacting with distributional word embeddings, to enrich the representation of tokens and measure the relatedness between tokens and each learnable cluster centroid. The proposed method jointly learns word clustering centroids and clustering-token alignments, achieving the state of the art results on multiple benchmark datasets and proving that the proposed cluster-token alignment mechanism is indeed favorable to text classification. Notably, our qualitative analysis has conspicuously illustrated that text representations learned by the proposed model are in accord well with our intuition.


Introduction
Text classification, as an extensively applied fundamental cornerstone for natural language processing (NLP) applications, such as sentiment analysis [34], spam detection [13] and spoken dialogue systems [22; 8], has been widely studied for decades. In general, almost all NLP tasks can be cast into classification problems on either document, sentence, or word level. Here we are focusing on the means of it in a narrow sense, i.e., given a sequence of tokens with arbitrary length, predicting the most likely categorization it belongs to.
Considerable compelling neural approaches to the text classification task have empirically demonstrated their remarkable behaviors in recent years, to whom how to orchestrate and compose the semantic and syntactic representations from texts are central. Much of the work concentrated on learning the composition of distributional word representations [25; 27; 5] for categorization, wherein plenty of deep learning methods have been adopted, such as TextCNNs [14], RCNNs [17], recurrent neural networks (RNNs) [21], FastText [12], BERT [6], etc. Most of them learn the word representations by firstly projecting the one-hot encoding of each token through a pretrained or randomly initialized word embedding matrices to acquire the dense real-valued vectors, and then feed them into neural models for classification.
These methods, however, have only exploited the low-dimensional semantic representations for each sample text in a supervised way. Some argued that unsupervised latent representations such as topic [10; 24; 18] or cluster modeling [4; 38; 31; 7] mined by latent variable models may be of benefit. [4] maintained that word clustering could deliver the useful semantic information by grouping all words in the corpus and can thus promote the classification accuracy. Moreover, [36] incorporated the neural topic models with Variational Autoencoder (VAE) [16] into the classification tasks so as to discover the latent topics in the document level and encode the co-occurrence of words with bag-of-words statistics.
Learning such corpus-level representation can administer to the enrichment of more globally informative features and is thus favorable to the task performance. There are plenty of works adopting VAE for learning these latent variables to boost the text classification performance [33; 2; 28]. Nevertheless, there remain problems that we cannot directly treat the sampled latent space of VAE for clustering centroids since there is no mechanism to modulate the representation of different samples towards different mean and variance for a better discrimination purpose under the Gaussian distribution assumption [19]. [29] and [19] alleviate these issues by minimizing the distance between the learnable latent representation from latent variable models and the clustering centers generated from statistical clustering approaches.
Grounding on this, we design an ad hoc Clustering-Enchanced neural model (hereafter CluE) that jointly learns the distributional clustering and the alignment between the domain-aware clustering centroids and word representations in the Euclidean hidden semantic space for text classification, with the vector space assumption that words with similar meanings are close to each other [26]. Instead of directly treating the latent variables as the clustering centroids, we employ a co-adaptation strategy to minimize the difference between the hidden variables and trainable clustering centroids initialized by traditional clustering algorithms with soft alignments.
In the present work, we propose the cluster-token alignment mechanism by assigning relevance probability distribution of clusters to each token, indicating how likely it is that tokens are correlated with each cluster center. In which clustering centroids are co-regulated with learned latent variables and can be regarded as the domain-or task-specific feature indicators.
Our work illustrates that jointly adapting the clustering centroids and learning the cluster-token alignment holds the promise of advancing the text classification performance by incorporating the clustering-aware representations. Our key contributions are: • to empirically and visually demonstrate that the proposed model could surprisingly deliver visuallyinterpretable text representations for text classification (as fig. 4). • to show that our clustering-token interaction mechanism could apparently capture semantic meanings, including the relevance alignment between clusters and input tokens. • to confirm that our joint learning model eclipses the prevailing baseline models and achieves state-of-the-art results on classifying both short and long texts.

Learning to Cluster and Align
We propose a clustering-enhanced architecture CluE for text classification (see fig. 1), consisting of two main components: a cluster co-adaptation module for refining clustering centroids (Sec. 2.1) and a cluster-enhanced classifier model for categorization (Sec. 2.2).
We denote the input sequence of words as w = {w 1 , w 2 , · · · , w T } with the length of T , the corresponding one-hot representation of labels as y, its tf-idf feature as x. To project the discrete word sequences into dense word representations as inputs, we define the word embedding matrices E ∈ R V ×D where V is the vocabulary size of the corpus, and D is the dimension of word embeddings.

Distributional Clustering with Hidden Variables
Cluster co-adaptation components (left in fig. 1) leverage latent variable models involving autoencoder (AE) and VAE to conduct the encoding and reconstruction process, simultaneously using the latent representation to regulate the trainable clustering centroids. Typically, we take VAE for the latent variable generation, namely Clustering-VAE, (CVAE), for further explication.
CVAE encodes the tf-idf features x ∈ R V for each word sequence into a latent variable word representation z ∈ R D , then resorts to a modulation mechanism by forcing z to learn together with cluster centers, concurrently reconstructing the original input as x ∈ R V from z.
We denote the trainable cluster centroids consisting of K cluster centers {c k ∈ R D |k = 1, 2, · · · , K}, where the cluster centroid parameters are initialized with K-means or Gaussian Mixture Models (GMM) trained on the pretrained word representations.
Clustering Co-adaptation We apply two-layer feed-forward fully-connected connections with non-linearity, denoted f , to project the tf-idf features x into the mean µ µ µ ∈ R D and variance σ σ σ ∈ R D under a prior p(z) of Gaussian distribution N (µ µ µ, σ σ σ).
where ∼ N (0, I) represents ∈ R D is sampled from the standard Gaussian distribution N (0, I), denotes the element-wise product.
After sampling z following the Gaussian prior p(z) with the reparameterization trick, we minimize the distance q ik between the i-th sample's latent encoding z i and each cluster centroid c k . Here we employ a Student's t-distribution kernel following [32] as the distance metric.
where α represents the freedom degree of Student's t-distribution (we set α as 1 in our experiments). q ik can be considered as the probability assigning the i-th sample to the k-th cluster.
The auxiliary target distribution p i is defined to learn the high confidence assignments [32]. We denote r ik as the squared q ik divided by the total occurrence of each cluster k and p ik as the normalized counterpart among all clusters: The objective of clustering co-adaptation is defined as a KL divergence between the the Student's t-distribution kernel based distance q i and the auxiliary target distribution p i : Feature Reconstruction Meanwhile, the original feature input is reconstructed as x using two feed-forward layers g, i.e., x = g(z). The reconstruction component objective L recon is defined as the mean squared error (MSE) between the original features and the reconstructed ones: Besides, CVAE employs variational inference to approximate the posterior distribution q(z|x) and force it to approach the prior p(z). The objective of KL diveregence L kld is defined as: where µ µ µ j and σ σ σ j represent the j-th element of mean and variance vectors respectively. Refer to [16] for detailed derivations.

Clustering-token Interaction
We will further describe the process of clustering-token interaction (the right part in fig. 1). Given word sequences w with length T , we firstly project the discrete word indices through the embedding matrices E to acquire the dense representation H e as the inputs to the clustering-token interaction module. Afterward, a single-layer bi-directional Long Short-Term Memory (LSTM) [11] network to encode the contextual information of tokens into H e , wherein the output states of forward and backward LSTMs are concatenated at each time step. The dimension of the LSTM hidden state was set to D/2, thus we get H ∈ R T ×D after concatenation.
The clustering-token interaction module is composed of a stack of N identical layers, of which each layer has two sublayers, namely clustering-token global alignment and feature aggregation sublayers.
We supplement a residual connection [9] around them followed by layer normalization [3] for each stack.
Cluster-token Global Alignment The clustering-token alignment sublayer can be described as the alignment score a ∈ R K×T between the k-th cluster c k and the t-th word representation h t in each sequence: We adopt the alignment score function as in [23], which can be interpreted as the content-based relevance function. It measures the relevance between each cluster and each input token: where W a ∈ R D×D denotes trainable parameters. Dot alignment score is used in our experiments.

Feature Aggregation
The feature aggregation sublayer attends to different dimension of word representations w.r.t each cluster centroids. We refine the t-th original representation h t using the corresponding cluster-word alignment score a kt , k = {1, · · · , K} via an Kronecker product.
where u t ∈ R T ×D denotes the aggregated output features, W d ∈ R KD×D is the trainable weight matrix for dimension reduction, ⊗ is the Kronecker product. Fig. 2 illustrates the interaction between a kt (upper-left) and h t (lower right corner). So far, we maintain the idea that a kt calculated from previous sublayer measures the relevance between each cluster (i.e.,matrix column {c 1 , · · · , c K } in the figure) and word tokens(i.e., w t in the figure). It can be further interpreted that the resulting matrix in the middle of the figure reveals the relation between cluster and embedding space.
Classification We define the final representation of stacked clustering-token interaction layers as S = {s t |t = {1, 2, · · · , T }}. Firstly we add a residual connection from after the bi-LSTMs followed by a layer normalization, and pass it through a dense layer with a non-linearity. Then a max-pooling layer is employed to get the final text representation o ∈ R D , with a linear projection to output the final classification logitsŷ.
where W O ∈ R D×D and W p ∈ R D ×|C| are trainable parameters, D denotes the hidden dimension, |C| is the number of classes. L cls represents the cross entropy loss between label y of one-hot encoding and the output logitsŷ for the classifier.

Experiment Settings
Our experiments are conducted on the task of text classification using four different benchmark datasets for short and long text classification separately. For comparison, we report the performance of a bunch of strong baseline models w.r.t the prediction accuracy on the test set. Code in TensorFlow [1] will be available after the double-blind review (for reviewers, please check the attached materials). We adopt the title texts from AG's News § , DBpedia § , Amazon Reviews § and Yahoo! Answers ‡ text data for short text classification. Meanwhile, content fields from AG's News § and DBpedia § , as well as IMDB movie reviews ¶ and R8 || datasets are utilized as long texts ** .

Models
Comparison Models We test mainstream baseline models including TextCNN † , BiLSTM, RCNN [17] and AttBiLSTM [20]. 6 and 12 Transformer [30] encoder layers followed by a maxpooling layer are implemented. Topic Memory Network (TMN) † [36] that combines neural topic model and memory network to tackle topic modeling and classification jointly were experimented. To further compare with the recently prevailing Text Graph Convolutional Networks † (TextGCN) [35], which builds corpus-level graph using word co-occurrences and document word relations, we conduct experiments on the source code. Additionally, we reproduce a text-level GCN based on the dependency parsing graph for each input sample, similar to [37].   [35].

Proposed Models
Hyperparameter settings Hyper-parameters are tuned with grid search on both short and long texts. We use the 300-dimensional pretrained Glove embeddings ‡ to initialize the word embedding matrix and clustering centroids. The maximum sequence length is set to 20 for all short texts except Yahoo dataset with 28 and the counterpart for long texts are 120 for AG's News and DBpedia and 200 for Yahoo! Answers and Amazon Reviews dataset. For the optimization, we use Adam optimizer [15] with the learning rate 1e-3, batch size of 512 and 64 for long and short inputs, respectively. The training process is set as a maximum of 10,000 steps with early stopping patience of 30 steps. Gradients are clipped when the L2 norm is more than 5. To avoid model over-fitting, we set the dropout rate as 0.2 during training. As shown in the table, CNN-dominant models, i.e., TextCNNs, perform steadily well on all datasets while LSTM-based models including Bi-LSTM, RCNN, and AttBiLSTM achieve better results on long texts. This is consistent with our initial intuition.

Quantitative Results
The performance of prevailing GCN models, i.e., TextGCN and Text-level GCN, matches that of LSTM-or CNN-dominant methods. However, TextGCN suffers from the lack of transferability and memory-efficiency, making it difficult to apply corpus-level TextGCNs on large datasets.
It is empirically shown that combing topic networks and memory networks to construct TMN models dramatically slows down the training process and can not be afforded for large short text datasets, even not to mention long texts. Notably, '-' symbols in table 2 represent the inacquirability of experimental results. Specifically, the overlong time costs (e.g., ≈4600 seconds per training epoch out of maximum 800 epochs on single NVIDIA Titan RTX GPU for Amazon short datasets) for TMN and memory/running errors in the corpus-level graph construction for TextGCN when handling large volumes of data. Table 2 illustrates the comparison between our CluE models with different settings for classifying AG's News short texts. Our CluE-baseline, CluE-CAE and CluE-CVAE models achieve 2.31%, 2.44% and 2.6% improvement on the test accuracy compared with CluE-baseline without clustering-token interaction layers, i.e., bi-LSTM (see fig. 1 for schematic intuition). Impact of Cluster Numbers It can be seen from fig. 3a that the model performance remains stable when the range of layer number is within 1 to 5, and then decreases afterward when classifying long texts. In contrast, the curve of short texts initially shows an increasing trend and reach a plateau from 4 to 8. It is observed that the model performance is superior when the number of clusters is approaching to that of classes. In our optimal settings of CluE-CAE and CluE-CVAE, the optimal cluster counts are both 4, which is exactly the class number of AG's News. Such curves could match our intuition that clustering mechanisms might learn the semantic meanings beneficial for classification to some extent. Fig. 3b witnesses the influence trend of layer numbers. We find that models with three layers reach their acme on test performance for short texts whilst the test accuracy with layer numbers range from 3 to 7 remains a steady stage for long texts. It shows that models with layer number 3 can get superior results. We recommend readers not to increase the depth of layers too much according to the law of Occam's razor. trained word embeddings (drawn as blue points in (c)) or latent hidden variables z (drawn as brown points in (d)) using t-SNE on AG's News dataset.

Qualitative Analysis
To illustrate the impact of CluE-CVAE models, we will display visualizations on AG's News test set unless mentioned otherwise. Main model settings used for visualization are as follows: clustering number 4, clustering-token interaction layer number 4, scaling factors λ 1 = λ 2 = λ 3 = 1.

Text Representation Visualization
In the proposed CluE-CVAE model, sentence embeddings are acquired after the max-pooling layer (upper-right in fig. 1). We plot the sentence embedding together with its corresponding classes into a scatter graph in fig. 4. It is dramatically vivid that sentence representations from different label classes are apparently partitioned into four distinct clusters and well separated from each other, hugely validating the ideas that our CluE models deliver the better discrimination between different classes. Meanwhile, such orthogonal clustering groups could provide more informative meanings to classifiers and thus boost the classification performance. Notably, we can observe from the plot that the data points near the intersection between the region of "Business" (in yellow) and "Sci/Tech" (in green) have plenty of mixed points. We make an extrapolation that this is due to the disambiguity of samples from these two classes. We will testify this at the end of this section.
Clustering Centroid Visualization We plot the scatter graph of learned clustering centroids with trained word embeddings ( fig. 3c), and those with all hidden variables of each input texts ( fig. 3d). We find that word embeddings after training circumfuse cluster centroids and have a high density around clustering centers. This underpins the proposed clustering-token interaction mechanism, showing that word representations move towards clustering centers to be more classifier-discriminative and class-informative in the compact cluster-token high-dimensional vector space, though no direct minimization mechanism in between were conducted.
Fig 3d witnesses that cluster centers are located at near the center of the multi-variance Gaussian distribution that latent variables z obey, indicating that our KL divergence loss (eq. 4) for minimizing the distance between hidden variables and cluster centers works well.
Cluster-token Alignment Visualization It is evident from the heatmap visualization ( fig. 6) that the relevance for clusters progressively increases or decreases with the depth increase of layers, finally focusing on a single cluster to form the final sentence representations ( fig. 4).   Figure 6: Visualization of outputs from each clustering-token alignment sublayer for example sentences "technical hitch delays russia space station launch reuters" and "experts optimistic about shuttle flight". The x-axis and y-axis of each plot correspond to tokens and clusters respectively. Each pixel shows the relevance weight α kt between the k-th cluster (row) and t-th token (column) (see eq. 7). Fig. 5 displays the confusion matrix between the golden and predicted labels, in which samples of label "Business" (hereafter 'B') and "Sci/Tech"(hereafter 'S') are mis-predicted in the most cases.

Error Analysis
To unveil this, we go through the wrongly predicted samples and attribute this to three reasons: true mispredictions, mislabels, or ambiguities between these two classes.
Firstly, we observe that samples involving tech company or product names could be predicted as 'S' by mistake, such as "google puts desktop search privacy up front", "amazon sues spammers for misleading consumers", "ibm quitting computer business". Some are labeled by mistake but predicted correctly, such as: • labeled 'B' but predicted as 'S': "fcc mulls airborne mobile phone use", "web based kidney match raises ethics questions". • labeled 'S' but predicted as 'B': "google founders selling off stock", "ibm buys two danish services firms", "'microsoft signs two indian deals"'.
However, there also exist plenty of ambiguous samples, like "google targets software giant", "google puts desktop search privacy up front", "red hat replaces cfo" which are labeled as 'B' in the dataset.
This exactly matches our previous assumption, according to fig. 4. It can be further inferred that text representations learned by our models could surprisingly be consistent with our intuition in terms of the semantic vector space, validating the impact of the proposed models.

Conclusion
The proposed CluE architecture enjoys both the advantage of latent variable models and clusteringtoken interaction mechanisms without introducing additional knowledge from outside, which allows for attending to semantic meanings from both tokens and their corresponding embedding elements. It overshadows the performance of prevailing baseline models and empirically proves that the proposed clustering-token interaction mechanism could be of benefit for achieving informative sentence embeddings. In the future, we will expand our experiments on the other NLP tasks such as natural language inference and neural machine translation.

Broader Impact
This work has the following potential positive impact on society: • Leveraging the proposed clustering enhanced method, user-generated text data can be analyzed and categorized to interpret social behaviors of users, such as rumor detection, spam detection, hate-speech detection, and sentiment analysis. In addition, these cluster-based analyses can also be embedded into recommender systems for the purpose of user-profiles and recommendations. • Latent variable models and clustering mechanisms have been leveraged to boost the prediction accuracy on text classifiers, including intent detection, Twitter hashtag prediction, sentiment analysis, etc. Latent variable models are shown to be effective in enriching representations in an unsupervised way. • Proposed cluster-token interaction mechanism could learn more informative and meaningful text representations as visualized in the paper, which can be adopted in other relevant applications such as natural language inference, topic modeling, etc. • Our methods connect between the neural clustering approaches and text classification tasks, which may be widely applied in the industry. Besides, other prevailing methods could also borrow this idea, like enriching BERT families with similar methods. • This clustering-enhanced method can be transferred into semi-supervised learning in practice by providing pseudo labels by assigning learned text representations to the closest cluster of which label is defined as the mode. This may reduce the requirement of amounts of golden labeled data and thereby curtail the cost.
At the same time, this work may have some negative consequences because there is no mechanism to enforce clustering centroids to be differential and far apart with each other, which can be seen from our plots. The performance may be further promoted by handling this problem.
It should be noted that the failure of the system could result in the wrong prediction of classifications, which may further lead to accumulative errors in downstream tasks, such as spoken dialogue systems.
The current study may suffer from implicit biases in NLP systems: • the demographic/representative bias that might be learned implicitly from a certain domain. Take our experimental AG's News dataset, for example, texts containing technical company names may be possibly predicted into "Sci/Tech" categories. • the implicit bias from word embeddings pretrained on Wikipedia. For example, family-or genderrelated topics occurred more about women. Although Wikipedia is a major dataset used for pretraining embeddings, it has inevitable biases with crowdsourcing.
As for the ethical aspect, our initialized cluster centroids might leverage some implicit gender-and ethnicity-relevant bias learned from pretrained embeddings, which should be checked when applying our methods into industrial applications.