1. Introduction
Text classification is now a standard tool for measurement tasks in political science across substantive domains (Justin and Stewart, Reference Justin and Stewart2013; Lucas et al., Reference Lucas, Nielsen, Roberts, Stewart, Storer and Tingley2015; Roberts, Reference Roberts2016; Goet, Reference Goet2019; Bestvater and Monroe, Reference Bestvater and Monroe2023; Bosley et al., Reference Bosley, Kuzushima, Enamorado and Shiraito2025). However, a common problem with current models is that they struggle to effectively capture context-dependent concepts such as toxicity, sentiment, and emotion (Parekh, Reference Parekh2012; Sellars, Reference Sellars2016). Such limitations arise from their inability to selectively focus on the most relevant words and the inattention to word order. This is particularly true for bag-of-words and dictionary-based methods (Siegel and Badaan, Reference Siegel and Badaan2020; Wasow, Reference Wasow2020; Jacobs et al., Reference Jacobs, Matthews, Hicks and Merkley2021; Osmundsen et al., Reference Osmundsen, Bor, Vahlstrup, Bechmann and Petersen2021; Osnabrügge et al., Reference Osnabrügge, Hobolt and Rodon2021). Even somewhat more sophisticated models, such as text embeddings,Footnote 1 face challenges when dealing with multiple meanings of words in different settings (Alrababa’h et al., Reference Alrababa’h, Marble, Mousa and Siegel2021; Bestvater and Monroe, Reference Bestvater and Monroe2023). This is because they rely on static representations and may not capture the nuances of how a word’s meaning shifts in different contexts. For instance, consider the word ‘left’ in the two sentences below: the context gives ‘left’ different meanings, something missed by all models using static representations.
Sentence 1: The left advocates for more government intervention in the economy to ensure equity and social welfare.
Sentence 2: After the debate, he left the stage.
Recent advancements in transformer-based language models offer a promising solution to this issue (Vaswani et al., Reference Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser and Polosukhin2017). These models leverage transfer learning, enabling efficient adaptation of pre-trained language representations to new tasks with minimal labeled data. Transfer learning, as implemented in transformer-based models, enables efficient knowledge transfer by first training on vast, unlabeled text corpora before fine-tuning on domain-specific labeled datasets. Such approach significantly enhances model performance while reducing data and computational requirements, making advanced natural language processing (NLP) techniques more accessible to applied scholars.
Although prior studies have applied transformer-based models to political science tasks, they primarily focused on specific applications or implementations rather than elucidating the underlying mechanisms. For instance, Bestvater and Monroe (Reference Bestvater and Monroe2023) used BERT for stance detection, Widmann (Reference Widmann2024) employed ELECTRA to analyze emotional appeals in German political discourse, Milliff (Reference Milliff2024) used MuRIL to measure appraisals in oral violence-exposure histories, and Licht et al. (Reference Licht, Abou-chadi, Barberá and Hua2025) measured anti-elite rhetoric across languages. However, these studies offered limited justification for the adoption of transformer-based language models and provided minimal discussion of the classification pipeline. On the other hand, Laurer et al. (Reference Laurer, van Atteveldt, Casas and Welbers2024) presented transfer learning in the context of BERT-NLI, which can be applicable to classification tasks but requires additional reformulation of the hypotheses to pair with the text and match the labels. Meanwhile, Timoneda and Vallejo Vera (Reference Timoneda and Vallejo Vera2025) provided a valuable comparison of performance across different transformer architectures including BERT, RoBERTa, DeBERTa, and XLM-R, but did not delve into how these models actually work internally. Importantly, all the articles mentioned above omitted the explanation of the functional integration of the attention mechanism and pre-trained embeddings in facilitating transfer learning which contributes to the effectiveness of these models. Given the relatively rare uptake of this method in the field despite their clear advantages, what is needed is a detailed explanation of transformer-based language models for a standard classification tasks with a simple application for applied scholars to build from.
To fill this gap, this article provides a conceptual overview of the pretrain-finetune paradigm (PFP), offering an accessible explication of its methods, applications, and limitations. Through a step-by-step breakdown of how these models work internally, I make this technique more accessible to applied researchers without extensive technical backgrounds. I further demonstrate the practical implementation of the PFP through an application to toxicity detection in social media discourse, showcasing how these models can effectively capture nuanced concepts that traditional approaches often miss. The accompanying tutorial and code examplesFootnote 2 further bridge the gap between theoretical understandings and practical implementation, enabling researchers to adopt these powerful tools with greater confidence and clarity about their inner workings.
In Section 2, I provide an overview of current methods used in the field of political science and discuss their limitations. I show that while there are a few papers that used the PFP approach (Bestvater and Monroe, Reference Bestvater and Monroe2023; Wang, Reference Wang2024, Reference Wang2023b; Burnham, Reference Burnham2025; Laurer et al., Reference Laurer, van Atteveldt, Casas and Welbers2024; Timoneda and Vallejo Vera, Reference Timoneda and Vallejo Vera2025), many published works using supervised learning still do not. To motivate the PFP, I then outline the limitations of the most widely used methods for political science domain-specific text analysis. Section 3 is dedicated to a comprehensive overview of the PFP focusing on the inner workings of the attention mechanism, while Section 4 walks through the process of using the PFP in details with an application to identify toxic language in Twitter conversation threads. The article concludes with a discussion on the limitations inherent in the PFP and suggests potential avenues for future research in this domain.
2. Current text classification approaches
Over the past two decades, quantitative text analysis in political science has evolved substantially—from early dictionary-based and topic-modeling approaches to the contemporary use of contextualized embedding models. This development reflects a broader methodological trajectory: initial efforts to identify political concepts relied on word counts and dictionary-based rules (Siegel and Badaan, Reference Siegel and Badaan2020; Osnabrügge et al., Reference Osnabrügge, Hobolt and Rodon2021), followed by probabilistic topic models (Catalinac, Reference Catalinac2016; Roberts et al., Reference Roberts, Stewart and Tingley2019), and later by neural feature extraction models such as word embeddings and, more recently, transformer-based architectures. The release of accessible software like quanteda (Benoit et al., Reference Benoit, Watanabe, Wang, Nulty, Obeng, Müller and Matsuo2018) further democratized text-as-data research by lowering technical barriers for applied researchers and enabling large-scale, reproducible text measurement.
To contextualize the discussion, imagine we are interested in measuring toxicity from some text corpus that contains the two example sentences below.Footnote 3
Example 1 (E1): Stop the evil yellow invasion from the Chinese.
Example 2 (E2): The flowers are yellow.
The simplest approach is to use a standard dictionary method. The procedure entails examining the input text for the presence of specific derogatory terms that have been pre-defined by scholars (Siegel and Badaan, Reference Siegel and Badaan2020; Wasow, Reference Wasow2020; Jacobs et al., Reference Jacobs, Matthews, Hicks and Merkley2021; Osmundsen et al., Reference Osmundsen, Bor, Vahlstrup, Bechmann and Petersen2021; Osnabrügge et al., Reference Osnabrügge, Hobolt and Rodon2021). Should these specific terms be detected within the input text, it is classified as toxic. For instance, (Siegel and Badaan, Reference Siegel and Badaan2020) used a dictionary containing anti-Shia slurs to measure sectarian hate speech on Twitter. I use a similar application to detect toxic language on Twitter to demonstrate the effectiveness of the PFP in Section 4.
While dictionary-based methods offer speed, transparency, and ease of implementation, they also have important limitations for classifying toxic language. First, dictionaries rely solely on explicitly pre-defined terms, which may overlook more sophisticated forms of toxicity, such as coded language, or manipulative speech. Second, due to the over-reliance on explicit terms (Barberá et al., Reference Barberá, Boydstun, Linn, McMahon and Nagler2021), dictionaries are inadequate in addressing the complexity of context-dependent terms, which might be deemed toxic or non-toxic based on their usage within a given context, such as the word ‘yellow’ in E1 and E2. Consequently, the inclusion or exclusion of ‘yellow’ in the dictionary leads to mis-classification of one of the two sentences.
A step forward came with bag-of-words (BOW) representations, which convert text into numerical vectors (i.e., text embeddings) by counting the occurrences of words or tokens from the input text, regardless of the token order (Justin and Stewart, Reference Justin and Stewart2013; Vries et al., Reference Vries, Schoonvelde and Schumacher2018; Barberá et al., Reference Barberá, Casas, Nagler, Egan, Bonneau, Jost and Tucker2019; Beltran et al., Reference Beltran, Gallego, Huidobro, Romero and Padró2021; Cocco and Monechi, Reference Cocco and Monechi2022). For example, (Cocco and Monechi, Reference Cocco and Monechi2022) used BOW along with a random forest classifier to measure populist content in party manifestos. (Beltran et al., Reference Beltran, Gallego, Huidobro, Romero and Padró2021) transformed Spanish tweets using BOW with logistic regression to examine the differences in how male and female politicians communicate with the public on social media.
Similar to dictionaries, despite its speed and straightforward implementation, BOW is unable to capture multiple meanings of words due to its lack of context sensitivity. The word ‘yellow’ from E1 and E2 would again be treated as the same using a BOW model. Moreover, word order is not factored in when generating numerical vectors, which makes BOW struggle to capture negative meanings. E3 would be numerically equivalent to E4 when using uni-grams in BOW. Such inability becomes particularly problematic in applications like toxicity detection.
Example 3 (E3): I do like Harris and not Trump.
Example 4 (E4): I do not like Harris and Trump.
A more advanced method of text representation is to use static word embeddings (D’Sa et al., Reference D’Sa, Illina and Fohr2020; Alrababa’h et al., Reference Alrababa’h, Marble, Mousa and Siegel2021; Esberg and Siegel, Reference Esberg and Siegel2023). To generate numerical representations in a continuous vector space and take advantage of the surrounding words, word2vec was introduced with the intuition that a word is defined by its neighboring words (Mikolov et al., Reference Mikolov, Chen, Corrado and Dean2013). For example, (Esberg and Siegel, Reference Esberg and Siegel2023) converted tweets into numerical vectors using word2vec to identify words that were semantically similar to their seed words in the data. Using word2vec with a naive Bayes classifier, (Alrababa’h et al., Reference Alrababa’h, Marble, Mousa and Siegel2021) identified anti-Muslim content in 15 millions tweets from British soccer fans.
The key limitation of word2vec and related models is that they generate static numerical representations. In other words, the numerical vector representing a word is fixed during training. Therefore, it is unable to handle the complexity of context-dependent words like ‘yellow’ in E1 and E2 when their context is different from training. The context provided by neighboring tokens is also limited by a window of tokens on the left or right, making it inadequate to connect two tokens that are further away from each other.
In response to the constraints in prior models, transformer-based language models were introduced to effectively manage the intricacies inherent in linguistic nuances (Vaswani et al., Reference Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser and Polosukhin2017). They address three key challenges in prior text representation methods.
First, they produce dynamic embeddings, allowing the numerical representation of each word to depend on all other words in the same sequence. This enables the model to differentiate context-dependent meanings—for example, ‘yellow’ in E2 is associated with ‘flowers,’ while in E1 it acquires a negative connotation through its connection with ‘Chinese,’ ‘evil’ and ‘invasion.’
Second, transformers incorporate word order through positional encodings—numerical vectors added to each token embedding that represent its position in the sequence. By combining semantic and positional information, transformers capture both meaning and structure, distinguishing between sentences such as E3 and E4.
Third, unlike static word embeddings such as word2vec, which rely on a fixed local context window, transformers can model global dependencies across an entire text sequence.Footnote 4 Earlier architectures such as recurrent neural networks (RNNs) and long short-term memory (LSTM) models partially addressed local-context limitations by processing tokens sequentially and retaining prior information. Bidirectional LSTMs extended this capability by incorporating context from both directions, improving sequence-labeling tasks like named entity recognition (NER) and part-of-speech (POS) tagging. However, because these models process tokens one at a time, they are prone to losing information over long sequences.
Transformer encoders overcome such constraint through multi-head self-attention, which allows each token to attend to all others in the sequence simultaneously. Each attention head learns a different type of linguistic relationship, producing context-specific embeddings that reflect both local and global meaning. This attention-based computation, rather than a larger context window alone, is what gives transformers their flexibility and superior representational power. Moreover, transformers produce context-rich representations that are resilient to linguistic variability, including typographical errors and nonstandard spellings common in social media data (Shawky et al., Reference Shawky, ElKaffas and Guirguis2024).
However, while transformer-based models have become dominant in NLP, they may not be universally optimal. RNNs and LSTMs still perform competitively on certain tasks—particularly sequence-labeling tasks like POS tagging and NER—and are less computationally demanding. For instance, models such as Flair have outperformed some transformer encoders on NER benchmarks (Yamada et al., Reference Yamada, Asai, Shindo, Takeda and Matsumoto2020). Thus, model selection should depend on the specific research goal, data availability, and computational constraints. In this article, transformer encoders were chosen because the primary task is context-dependent text classification, where capturing long-range semantic relationships and interpretive nuance is more critical than token-level prediction.
Despite the exceptional efficacy of transformer-based language models in text analysis (Park et al., Reference Park, Vyas and Shah2022; Karl and Scherp, Reference Karl and Scherp2023), their adoption within the field of political science remains limited. With a search of 2020-2025 volumes of the American Political Science Review, the American Journal of Political Science, and the Journal of Politics for all articles that used machine learning of texts to create measures of latent concepts (Park and Montgomery, Reference Park and Montgomery2025), 22 papers used topic modeling, 12 papers used dictionary-based methods, and 33 papers used some type of supervised learning for text analysis.Footnote 5 Among the 33 papers that used supervised learning, only eight leveraged transformer-based language models with seven implementing some degree of fine-tuning and none engaging in domain-adaptive pre-training (DAPT) (Gururangan et al., Reference Gururangan, Marasović, Swayamdipta, Lo, Beltagy, Downey and NA2020). Such limitation may partly be attributed to a lack of explication of the mechanisms of these models and misconceptions about the amount of labeled data and computational resources these methods require. In Section 3, I offer a comprehensive elucidation of the PFP focusing on the attention mechanism. For reproducibility, all computation in this article was conducted on Google Colab with an A100 GPU. All PFP models used in this article can be found on HuggingFace Hub.Footnote 6 Python code are provided in the replication archive and the online tutorial.Footnote 7
3. The pretrain-finetune paradigm
In this section, I first offer a detailed overview of the transformer encoderFootnote 8 with an emphasis on the attention mechanism and its integration with embedding generation. Then, I discuss the pre-training phase, during which the model acquires general linguistic patterns, followed by the fine-tuning stage, where task-specific data further improves the model’s classification performance. Finally, I provide practical guidelines for scholars to implement the PFP with different levels of computational resources or available data at hand.
3.1. The transformer encoder
A transformer encoder, as shown in Figure 1, takes text embeddings as the input and outputs contextualized embeddings of the same length as the input sequence. Unlike the input embeddings, each output embedding contains not only information about the individual token, but also its relationship with every other token in the same sequence. Sections 3.1.1 to 3.1.4 examine each part in Figure 1 in details.
Transformer encoder architecture.

Figure 1 Long description
Flow diagram showing how input text is converted into contextualized embeddings by a transformer encoder. The input text is tokenized, passed through an embedding layer, combined with positional encodings, and then processed by a transformer encoder containing a multi-head self-attention layer and a feed-forward neural network layer.
3.1.1. Transformer encoder input embedding generation
Consider E1 again. As shown in Figures 1 and 2, the model first tokenizesFootnote 9 the input sequence into individual tokens. Then it maps the tokens into input IDs according to their position in the vocabulary containing all possible words in the training corpus. At this stage, both ‘the’s have the same input ID since they occupy the same position in the vocabulary. Then, the model takes the input IDs and maps them into vectors of size 512Footnote 10 through an embedding layer which acts as a look-up table to get the initialized input embeddings (Vaswani et al., Reference Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser and Polosukhin2017). These corresponding embeddings can be loaded from other previously pre-trained models or initialized randomly,Footnote 11 and the embedding layer is often the first trainable layer in a transformer-based language model. Notice that at this stage, the same word is always mapped to the same embedding without any contextual information from surrounding words, similar to static word embedding models.
Input embedding generation to the transformer encoder. numbers are for illustration purposes only.

Figure 2 Long description
Step-by-step diagram using the sentence ‘Stop the evil yellow invasion from the Chinese’ to illustrate how input tokens are converted into input IDs, token embeddings, and positional encodings. The token embeddings and positional encodings are added together to produce an 8-by-512 encoder input embedding matrix. Numbers are illustrative.
The next part of the embedding layer is the calculation of positional encodings, which are also of length 512 for each token and used by the model to keep track of their positions in the sequence and how distant they are from each other.Footnote 12 The token embeddings shown on the top in Figure 2 and positional encodings shown in the middle are summed together to construct the input embeddings to a transformer encoder illustrated in Figure 1.
3.1.2. The self-attention mechanism
The core of the transformer encoder is the multi-head self-attention layer. Before covering multi-head self-attention, I first discuss the (single-head scaled dot-product) self-attention mechanism without introducing trainable parameters to build intuition.
Consider E1 and E2 again. The mere syntactic arrangement fails to capture the polysemous nature of the word ‘yellow.’ For a nuanced and context-rich representation of the word in E1, it is necessary to establish a semantic linkage between ‘yellow’ and contextual markers such as ‘evil’ or ‘Chinese.’ In the parlance of transformers, the word ‘yellow’ should pay attention to other surrounding words, creating connections that vary in strength based on context. The key advantage of transformers is their ability to not only estimate word positions in a semantic space, but also the relative importance of a given word in shaping the meaning of other words (Vaswani et al., Reference Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser and Polosukhin2017). This is achieved through the incorporation of the scaled dot-product self-attention mechanism.
To disentangle the mechanism mathematically, imagine I want to calculate the contextualized embeddings incorporating self-attention scores for E1, as illustrated in Figure 3. The self-attention mechanism takes in an input embedding matrix
$X$ (i.e., the encoder input embedding matrix shown in Figure 2 and in the middle of Figure 1) and outputs a contextualized embedding matrix
${X^{\text{*}}}$.
${X^{\text{*}}}$ is generated using the self-attentionFootnote 13 score matrix
$A$ through:Footnote 14
\begin{equation}{X^{\text{*}}} = {\text{Self - Attention Score}}\left( X \right) \cdot X = A \cdot X = softmax\left( {\frac{{X \cdot {X^T}}}{{\sqrt d }}} \right) \cdot X\end{equation}Calculation of the self-attention mechanism. Numbers are for illustration purposes only.

Figure 3 Long description
Diagram illustrating the calculation of self-attention. An encoder input embedding matrix is multiplied by its transpose, scaled, and normalized with a softmax function to produce an 8-by-8 self-attention score matrix. This matrix is then multiplied by the original input embedding matrix to produce a contextualized embedding matrix. Example tables show token-to-token attention scores and resulting contextualized embeddings.
where:
\begin{equation*}\begin{array}{*{20}{c}}
{X = {\text{the encoder input embedding matrix, }}} \\
{d = {\text{dimensionality of the model (see footnote 10}}{\text{.)}}}
\end{array}\end{equation*} For E1, the input sequence length is 8 and the dimension
$d$ of the model and input embedding is 512,Footnote 15 which is the dimension of the encoder in the original paper that introduced transformers (Vaswani et al., Reference Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser and Polosukhin2017). As shown in Figure 3, the model first conducts dot-product matrix multiplication of
$X$ and the transpose of
$X$, and divide it by a scaling factor, usually the square root of the input embedding dimension. The resulting matrix is then passed through a softmax function for normalization, resulting in an 8 by 8 matrix where all the rows sum up to 1. The values in this resulting matrix, as shown in matrix
$A$ in Figure 3, are the self-attention scores, where they represent the strengths of the relationships between one token and another. If a particular token is not relevant to the understanding of the target token, the self-attention mechanism may assign a very low score to that position, effectively ignoring its contribution. Higher self-attention scores correspond to stronger relationships between two tokens. Intuitively, I can think of the word ‘yellow’ consisting of 0.01 Stop
$ + $ 0.03 the
$ + $ 0.15 evil
$ + $ 0.33 yellow
$ + $ 0.25 invasion
$ + $ 0.04 from
$ + $ 0.02 the
$ + $ 0.17 Chinese, which sums to 1. Different from the input embedding generation, the same token ‘the’ can have different self-attention scores when they appear multiple times in the input sequence.
To obtain the contextualized embedding matrix
${X^{\text{*}}}$ (i.e., the yellow matrix in Figure 3) from the self-attention mechanism, the model conducts another dot-product matrix multiplication of
$A$ and
$X$. Each row in the resulting matrix
${X^{\text{*}}}$ contains the contextualized embedding of the initial input sequence, where the self-attention scores and positional encodings have been incorporated into the resulting embeddings.Footnote 16
At this stage, the calculation of self-attention requires no trainable parameters. Up to now the interaction between tokens has been driven by their own embeddings. To add trainable parameters to the model, I add updatable weight matrices. Although in the simplified formulation of self-attention based on Equation 1 the model uses the same input embedding matrix
$X$ three times, in practice, each instance of
$X$ is multiplied by a distinct weight matrix
${W_Q}$,
${W_K}$, and
${W_V}$, as illustrated in Figure 4. These three weight matrices learn task-relevant linear projections of the same input sequence, each emphasizing different aspects of how tokens relate to one another. By separating the transformations this way, the model can capture multiple dimensions of contextual meaning and generate more expressive attention patterns. This operation yields the contextualized embedding matrix
${X^{\text{*}}}$ as the output.Footnote 17 In practical transformer implementations, the self-attention mechanism therefore operates not directly on the original embeddings, but on these learned projections.Footnote 18
Self-attention with trainable weight matrices
${W_Q}$,
${W_K}$, and
${W_V}$.

Figure 4 Long description
Diagram showing how trainable query, key, and value weight matrices are added to the self-attention mechanism. The input embedding matrix is projected into query, key, and value representations; query and key representations are used to calculate normalized self-attention scores, which are then applied to the value representation to produce a contextualized embedding matrix.
3.1.3. The multi-head self-attention layer
The entire process described so far is everything that happens within a module called an attention head. When using only one set of weight matrices
${W_Q}$,
${W_K}$, and
${W_V}$, it is called single-head attention. Often times, single-head attention is not enough to capture complex relationships among tokens in the same sequence. Therefore, multi-head attention is used to make the model attentive to different aspects of the tokens.
The only architectural difference for multi-head attention is that the model maintains one set of weight matrices for each attention head and then concatenates the resulting contextualized representations from all heads afterwards. Consider a transformer encoder with two attention headsFootnote 19 as shown in Figure 5. Notice that the encoder input embedding matrix is split into two smaller sub-matrices
${X_1}$ and
${X_2}$ to use as the input for each attention head. The input embedding is typically split across the embedding dimension (columns) instead of the sequence length dimension (rows).Footnote 20 Such approach allows separate sections of the input embedding to learn different aspects of the meanings of each token as it relates to other tokens in the sequence, which allows the transformer encoder to capture richer interpretations of the sequence.Footnote 21
Calculation of the multi-head self-attention with two attention heads.

Figure 5 Long description
Diagram illustrating multi-head self-attention with two attention heads. The encoder input embedding matrix is split into two submatrices, each processed through separate query, key, and value weight matrices. The two attention heads produce separate contextualized embedding matrices, which are concatenated and multiplied by an output weight matrix to produce the final multi-head contextualized embedding matrix.
Within each attention head, the model performs the same self-attention operation as shown earlier in Figure 3, producing one contextualized embedding matrix per head. Then it concatenates the output matrices, i.e., the contextualized embedding matrices, from each attention head to obtain
${X_{1\& 2}}^{\text{*}}$. To learn the optimal way to combine different output matrices from all attention heads, the model adds another trainable weight matrix
${W_O}$ before obtaining the final multi-head embedding matrix
${X^{\text{*}}}$ which contains the contextualized embedding of the input text after the multi-head self-attention mechanism. The matrix
${W_O}$ allows the model to capture more complex interactions across different heads.
During training, all weight matrices are initialized with small random values and updated iteratively through backpropagation. In this process, the model first generates predictions based on its current parameters and compares them to the true labelsFootnote 22 to compute a loss function that quantifies prediction error. The model then computes the gradient and uses this information to adjust the parameters in the direction that reduces the loss. This gradient-based optimization is repeated across many iterations and batches of data, gradually refining the weight matrices to minimize overall error. Once training converges, these learned parameters encode how strongly each token attends to others across multiple representational subspaces, and they are subsequently retained for downstream inference.
3.1.4. Feed-forward neural network layer
The multi-head self-attention mechanism is the core innovation of the transformer encoder. Following Figure 1, the next componentFootnote 23 is a feed-forward neural network (FNN).Footnote 24 The FNNFootnote 25 receives the output from the multi-head self-attention layer, denoted as
${X^{\text{*}}}$ in Figure 5, and processes it through dimensionality expansion and reduction to produce the encoder’s final output (Lin and Lucas, Reference Lin, Lucas, Box-steffensmeier, Christenson and Sinclair-chapman2024).
While the multi-head self-attention mechanism enables the model to handle long-range dependencies within the data, the FNN enhances the model’s capacity to learn complex and non-linear relationships.Footnote 26 This capacity is crucial for classification tasks requiring language comprehension, where the meaning of a word often relies on its context within a sentence or even across a paragraph.
3.2. Pre-training and fine-tuning
In this section, I examine the PFP of encoder-only language models, which typically comprise of multiple transformer encoders stacked together, resulting in millions or billions of trainable parameters. Such large-scale models require extensive datasets to ensure diverse and ample examples for effective learning. However, these expansive datasets are often not accessible to applied scholars. Transfer learning offers a solution to this challenge, allowing models pre-trained on large datasets by research institutions and corporations to be fine-tuned on task-specific datasets with minimal resources.
During the pre-training phase, the parameters of the transformer encoders are learned using self-supervised learning on a vast corpus of unlabeled text, such as the Common Crawl. The objective of pre-training is to enable the model to acquire a general understanding of linguistic, semantic, and syntactic patterns in the language. This phase effectively initializes the model’s parameters in a contextually informed manner, as opposed to random initialization, which lacks relevance to specific downstream tasks (Ruder et al., Reference Ruder, Peters, Swayamdipta and Wolf2019).
In the fine-tuning stage, the pre-trained model is further adapted to address a specialized task, such as toxic language classification, by training on a smaller, labeled dataset (e.g., a corpus of annotated tweets). Unlike pre-training, fine-tuning is generally not resource-intensive, and can yield substantial performance improvements for tasks with limited annotated data. In this article, I propose the PFP approach due to its potential to deliver high performance in text classification tasks, while giving researchers greater control over the data that the model learns from.
3.2.1. Domain definition
Before turning to the implementation of the PFP, it is useful to clarify what a domain is in this context. In NLP research, a domain refers to a collection of texts that share systematic linguistic regularities—topical, stylistic, or community-specific—that differ from the general corpora on which base models such as BERT are originally pre-trained. These differences may arise from topical specialization (e.g., legislative debates or policy documents that employ distinctive jargon), stylistic variation (e.g., the informal, sarcastic tone of social-media discourse), or community-specific lexicons that encode culture-bound meanings (e.g., ethnic slurs or political slogans).
Distinguishing among these forms of domain variation is important because they pose distinct representational challenges for language models. Polysemous variation, as in the word ‘left,’ represents a linguistic-semantic challenge: the same surface form can express multiple, unrelated meanings. Resolving such ambiguity depends primarily on the model’s ability to use local syntactic and semantic context—a strength already present in contextual encoders through mechanisms such as multi-head self-attention. In contrast, socio-cultural or community-specific variation, exemplified by the phrase ‘yellow invasion,’ reflects a cultural-pragmatic challenge. Its pejorative sense depends on historically and socially embedded usage that may be under-represented in the general pre-training data. Addressing this type of variation requires additional exposure to in-domain texts in which such expressions appear, allowing the model to learn their contextual associations and pragmatic connotations.
Domain-adaptive pre-training (DAPT) directly addresses this latter problem by continuing pre-training on a large, unlabeled corpus drawn from the target domain before task-specific fine-tuning. Through this intermediate adaptation step, the model updates its internal representations to reflect domain-specific linguistic patterns without discarding the broad semantic knowledge acquired during initial pre-training. In short, DAPT allows the model to better align its representational space with the statistical properties of the target corpus, thereby improving downstream classification performance when the new data differ markedly from the general-domain text.
In later sections, I return to this distinction to show that when the target domain is only moderately distinct from the general pre-training corpus—as in the case of political discourse on Twitter—the empirical gains from DAPT remain limited, underscoring the importance of matching method to domain specificity.
3.2.2. Pre-training stage
To contextualize the following discussion, I use the classic BERTFootnote 27 as an example of encoder-only models (Devlin et al., Reference Devlin, Chang, Lee and Toutanova2019). Encoder-only models exploit transfer learning (Zhuang et al., Reference Zhuang, Zhiyuan, Duan, Xi, Zhu, Zhu, Xiong and He2021).Footnote 28 In the context of classification tasks, such as toxic language detection, researchers usually start to train neural networks by randomly initializing the weights from a specified random seed. Intuitively, as the training process begins, these weights are continually updated to perform the task with fewer errors, a process often referred to as optimization. During the pre-training stage, the model is trained using self-supervised learning, which allows the use of enormous amounts of data without the need for manual labels. For example, for BERT, the self-supervised pre-training task consists of predicting missing words from sentences (i.e., Masked Language Modeling) from a large internet corpus of unlabelled text including the entire Wikipedia and Book Corpus.Footnote 29
The pre-training process of a BERT-like encoder-only model is shown in Parts 1 and 2 in Figure 6. The input tokens (along with a special < CLS > tokenFootnote 30 denoting the start of the sequence specific for BERT-like models) are converted to token embeddings through the embedding layer as described in Section 3.1.1 and Figure 2. These embeddings are passed through a series of transformer encoders to create a set of output embeddings as illustrated in Section 3.1.3 and Figure 5. The first encoder receives the output from the embedding layer as the input, while the subsequent encoders receive the output from the previous encoder as their input. A small fraction of the input tokens is randomly replaced with a generic < mask > token.Footnote 31 In pre-training, the goal is to predict the missing token from the associated output embedding.Footnote 32 The model then calculates the loss from each of its predictions to update the weights for all learnable layers as highlighted in shaded boxes in Figure 6 through back-propagation by calculating the gradients or derivatives of the loss with respect to the weights (Devlin et al., Reference Devlin, Chang, Lee and Toutanova2019).
Pre-training and fine-tuning for BERT-like encoder-only models. Shaded boxes contain trainable parameters.

Figure 6 Long description
Large workflow diagram showing the pre-training and fine-tuning process for a BERT-like encoder-only model. Part 1 shows input text passing through an embedding layer and a stack of transformer encoders. Part 2 shows pre-training through masked token prediction and cross-entropy loss. Part 3 shows fine-tuning for toxicity classification, where the model predicts toxic or non-toxic labels and updates trainable parameters through backpropagation. Shaded boxes indicate trainable parameters.
In the PFP, researchers can optionally conduct DAPT from a publicly pre-trained model to improve classification performance by repeating the pre-training process (Gururangan et al., Reference Gururangan, Marasović, Swayamdipta, Lo, Beltagy, Downey and NA2020), such as training with masked language modeling on domain-specific data, to update trainable parameters in both Parts 1 and 2 shown in Figure 6. Part 1 is then saved as the domain-adapted model to use later for fine-tuning tasks with Part 3. However, for researchers with limited computational resources, fine-tuning on a good quality labeled dataset could also achieve similar performance as discussed in the following section.
3.2.3. Fine-tuning stage
Considering the substantial parameterization inherent to language models,Footnote 33 pre-training or DAPT can incur significant computational expenses and necessitate extensive datasets. Rather than conducting the pre-training ourselves, political science researchers can leverage pre-trained models previously developed and made available by companies or research institutions worldwide.Footnote 34
Transformer-based pre-trained language models like BERT perform well on general-purpose language tasks but may struggle with domain-specific tasks like toxic language classification. Subsequently, scholars can fine-tune the pre-trained models to accommodate diverse downstream tasks using task-specific data, thereby capitalizing on the general linguistic knowledge established during the pre-training stage (Barbieri et al., Reference Barbieri, Camacho-Collados, Neves and Espinosa-Snke2020; Chalkidis et al., Reference Chalkidis, Fergadiotis, Malakasiotis, Aletras and Androutsopoulos2020; Lee et al., Reference Lee, Yoon, Kim, Kim, Kim, So and Kang2020; Caselli et al., Reference Caselli, Basile, Mitrović and Granitzer2021). In the fine-tuning stage, the model parameters are updated to specialize the model to a particular task.
As illustrated in Parts 1 and 3 in Figure 6, to fine-tuneFootnote 35 a pre-trained model like BERT, scholars can append a task specific neural network on top of the encoder-only model and train the entire model with the a small annotated dataset. Instead of comparing the predicted token with the original masked token in pre-training, during fine-tuning for classification, the model compares the predicted label with the true label to compute the loss and update the weights through back-propagation as shown in Part 3 in Figure 6. Learned linguistic features such as syntactic and semantic roles from the pre-trained model are largely preserved in the fine-tuned models (Merchant et al., Reference Merchant, Rahimtoroghi, Pavlick and Tenney2020).
Compared to pre-training, fine-tuning is a computationally inexpensive approach that requires considerably smaller volumes of data while affording adaptability to specific tasks, and can take just a few minutes to complete. In Section 4, I apply the PFP approach to a toxic language classification task to demonstrate its data efficiency, training efficiency, and performance enhancement capabilities. I show that models trained with PFP outperform the traditional text classification methods reviewed in Section 2 using an annotated sample Twitter dataset of conversation threads following tweets from US Senators one month before and after the 2020 Presidential Election.
3.3. Guidelines of the PFP
Before outlining practical implementation steps, it is useful to briefly consider why the PFP is particularly effective for political text analysis compared to earlier modeling frameworks. Earlier architectures—such as static embedding and LSTM-based models—often captured domain-specific patterns but struggled to generalize across new datasets or topics without substantial retraining. In contrast, transformer encoders leverage large-scale pre-training to learn contextualized representations that transfer effectively across domains and time periods. Liu and Ritter (Reference Liu and Ritter2023) demonstrated that transformers exhibit greater robustness and temporal generalization than earlier sequential models. These findings underscore the rationale for adopting the PFP: it capitalizes on the generalization strengths of pre-trained models while allowing applied researchers to adapt models efficiently to their own corpora and research questions.
There are several ways to use the PFP with different levels of data and compute availability. Figure 7 shows the entire text classification workflow.
Text classification workflow following the PFP. Intermediate steps can be skipped when working with limited computational resources and data.

Figure 7 Long description
Six-step workflow for applying the pretrain-finetune paradigm to text classification. The steps are: define the measurement objective; collect, clean, and preprocess data; domain-adapt a pre-trained model with unlabeled data; fine-tune the model with labeled data; validate the model with out-of-sample test data; and apply the trained model for measurement. Arrows show that some intermediate steps can be skipped, including fine-tuning without domain-adaptive pre-training or using an off-the-shelf model.
When researchers have no annotated data, the simplest way to adopt the PFP is to download publicly available classifiers already trained using the PFP and apply them directly to datasets at hand. This approach offers the key advantage of minimal computational cost, as the model has already undergone the resource-intensive pre-training and fine-tuning stages. However, a potential drawback of such direct application is the difficulty in finding an existing model that aligns perfectly with the specific needs of the task at hand.
When deciding whether to bypass steps outlined in Figure 7, researchers may initially employ off-the-shelf models and validate their performance using labeled data. In Section 4, I show that while off-the-shelf models can be valuable in certain scenarios, they may also prove ineffective in others. Consequently, rigorous validation is essential especially when utilizing models with lower levels of customization (Justin and Stewart, Reference Justin and Stewart2013; Park and Montgomery, Reference Park and Montgomery2025).
For researchers with some annotated data and limited compute resources, they can download a publicly pre-trained model and use the generated embeddings to train a classifier on top of the model (Licht et al., Reference Licht, Abou-chadi, Barberá and Hua2025), where only Part 3 in Figure 6 is updated.
For researchers with more compute resources, a more tailored approach is to start with a domain-adapted model that has been pre-trained on a relevant corpus, and then fine-tune it using a small annotated dataset, such as a few hundreds labeled tweets, where both Parts 1 and 3 in Figure 6 are updated accordingly. This hybrid strategy of leveraging transfer learning combined with targeted fine-tuning is the most recommended approach for applied scholars in the PFP, as it balances the computational and data efficiency of using a pre-existing model with the ability to customize the model to their specific research requirements.
For scholars with access to more compute resources, another option is to engage in the entire pre-training and fine-tuning process from steps 1 through 6, allowing for maximum customization of the language model to their preferences and the task at hand. They can download a publicly pre-trained model and conduct DAPT with the model by re-doing the pre-training tasks to update Parts 1 and 2 in Figure 6 and save Part 1 as the domain-adapted model. Then conduct fine-tuning to update Parts 1 and 3 accordingly to obtain the final classification model. This approach, while more computationally intensive, provides the greatest flexibility in tailoring the model to the unique needs of scholars.
In the following section, I demonstrate the power of the PFP through a real-world application on toxic language classification. To illustrate the potential of the PFP in non-English content, I also replicate a paper by Chang and Masterson Reference Chang and Masterson2020 where they applied Long Short-term Memory (i.e., LSTM) along with word2vec to classify over ten thousand Chinese Weibo posts into political versus non-political categories. More details are discussed in Appendix 2.
4. Application to toxic language classification
In this section, I provide a step-by-step walk-through of the guidelines illustrated in Figure 7, with an application to toxic language classification to validate the PFP and serve as a template for scholars to build from. The objective is to systematically compare the performance of various PFP models against each other and against baseline models to assess their out-of-sample validity, face validity, and predictive validity through a real-world application. Table 1 provides a complete list of all models used, which are discussed with greater details in Appendix 6.
List of all models used in Section 4

Table 1 Long description
Table listing 17 models used in the toxicity classification application. The columns report model number, model name, model category, and training time. Models 1–6 are off-the-shelf PFP models, Models 7–11 are fine-tuned PFP models, Model 12 uses frozen encoders, Model 13 uses domain-adaptive pre-training and fine-tuning, and Models 14–17 are baseline models. Training times range from no additional training to 46 hours plus fine-tuning for the domain-adapted model.
4.1. Data preparation
The proliferation of toxic language has intensified with the widespread use of social media (Massaro and Stryker, Reference Massaro and Stryker2012; Chandrasekharan et al., Reference Chandrasekharan, Pavalanathan, Srinivasan, Glynn, Eisenstein and Gilbert2017; Rheault et al., Reference Rheault, Rayment and Musulan2019; Agarwal et al., Reference Agarwal, Hawkins, Amaxopoulou, Dempsey, Sastry and Wood2021; Matamoros-Fernández and Farkas, Reference Matamoros-Fernández and Farkas2021; Tamara et al., Reference Tamara, Harvey, Jordon, Srauy and Miltnern.d..). Accurately measuring toxicity within large datasets remains challenging due to the absence of an unambiguous and universally accepted definition. The PFP allows scholars to customize models based on their own theoretical definitions, instead of relying on models trained with definitions provided by others which are often not transparent. Appendix 3 offers a more detailed discussion of the definitional debate on toxicity. While resolving the definitional debate goes beyond the scope of this article, to demonstrate the effectiveness of the PFP, I adopted a comprehensive and operationalizable definition of toxicity offered by (Poletto et al., Reference Poletto, Basile, Sanguinetti, Bosco and Patti2021), where toxicity is defined as ‘any impolite, rude or hurtful language that can show a debasement of someone or something, or show intense emotion, including hate speech, derogatory language and also profanity’ (Poletto et al., Reference Poletto, Basile, Sanguinetti, Bosco and Patti2021).
To apply this framework, I collected a dataset comprising 20,072 tweetsFootnote 36 posted by U.S. Senators from the 116th U.S. Congress between October 1 and November 30, 2020, using the Twitter Academic API. Additionally, conversation threadsFootnote 37 generated in response to each of these tweets over the following year were gathered, yielding a total of 1,652,973 tweets. From this corpus, I randomly sampled 3,000 tweets to be labeled by human annotators recruited via Amazon Mechanical Turk. All annotators were required to complete a training module and pass a qualification test to ensure consistency and accuracy in annotation. Each tweet was annotated by two independent coders, achieving an inter-coder reliability rate of 93%. After excluding cases with inconsistent annotations, the final dataset contained 2,790 tweets with full agreement, of which 1,149 (41.2%) were labeled as toxic and 1,641 (58.8%) as non-toxic. For model training, I randomly divided the annotated dataset into training (80%), validation (10%) and test (10%) subsets. Detailed information on the data annotation process is available in Appendix 4.
I compare five categories of models: off-the-shelf PFP models trained on existing toxicity benchmarks, PFP models fine-tuned on the annotated Twitter data, a frozen-encoder PFP model that updates only the task-specific classification layer, a domain-adapted and fine-tuned PFP model, and four baseline models based on dictionary methods, BOW with Naive Bayes, fastText with a linear classifier, and Google’s Perspective API. For consistency in evaluation, the test set is used to assess all models in Table 1. Full model descriptions, implementation details, and additional evaluation tables are provided in Appendix 6.
4.2. Validation of the PFP
To validate the PFP, I first assess the out-of-sample performance of each model listed in Table 1 alongside their computational costs in terms of training time, focusing on balanced accuracy scores. Second, I examine the content validity of this measure by looking at example tweets classified by the models and whether the results align with theoretical definitions and human intuition. Then, I further examine the face validity of the measure by comparing the proportion of toxic tweets in the human annotated random sample and the classified full dataset. Finally, I investigate the predictive validity of the toxicity measure through an exploration of escalation of toxicity within conversation threads on Twitter. Results indicate that all fine-tuned PFP models outperform the baseline models for the toxicity classification task, regardless of DAPT.
4.2.1. Out-of-sample performance
Figure 8 illustrates the balanced accuracy scores on the out-of-sample test dataset for all models listed in Table 1. Detailed evaluation results for each model category (i.e., off-the-shelf models, fine-tuned PFP models, and baseline models) are presented in Tables A1, A2, and A3 in Appendix 6. Across all metrics, the fine-tuned PFP models exhibit significantly improved performance relative to the baseline models consistently. Among these, Model 10 achieves the highest balanced accuracy score of 0.8860, highlighting its effectiveness for toxic language classification. Figure 9 shows the confusion matrix for Model 10. Confusion matrices for Models 14-17 are provided in Appendix 6.
Balanced accuracy scores of all models.

Figure 8 Long description
Scatterplot showing balanced accuracy for Models 1–17, grouped into off-the-shelf PFP models, fine-tuned PFP models, and baseline models. Fine-tuned PFP models generally perform best, with Model 10 achieving the highest balanced accuracy at 0.886. Model 12, which freezes the encoder parameters, performs substantially worse than the other fine-tuned models. Baseline models show lower and more variable balanced accuracy.
Confusion matrix for model 10.

Figure 9 Long description
Confusion matrix for Model 10 on the test set. The model correctly classifies 152 non-toxic tweets and 97 toxic tweets. It misclassifies 13 non-toxic tweets as toxic and 17 toxic tweets as non-toxic, indicating strong overall classification performance with relatively few false positives and false negatives.
As shown in Table 1, fine-tuning times for the models varied, with most models requiring only a few minutes. Details are included in Appendix 6. The longest fine-tuning duration was recorded by Model 11, taking 3 minutes and 46 seconds. In contrast, Model 12, which involved updating only the task-specific layer rather than performing full fine-tuning, required just 32 seconds for training, but displayed a notable reduction in performance. It is the worst-performing model, and should not be used for research in general. This underscores the importance of updating the parameters of the encoders during fine-tuning to maximize model performance for a given task. Even without additional training, certain off-the-shelf models (Models 1, 2, 4, and 5) achieved balanced accuracy scores exceeding that of the best-performing baseline model (Model 16). The high performance among off-the-shelf models may, in part, be due to the alignment between toxicity definitions in the annotated OffensEval and AbusEval dataset, which were used to fine-tune these models, and the definition applied within my annotated Twitter dataset. This highlights the importance of validating off-the-shelf models to ensure they align well with the specific requirements of the target dataset.
Interestingly, the process of DAPT prior to fine-tuning, which required a substantial 46 hours of computational time, did not produce any measurable improvement in classification accuracy compared to models that were simply fine-tuned. It is important to note that the Twitter corpus used in this study represents a moderately domain-shifted context rather than a highly specialized linguistic environment. Political discourse on social media differs from the formal, encyclopedic style of the corpora on which BERT was originally pre-trained, yet it does not feature entirely novel or domain-exclusive vocabulary, such as medical or legal documents. Consequently, the limited additional benefit from DAPT observed in Model 13 is theoretically consistent with expectations. This finding is informative for applied researchers: it suggests that while DAPT can substantially improve performance in domains with distinct lexicons—such as medical or legal texts—it may offer only marginal returns for general political communication. The empirical illustration thus serves as a baseline case, demonstrating that DAPT is not always necessary and that task-specific fine-tuning alone can often achieve strong performance at much lower computational cost.
4.2.2. Content validity
Beyond evaluating classification metrics, I also assess the content validity of PFP models in comparison to the baseline models. To this end, I examine instances where Model 10, the best-performing PFP model, classified tweets as toxic with highest probabilities, while baseline models yielded divergent classifications. Table 2 highlights examples of such classifications. In many cases, the baseline models failed to detect toxicity in tweets where neutral words, such as ‘crying’ were used with negative or derogatory intent. This finding suggests that the baseline models struggle with subtle contextual cues that indicate toxicity, while Model 10’s more nuanced understanding of context allows for improved identification.
Examples of disagreed tweets in the test set. Probabilities are for the predicted label

Table 2 Long description
Table showing examples of test-set tweets where Model 10 and baseline models disagree. The columns include the tweet text, true label, Model 10 prediction and confidence, and predictions from the dictionary-based model, bag-of-words model, fastText model, and Google Perspective API. The examples illustrate that Model 10 often identifies contextual toxicity with high confidence, while baseline models produce inconsistent classifications.
To enhance interpretability of the models’ classification decisions, I employed the integrated gradients (IG) algorithm to calculate attribution scores for each token when classifying the input tweet as toxic or not (Sundararajan et al., Reference Sundararajan, Taly and Yan2017). The IG method quantifies how much each input token contributes to the model’s prediction by computing the gradients of the output with respect to the token embeddings, and then integrating these gradients along a path from a neutral baseline input (e.g., an empty or zero vector) to the actual input. Tokens with higher positive attribution scores increase the model’s confidence in the predicted class (e.g., toxicity), whereas tokens with negative scores suppress that prediction.
Figure 10 provides a representative example comparing E1 and E2 both containing the word ‘yellow,’ showing how words such as ‘evil’ contribute positively to toxicity detection, while neutral words receive near-zero or negative attribution. Table A4 in Appendix 7 visualizes token-level attributions for additional examples. This interpretability approach allows for an intuitive understanding of how the model weighs contextual cues when making predictions—revealing that transformer-based models capture nuanced linguistic relationships that simpler approaches cannot. More comprehensive details regarding the implementation and interpretive value of integrated gradients in this context are provided in Appendix 7.
Token-level attribution scores with integrated gradients algorithm.

Figure 10 Long description
Two-panel visualization of token-level attribution scores for two example sentences containing the word ‘yellow.’ Panel A shows a toxic sentence in which terms such as ‘evil’ and ‘yellow’ contribute to the model’s toxicity prediction. Panel B shows a non-toxic sentence about flowers, where the same word appears in a neutral context. The figure illustrates how the model uses surrounding context to assign different meanings to the same word.
4.2.3. Proportion validity
I further analyze the aggregate classification outcomes by comparing the proportion of tweets labeled as toxic and non-toxic by human annotators versus the models. Since the human-annotated dataset is a random sample from the full dataset, it provides a strong approximation of the true proportion of toxic and non-toxic tweets. While the models align closely in ranking senators based on the volume of toxic tweets in their conversation threads, notable discrepancies emerge in the absolute counts and proportions. Figure 11 presents the proportion of toxic and non-toxic tweets classified across different models, with the dotted line indicating the proportions identified in the human-annotated random sample. Notably, Model 15 classifies more than twice the proportion of toxic tweets compared to the human benchmark, whereas Model 14 substantially underestimates toxicity. Model 10 yields the closest approximation to the human-annotated proportion, followed by Model 16.
Bar-plots of Proportion of Toxic and Non-Toxic Tweets Labeled by Different Models.

Figure 11 Long description
Two bar plots comparing the proportions of tweets labeled toxic and non-toxic by Models 10, 14, 15, and 16. A red dashed line marks the human-annotated benchmark of 41.2 percent toxic tweets and 58.8 percent non-toxic tweets. Model 10 most closely matches the human benchmark, Model 14 substantially underestimates toxicity, and Model 15 substantially overestimates toxicity.
These discrepancies persist when disaggregating results by gender and party affiliation. As shown in Figure 12, Model 15 continues to classify a substantially higher proportion of tweets as toxic, whereas Model 14 reports significantly lower proportions compared to the human-annotated random sample. Among the baseline models, Model 16 most closely aligns with Model 10 and the human benchmark in overall classification proportions, where others demonstrate considerable misalignment. This analysis highlights Model 10’s superior performance in maintaining both contextual sensitivity and reliability in toxicity detection.
Proportion of toxic tweets labeled by different models.

Figure 12 Long description
Two-panel bar plot showing the proportion of tweets labeled toxic by Models 10, 14, 15, and 16, disaggregated by senator gender and party. A red dashed line marks the 41.2 percent human-annotated benchmark. Across both panels, Model 15 labels a very high proportion of tweets as toxic, Model 14 labels a much lower proportion as toxic, and Model 10 remains closest to the human benchmark while preserving subgroup differences.
4.2.4. Predictive validity
To demonstrate the potential usefulness of the PFP in political science and check predictive validity of the toxicity measure, I analyze how Twitter user-base responded to tweets from Senators of the
${116^{th}}$ U.S. Congress and explore whether factors correlate to toxicity within conversation threads in theoretically expected directions.
In recent years, the U.S. political landscape has become increasingly polarized, leading to a heightened level of incivility in political discourse, especially in online spaces (Druckman et al., Reference Druckman, Peterson and Slothuus2013; Iyengar and Westwood, Reference Iyengar and Westwood2015; Rogowski and Sutherland, Reference Rogowski and Sutherland2016; Abramowitz and Webster, Reference Abramowitz and Webster2018; Iyengar et al., Reference Iyengar, Lelkes, Levendusky, Malhotra and Westwood2019). Research on partisan polarization suggests that political divisions between Republicans and Democrats have intensified, with individuals becoming more entrenched in their ideological camps (Iyengar and Westwood, Reference Iyengar and Westwood2015). Negative partisanship has fueled hostile rhetoric, particularly against high-profile political figures (Abramowitz and Webster, Reference Abramowitz and Webster2018). When politicians post toxic content, it can provoke out-partisan responses that mirror or escalate such toxicity. Social media platforms further amplify negative content through engagement-driven algorithms, where posts expressing toxicity or hostility are often more widely circulated (Steve et al., Reference Steve, Van Bavel and van der Linden2021; Huszár et al., Reference Huszár, Ktena, O’brien, Belli, Schlaikjer and Hardt2022). As a result, some scholars have argued that toxic tweets by politicians are more likely to generate toxic responses and be displayed widely, creating a self-reinforcing cycle where toxicity is both rewarded and amplified (Munger, Reference Munger2017; Steve et al., Reference Steve, Van Bavel and van der Linden2021; Huszár et al., Reference Huszár, Ktena, O’brien, Belli, Schlaikjer and Hardt2022). Therefore, I propose the following hypothesis:
Toxic parent tweets are associated with higher levels of toxicity in the following conversation threads.
To validate this theory, each tweet is classified as either containing toxic content (
$ = 1$) or not (
$ = 0$). Using these classification results, I calculate a Toxicity score for each parent tweet, representing the proportion of toxic tweets within the conversation threads following that tweet. The Toxicity score ranges from 0 to 1, where 0 indicates the absence of toxic tweets in the threads and 1 indicates that all tweets in the threads are toxic. The main explanatory variable ParentToxicity measures whether the parent tweet is toxic or not, where 1 indicates toxicity and 0 otherwise. To test this hypothesis, I additionally control for whether the parent tweet mentions the two presidential candidates (Donald Trump or Joe Biden), specific policy issues: (economy, COVID, abortion, crime or climate), and whether the parent tweet references other Senators from either the same or opposing party.Footnote 38 I also control for Senator-specific fixed effects.
To assess the effect of toxic parent tweets on toxicity levels in subsequent conversation threads, I implement a fixed effects model. For each Senator
$i$:
\begin{equation}\begin{gathered}
Toxicit{y_i}{ = \,{\alpha _i}}\, + \,{\beta _1}\,ParentToxicit{y_i} \hfill \\
\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,{+ \,{\beta _2}} MentionTrum{p_i}\, + \,{\beta _3}MentionBide{n_i}\, + \,\,{\beta _4}MentionEconom{y_i} \hfill \\
\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,{+ {\beta _5}MentionCovi{d_i}} + \,{\beta _6}MentionAbortio{n_i}\, + \,{\beta _7}MentionCrim{e_i} \hfill \\
\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,{{ + \beta }_8}MentionClimat{e_i}\, + \,{\beta _9}MentionCopartisa{n_i}\, + \,{\beta _{10}}MentionOutpartisa{n_i} \hfill \\
\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,{ + { \in _i}} \hfill \\
\end{gathered} \end{equation}
with Senator-specific intercept
${\alpha _i}$ and error term
${ \in _i}$. The regression analysis was implemented in R using the plm package.
The results from Model 10, summarized in Table 3, show a positive and statistically significant coefficient for the main explanatory variable ParentToxicity at 0.0767, suggesting that, for a given Senator, posting toxic tweets correlates with increased probability of toxic content for each subsequent tweet in the conversation threads. Importantly, while the direction of this relationship is consistent across models, the magnitude varies substantially. Model 15, for instance, reports a considerably higher coefficient of 0.3002, leading to massive differences in interpretation using BOW. Such high coefficient could be attributed to its systematic over-estimation of toxicity, as evidenced in Section 4.2.3. Conversely, classification results from Model 14 produced a lower coefficient, which may reflect its observed tendency to under-count toxicity levels.
Results from fixed effects model with senator-clustered standard errors

Table 3 Long description
Regression table showing fixed effects models predicting toxicity in conversation threads using four different toxicity measures. The key predictor, ParentToxicity, is positive and statistically significant for Model 10, the dictionary-based model, and the bag-of-words model, but not statistically significant for the fastText model. The table reports coefficients, senator-clustered standard errors, observations, R-squared values, adjusted R-squared values, and F statistics for each model.
Note: Full regression table including other control variables is provided in Appendix 8. Additionally, parent tweets that mention Trump, the economy, and COVID are associated with increased toxicity in conversation threads, whereas tweets mentioning co-partisan Senators correspond with lower toxicity levels in the conversation threads.
Despite the closest alignment of Model 16 to Model 10 on an aggregate level shown in Section 4.2.3, Model 16 fails to capture a statistically significant relationship between ParentToxicity and toxicity in subsequent threads. For further details, Table A5 in Appendix 8 provides a complete table of regression coefficients. Additionally, parent tweets that mention Trump, the economy, and COVID are also associated with increased toxicity in conversation threads, whereas tweets mentioning co-partisan Senators correspond with lower toxicity levels in the conversation threads. Collectively, these findings underscore the robustness and reliability of PFP models in measuring toxicity and capturing meaningful relationships in downstream analysis, particularly for nuanced patterns in toxic language within political discourse.
5. Conclusion
This article makes an important contribution to political science by elucidating the PFP as a robust, accessible approach for text classification. Addressing a gap in the field, I explain the PFP in detail, demystifying how transformer-based language models can and should be effectively adapted for political science research. With step-by-step practical guidelines, I clarify the processes involved in pre-training and fine-tuning, making these models accessible to scholars who may not have extensive computational resources or technical expertise. By walking through each component of the transformer encoder architecture and detailing how it overcomes the limitations of traditional models, such as BOW or dictionary-based approaches, I provide scholars with a comprehensive yet approachable framework to adopt the PFP for nuanced textual measurement tasks.
I also demonstrate the PFP’s impressive effectiveness through an empirical application focused on toxic language classification, which showcases its power in capturing complex, context-dependent meanings often missed by traditional methods. This application highlights how the PFP can accurately interpret subtle cues and dynamic language patterns in social media data. By fine-tuning pre-trained models on a relatively small, annotated dataset, the PFP allows researchers to harness the models’ rich linguistic understanding, enhancing accuracy in detecting politically relevant language, such as toxicity in online conversation threads following Senators’ tweets. I find that Senators who post toxic content on Twitter encounter higher levels of toxicity in the subsequent conversation threads. This empirical demonstration establishes the PFP as a highly efficient and effective approach for creating context-sensitive text classifiers that respond to real-world research needs in political science.
Looking ahead, there are several promising future directions for the PFP. Firstly, as multilingual models evolve, the PFP approach could be expanded to accommodate political science research in non-English languages or low-resource languages, thereby broadening the scope of comparative studies and cross-cultural research. For instance, Appendix 2 shows an application to classify Chinese Weibo posts. Additionally, the PFP framework’s flexibility could be extended to address multi-modal data, applying transformer-based models to images, audio, and text in combination, which could yield new insights into multi-modal political messages or campaigns. Finally, as large language models continue to improve, future research could focus on refining the interpretability of these models within the PFP framework. Techniques such as integrated gradients described in details in Appendix 7, which I use to highlight model decision-making, could become more sophisticated, allowing researchers to gain deeper insights into how and why these models interpret complex political language as they do.
Ultimately, by breaking down the complexity of transformer-based models and demonstrating their superior performance in text classification, this paper establishes the PFP as a valuable tool for political scientists for its superior performance, data efficiency, and computational accessibility. As scholars face increasingly large and complex datasets, the PFP offers an efficient and effective way to enhance measurement accuracy and analytical rigor. This article not only lays the foundation for adopting the PFP but also encourages innovative applications that will advance empirical research across diverse domains in political science.
Acknowledgements
Significant thanks to Profs. Jacob Montgomery, Christopher Lucas, and Ted Enamorado for their role in advising, reading, and offering improvements to this paper. Thanks to Prof. Margit Tavits, Jeremy Siow, the WashU Political Science Research Workshop, and the WashU Political Data Science Lab for further feedback.
Data availability statement
Replication data and code can be found in Harvard Dataverse: https://doi.org/10.7910/DVN/STDKZ2.
Declaration of interests
None
Funding statement
None
Supplementary material
The supplementary material for this article can be found at https://doi.org/10.1017/psrm.2026.10120. To obtain replication material for this article, https://url.uk.m.mimecastprotect.com/s/3BAPC7L88smj5N4Ec8fXfopsNB?domain=doi.org











