R-Package for NLP in Psychology
R-Package for NLP in Psychology
CITATION
Kjell, O., Giorgi, S., & Schwartz, H. A. (2023, May 1). The Text-Package: An R-Package for Analyzing and Visualizing Human
Language Using Natural Language Processing and Transformers. Psychological Methods. Advance online publication.
[Link]
Psychological Methods
© 2023 American Psychological Association
ISSN: 1082-989X [Link]
Abstract
The language that individuals use for expressing themselves contains rich psychological information. Recent
significant advances in Natural Language Processing (NLP) and Deep Learning (DL), namely transformers,
have resulted in large performance gains in tasks related to understanding natural language. However, these
state-of-the-art methods have not yet been made easily accessible for psychology researchers, nor designed
to be optimal for human-level analyses. This tutorial introduces text ([Link] a new R-package for
analyzing and visualizing human language using transformers, the latest techniques from NLP and DL. The
text-package is both a modular solution for accessing state-of-the-art language models and an end-to-end
solution catered for human-level analyses. Hence, text provides user-friendly functions tailored to test
hypotheses in social sciences for both relatively small and large data sets. The tutorial describes methods for
analyzing text, providing functions with reliable defaults that can be used off-the-shelf as well as providing a
framework for the advanced users to build on for novel pipelines. The reader learns about three core meth-
ods: (1) textEmbed(): to transform text to modern transformer-based word embeddings; (2) textTrain() and
textPredict(): to train predictive models with embeddings as input, and use the models to predict from; (3)
textSimilarity() and textDistance(): to compute semantic similarity/distance scores between texts. The reader
also learns about two extended methods: (1) textProjection()/textProjectionPlot() and (2) textCentrality()/
textCentralityPlot(): to examine and visualize text within the embedding space.
Translational Abstract
Natural language is the fundamental way individuals communicate their thoughts and emotions to others.
Recent advances in Artificial Intelligence (AI), referred to as transformers, have resulted in large
increases in performance at most tasks related to understanding natural language. This tutorial introduces
how to use these state-of-the-art AI techniques in both custom research analyses as well as in completely
end-to-end analytic processes. We describe text, a software package which provides transformer-based
techniques intended to be easily accessible for social scientists. The text-package is open-source, written
for the statistical programming language R, and it is free to use or alter. It comprises user-friendly func-
tions to transform text to numeric representations, that are used for examining their relationship to other
variables or for visualizing statistically significant features of texts. Transformers can facilitate analyses
of natural language for gaining psychological insights with unprecedented accuracy and provide a more
detailed understanding of the human condition.
1
2 KJELL, GIORGI, AND SCHWARTZ
How individuals express themselves and their state of mind assessments as a complement to traditional rating scales (Kjell
with natural language constitutes a wealth of information for et al., 2019, 2022), and analyze written narratives of traumatic life
understanding them psychologically and socially (e.g., see Kern events to predict health related outcomes (Campbell & Penne-
et al., 2016; Kjell et al., 2019). “Language is the most common baker, 2003; Son et al., 2020). Probed language may also involve
and reliable way for people to translate their internal thoughts and asking participants to recall various memories, describe them-
emotions into a form that others can understand” (Tausczik & Pen- selves in various ways, partake in stream-of-consciousness tasks
nebaker, 2010, p. 25). This tutorial explains how psychology and so on.
researchers can use recent advances in Artificial Intelligence (AI), In addition, language may be generated within an experimental
including Natural Language Processing (NLP) and Deep Learning, context. Computational language methods can, for example, be
to quantitatively analyze natural language. used to enhance experimental control by matching word stimuli
Researchers in NLP have turned to open-vocabulary methods according to semantic similarity (Dougal & Rotello, 2007; Gagné
that rely on patterns in linguistic data to derive models of lan- et al., 2005), examining the text generated from experimental
guage. These methods leverage the idea that words may be repre- manipulations (Garcia & Sikström, 2013) and using semantic sim-
sented by values based on how they co-occur in languages (e.g., ilarity of the names of objects to find significant correlations with
This article is intended solely for the personal use of the individual user and is not to be disseminated broadly.
Firth, 1957), and allow for modeling words according to the con-
This document is copyrighted by the American Psychological Association or one of its allied publishers.
Current Alternatives If you experience problems with the installation, see the
extended installation guide for up-to-date information ([Link]
There are few alternatives in R (R Core Team, 2022) that focus
[Link]/articles/Extended_Installation_Guide.html).
on getting state-of-the-art word embeddings; and that have func-
tionalities tailored for analyzing embeddings in downstream tasks
relevant for social sciences and psychological research. Computer Core Functionality
scientists have predominantly used Python (Van Rossum & Drake,
1995), and Python-libraries such as the Differential Language The text-package has three core functionalities: (1) transforming
Analysis ToolKit (DLATK; Schwartz et al., 2017), PyTorch text to word embeddings, (2) predictive modeling with word
(Paszke et al., 2019), spaCy (Honnibal, & Montani, 2017), and embeddings, and (3) comparing words or texts for semantic simi-
NLTK (Bird et al., 2009). Further, even though computer scientists larity. These are described below, followed by the introduction of
use Python for standard NLP/ML tasks, few python packages two extended functionalities.
attempt to bridge this line of work with psychological research
such as DLATK. The text-package comprises an interface with Transforming Text to State-of-the-Art Word
Python to get the state-of-the-art language models while also con-
This article is intended solely for the personal use of the individual user and is not to be disseminated broadly.
Embeddings
This document is copyrighted by the American Psychological Association or one of its allied publishers.
word embeddings. Words within natural language are not ran- static (or decontextualized), so that the embedding for “happy” is
domly distributed, instead contextual words are predictable and always the same even if it appeared in the context of “I am happy”
define its meaning (Iliev et al., 2015). Hence, it is possible to use versus “I am not happy.” Examples of commonly used decontextual-
this distribution to represent “the meaning of a word through the ized approaches include word2vec (Mikolov et al., 2013), Latent
contexts in which it has been observed in a corpus” (Erk, 2012, Semantic Analysis (LSA; Deerwester et al., 1990) and Latent
p. 635). This may be achieved by constructing a table of word co- Dirichlet allocation (LDA; Blei et al., 2003).
occurrence counts, where the dimensions are extracted using a
Contextualized Word Embeddings and Word Order
dimension reduction technique such as the Singular Value Decom-
position (Golub & Kahan, 1965). Practically, the first column of Contemporary NLP algorithms aim to extract the latent mean-
the frequency table may hold the words in a natural language, the ings in text. These algorithms are based on deep neural net (or
first row may hold word contexts (such as documents of texts) and deep learning) architectures to construct contextualized word
the rest of the cells hold the co-occurrence counts/frequency. Ulti- embeddings, using decontextualized word embeddings as input
mately, the words are represented by a vector containing a number (e.g., see BERT; Devlin et al., 2019). When using these algo-
This article is intended solely for the personal use of the individual user and is not to be disseminated broadly.
for each extracted dimension. Note that these types of approaches rithms, a word’s embedding is different depending on the context
This document is copyrighted by the American Psychological Association or one of its allied publishers.
are referred to as unsupervised, as no predefined categories or it was in and the order of the words in the context—this is
judges are used to produce the numeric representations. achieved by enabling the word embedding to be influenced by
other word embeddings in the context through a mechanism
Decontextualized Word Embeddings: A Bag of Words referred to as self-attention.
Decontextualized word embeddings (or semantic representations The Deep Neural Network Architecture: The Layers and
as they were called) do not account for the context a word was in.
Hidden States
Earlier methods were unable to capture the order that words appeared
in, so that words in a text were treated as a bag of scrambled words: As a deep learning transformer model, BERT comprises several
Bag of words (BOW) models (see Figure 1). The word embedding is layers. Hidden states refer to the output of each layer; these may
Figure 1
An Illustration of How Information is Connected Within the Output of Different Language Model Architectures
LU LU LU LU LU LU LU LU LU
w1 w2 w3 w1 w2 w3 w1 w2 w3
be aggregated across layers to a word embedding that represents introducing deep learning with a focus on Natural Language Proc-
each word (or sentence). The use of multiple layers enables the essing (e.g., see Lauriola et al., 2022), in length discussing the
models to capture nonlinear relationships. BERT-base comprises opportunities and risks of using these models (Bommasani et al.,
12 layers, whereas BERT-large comprises 24 layers; where each 2021) as well as reviews/surveys providing a broader overview
layer comprises numeric values for each dimension, which for and deeper understanding about various model architectures of
BERT is 768 dimensions. Hence, with BERT-large one token can neural networks such as recurrent, recursive, convolutional, and
be represented with 18,432 (24 3 768) values. There are several attention models (Babic et al., 2020; Otter et al., 2019; Qiu et al.,
ways to make use of these layers: including only using one of the 2020), and specifically focusing on the BERT models (Rogers
layers or concatenating them to one longer embedding. et al., 2020).
It is not yet fully understood how the various layers differ; and
Performance of BERT
the advice on how to best use them differs. In short, empirical
examinations indicate that “BERT’s intermediate layers encode a Devlin et al. (2019) demonstrated that BERT obtains substantial
rich hierarchy of linguistic information, with surface features at improvement on a wide range of NLP tasks. For example, it
the bottom, syntactic features in the middle and semantic features
This article is intended solely for the personal use of the individual user and is not to be disseminated broadly.
at the top” (Jawahar et al., 2019, p. 1). Further, it has been demon- understanding tasks called GLUE (General Language Understand-
strated that later BERT layers are more context specific (Ethayar- ing Evaluation); and a 4.6% absolute improvement accuracy on
ajh, 2019). Later we discuss how to use these layers in human the MultiNLI (the Multi-Genre Natural Language Inference
level tasks. corpus, which comprises several hundred thousands of sentence
pairs).
Self-Attention
Accessible Pretrained Language Models in Text
Transformer’s deep neural net architecture has the self-attention
mechanism at its core (Vaswani et al., 2017). It is self-attention To get contextualized word embeddings for your text data, the
that enables the model to combine information about surrounding text-package connects with HuggingFace’s Transformers library
words at varying degrees. Thus, each surrounding word can influ- (Wolf et al., 2019) in Python. This enables the users to imple-
ence the word embedding of the target word. In other words, self- ment many state-of-the-art pretrained language models, includ-
attention enables the algorithm to incorporate the embeddings of ing XLnet (Yang et al., 2019), RoBERTa (Liu et al., 2019), and
other words’ embeddings in so far as it produces a more robust ALBERT (Lan et al., 2019). As the name suggests, a pretrained
representation of the target word. The self-attention mechanism model has already been trained on other data; so that the model
puts different attention or weight to different word embeddings can be applied to your text to retrieve high-quality embeddings.
from the context depending on which appear to be most relevant. This is good considering that training a high-quality deep learn-
During training, the transformer-based models have learned how ing language model requires a lot of computational resources;
to parameterize the attention layers to amplify the influence of the Wolf et al. (2019) point out that RoBERTa was trained on 160
most relevant parts of a context. GB text, and that training this on a typical cloud computing serv-
The transformers’ self-attention mechanism may be compared ice would cost around 100K USD. Consequently, some models
with previous models such as Long Short-Term Memory models have been developed with the focus of being smaller and requir-
(LSTM; Hochreiter & Schmidhuber, 1997). These models are based ing less computational resources to be trained (e.g., see Destil-
on recurrent neural networks, where the influence of the context BERT; Sanh et al., 2019), whereas others have had the focus on
mechanism is less pervasive than in transformers. In LSTM the achieving improved performance (e.g., XLNet; Yang et al.,
influence of the context is only based on the previous state—the 2019).
embedding of the word just to the left of the target word, which in Some models include multiple languages such as multilin-
turn was influenced by its surrounding words, and so on. The model gual BERT (mBERT), which is trained on text from the top 104
can also be run across the sequence backward, such that the previ- languages with the largest Wikipedia entries. Hence, the same
ous state is an embedding of the word to the right. However, it still model includes several languages, where similar languages
requires for nonadjacent pairs of words to pass information about (e.g., Germanic, Slavic) are found close to each other in the
each other through the embeddings between them rather than embedding space (Libovickỳ et al., 2019). mBERT is found to
directly. With self-attention all words are connected with the poten- learn cross-lingual word alignment with high-quality (Libov-
tial to influence each other’s meaning through the word embed- ickỳ et al., 2019). The text-package implements these multilin-
dings. The transformers can model the dependency of every two gual models.
words in a text sequence and are also suitable for long range
Model and Word Embedding Specifics
dependencies. The architecture of the transformers also reduces the
amount of sequential computational steps compared with previous Different models may be based on different types of (domain)
contemporary models such as LSTMs; and this results in decreased text, and use different tokenization (described in detail below),
information loss and faster training times through parallel process- number of layers and hidden states. It is useful to consider these
ing (Wolf et al., 2019). aspects when selecting an appropriate model and its settings,
These descriptions are at a very high level aimed to provide the although default settings in text will often achieve apt results.
reader with a sufficient understanding to be able to make use of Type of Domain Text Used in Pretraining. Word embed-
the key functionality of transformers: turning text into feature vec- dings become better when there is high domain similarity between
tors (embeddings). There are many recent papers specifically the text used to create the language model and the text that should
6 KJELL, GIORGI, AND SCHWARTZ
be interpreted/used for down-stream tasks. To create models for a generally been found to yield good results; but recently Matero
narrow domain can however be challenging because pretrained et al. (2021) more carefully examined which layer(s) that pro-
models require large quantities of text data (and computational duce most accurate results in predicting depression related
resources). Nevertheless, it is worth thinking about the type of text measures, which suggested that “layer 19 (sixth-to last) is the
used to train the models, and how that might influence your most ideal by itself” (p. 1).
results. BERT was originally trained using Wikipedia text; how- Limitations of Transformers. Transformer models are very
ever, other BERT models have been fine-tuned on clinical text large. While researchers have developed ways to shrink mod-
(Alsentzer et al., 2019) and scientific text data (Beltagy et al., els, the best versions of these models are still scaling exponen-
2019). These and many more models are available through the tially. That is, the size of the files defining the models that
text-package. users need is increasing more rapidly than the performance
Uncased Versus Cased Models. Uncased models convert all gains. While BERT-base comprises 110M parameters and
words to lowercase, whereas cased models keep the casing of the achieves a Spearman rho of .86 on a standard semantic simi-
text. Select a cased model if you think that letter casing will be larity task, BERT-large is approximately three times that size
helpful for your analyses. If you do not think that casing will be comprising 336M and achieves only a modest improvement in
This article is intended solely for the personal use of the individual user and is not to be disseminated broadly.
$x
# A tibble: 1 × 768
Dim1 Dim2 Dim3 Dim4 Dim5 Dim6
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
0.311 0.270 0.0274 0.408 0.202 0.113
3
. . . with 762 more variables: Dim7, Dim8, Dim9, . . . Note that in many modern NLP papers and deep learning packages, an
L2 penalization is referred to as “weight decay.”
THE TEXT-PACKAGE 9
Word Embeddings as Input to a Predictive Model model’s predictive ability while simultaneously accounting for
its ability to generalize (e.g., see Browne, 2000). The simplest
The word embeddings may be used in predictive models such as form of a cross validation method randomly divides a dataset
multiple linear regression: into a training-set and a testing-set. The parameters, that is,
the β…βm in the specified regression above, are estimated
y = b0 + b1 ∗x1 ... + bm ∗xm + 1 in the training-set; and then applied to the test-set
to predict values (ŷ) that can be compared with the observed
where y denotes the observed values (in which ŷ represents the values (y). Using this method results in an out-of-sample per-
formance, where the trained model is applied on new data from
predicted value), x1 … xm the predictors, i.e., the dimensions of
the same population.
the word embeddings (where the subscript refers to the mth dimen-
sion), β0 the constant, β1 … βm the coefficients that define the
relationship between embeddings and the outcome, and ε the error
K-Fold Cross Validation
term.
This article is intended solely for the personal use of the individual user and is not to be disseminated broadly.
Considering that the word embeddings often comprise many K-fold cross validation is a procedure to divide the training
This document is copyrighted by the American Psychological Association or one of its allied publishers.
dimensions, it is often useful to first carry out a dimension reduction and testing sets efficiently. If data are scarce, it may be consid-
technique. To achieve this, Principal Component Analysis (e.g., see ered wasteful to not use all data, for example, to only use 50%
Wold et al., 1987) is implemented in text because we have noticed of the data for training and 50% only for testing. First, it is pos-
that it is particularly efficient for reducing the dimensionality of sible to run the procedure again by alternating the purpose of the
word embeddings. It is possible to select other statistical prediction data sets, so that the original testing-set becomes the training-set,
models in text, including using ridge (L2 penalized) regression and the original training-set becomes the testing-set: In this way
by itself (Hoerl & Kennard, 1970), lasso regression (also called all data will have predictions that can be correlated with the
L1-penalized model; Tibshirani, 1996), or a mix of L1 and observed values. Second, to make better parameter estimations
L2-penalized regression (i.e., “elastic-net” regression; Zou, & it is possible to get more power in the statistical models by mak-
Hastie, 2005) and for categorical variables ridge-penalized logistic ing sure that the training set is larger. One common way is to
regression or random forests (e.g., see Ho, 1995). Although text sup- select 90% of the data to the training set and 10% for the testing;
ports lasso and elastic-net (the latter is a composite of both a lasso and then alter the purpose of the data as previously described.
and ridge penalty), it is worth noting that the top systems in the pre- This is done ten times, so that all cases get a prediction.
viously mentioned tasks use only a ridge penalty (Matero et al., Hence, k in k-fold refers to the number of groups (or folds);
2019), which is also the default in the most popular contextual so, the described procedure is called 10-fold cross validation.
embedding library, transformers (controlled with the “weight_de- It is also possible to train on all but one case (that is called
cay” in the pytorch library it utilizes). This lack of utilization for leave-one-out cross validation). Leave-one-out cross validation
is good for very small dataset, whereas for larger dataset it
dense embeddings is probably because any regularization involving
requires a lot of computational power and time (for rather
a lasso is designed for sparse input information (Ganguli &
small gains).
Sompolinsky, 2012), which is not present in most embeddings.
Embeddings are typically dense and rotationally invariant. In other Cross Validation With Test, Train, and Development Sets. To
words, singular dimensions do not necessarily correspond to distinct fit models with hyperparameters (e.g., the penalty in ridge regres-
sets of words. On the other hand, for nondense input vectors, such as sion), a development set (also called assessment set) can be used
with dimensions corresponding to counts of particular words—a to evaluate on. Figure 2 shows how the training set in the outside
multihot encoding or word count vector—the lasso has been fold is split into a training (or analysis) set and development
found beneficial (Schwartz et al., 2013).
(assessment) set. Hence, the training set is used to fit models with
different penalties; these are then assessed in the development set.
The model with the best result (e.g., evaluated using the correla-
Cross Validation
tions between observed and predicted scores) is subsequently
To evaluate the predictions made by a statistical model, it is applied in the test set of the outside fold. This procedure is
possible to correlate the predicted values with the observed val- repeated for all folds.
ues (i.e., cor[y, ŷ]) using cross-validation. Cross validation is a
technique that may be used to evaluate and select a statistical Nested K-Fold Cross Validation. To use nested cross valida-
model with minimal overfit (for a more detailed discussion tion, including train and test loops in the inner fold of each outside
on cross validation in psychology, e.g., see Mosier, 1951; fold, is also a way to make better use of the data (see Figure 3). The
Yarkoni & Westfall, 2017). Overfitting arises when data- above cross validation method with test, train and development sets
specific errors or noise are modeled, which results in a focuses on achieving more accurate estimates of the machine learning
model that is bad at generalizing to other data. The cross- approach, which is good when comparing machine learning algo-
validation methods aim to limit this risk by estimating a rithms. The nested k-fold cross validation focuses on achieving a
10 KJELL, GIORGI, AND SCHWARTZ
Figure 2
Cross Validation With Three Outside Folds; and ¾ Analysis and ¼ Development Set
Note. See the online article for the color version of this figure.
This document is copyrighted by the American Psychological Association or one of its allied publishers.
more accurate model; but tends to take longer time because more to get predictions for words that were not in the original model/
models need to be fitted and evaluated. words list, since the estimated parameters are applied to the dimen-
sions of the word embeddings.
Applying Predictive Models to New Data
Functions
Language-based predictive models can be applied to new data.
Independently trained language models may be applied to new data textTrain(). The textTrain() function is used to examine
to examine semantic-psychological features such as valence or how well the word embeddings from a text can predict a numeric
arousal. It is also easy to share predictive models between projects or categorical variable, based on the different cross-validation
and researchers. For example, it is possible to develop predictive methods described above. The textTrain() function is a wrapper
models for valence and arousal, based on the Affective norms for for textTrainRegression() and textTrainRandomForest(). In the
English Words (ANEW; Bradley & Lang, 1999). The ANEW is a example below we examine how well the satisfaction text-responses
list of more than 1,000 words that have been rated according to va- can predict the rating scale scores from the Satisfaction with life
lence, dominance, and arousal by participants. A valence model can scale. We advise researchers to share their predictive models,
be created by predicting valence from the word embeddings of the for example, on their Open Science Framework account (https://
words in the list. First the model can be evaluated using cross vali- [Link]/) or GitHub. For this purpose, it is possible to attach a descrip-
dation to see how good it is; and then it can be saved without using tion of the data and model by describing it in the describe_model set-
cross validation to use all the data. This model can now be used to ting. For example, use the following format:
estimate the valence of any word or set of text represented by a
word embedding based on the same language model (and settings)
originally used to create the word embeddings in the predictive model_description = “author(s): XXX; data: N = XXX, population =
model. Hence, it is a flexible method considering that it is possible XXX; publication: title = XXX; description: e.g., measure details etc.”
Figure 3
Example of Nested Cross Validation With Two Outside Folds and Four Inside Folds
Note. Prioritizing more outside than inside folds makes often more sense. See the online article for the color version of this figure.
THE TEXT-PACKAGE 11
p_value_
Harmony in life scale scores descriptions correlation df p_value t_statistics alternative corrected
This document is copyrighted by the American Psychological Association or one of its allied publishers.
Figure 4
Call:psych::[Link](x = satisfaction_text_valence$.pred, y = Illustration of the Semantic Similarity of Two Words in a
Language_based_assessment_data_8$swlstotal) Simplified Two-Dimensional Embedding Space
Correlation matrix
[1] 0.64
Sample Size
[1] 40
Probability values adjusted for multiple tests.
[1] 0
space; and the more similar two embedding vectors are the closer
they are positioned in the space. There are many ways to capture
how closely positioned two vectors are; in text many common
similarity and distance measures can be used, including “cosine,”
“euclidean,” “maximum,” “manhattan,” “canberra,” “binary,” or
“minkowski” (for a review of similarity measures see Chandra- Note. This also holds when adding many more dimensions.
sekaran & Mago, 2022). The default similarity measure in text,
is to measure the cosine of the angle between them (see a simpli-
fied illustration in Figure 4). used to measure the semantic similarity between a person’s answer
Similar to a correlation, the cosine can range from 1 to 1 (see to whether they experience harmony in their life to the word norm
Wickens, 2014, for a discussion on how correlation and cosine describing harmony in life: If the score is high the person is seen to
have high harmony in life. Below this analysis is described.
are mathematically related); but in the embedding space the co-
sine between two words is typically not much below 0. The
smaller the angle, the higher the cosine is, and thus, the more # Compute semantic similarity scores between two text columns,
similar are the embeddings (this cosine measure is referred to as using the previously created word_embeddings.
a semantic similarity score). semantic_similarity_scores <- textSimilarity(
The cosine may be seen as an unstandardized effect size indicat- word_embeddings$texts$harmonytexts,
ing the strength of a relationship (Charikar, 2002); however, it word_embeddings$texts$satisfactiontexts
should be noted that its absolute value is not comparable between )
Figure 5
Illustrations of the Supervised Dimension Projection Method
This article is intended solely for the personal use of the individual user and is not to be disseminated broadly.
This document is copyrighted by the American Psychological Association or one of its allied publishers.
Note. The illustration exemplifies the reduction of two dimensions to one dimension, where in practice there
are many more dimensions. See the online article for the color version of this figure.
out different visual settings without the need to rerun the heavy compu-
tational processes. # Pre-processing data for plotting
To plot words, each individual word type needs to be repre- projection_results <- textProjection(
words = Language_based_assessment_data_8$harmonywords,
sented by an embedding: a word type embedding (i.e., a single
word_embeddings = harmony_words_embeddings$texts,
embedding per word type taken from aggregating token embed-
word_types_embeddings = harmony_words_embeddings$word_types,
dings across all instances of all word types in the given data).4 In
x = Language_based_assessment_data_8$hilstotal,
textEmbed() the optional setting aggregation_from_tokens_to_-
y = Language_based_assessment_data_8$age
word_types, controls how the word types embeddings are aggre- )
gated (default = “mean”). projection_results$word_data
textProjection().
Figure 6
A One-Dimensional Plot From textProjectionPlot()
humiliated
hopeless impatient warm happy
extended unstable
anxious sad amazed brotherhood
driven
love content fair sunshine being
incompatible rattled
ashamed unsure
overwhelmed kinship peaceful respectfulcaring well good
accepting positive
scattered
peace
−30 −20 −10 0 10 20 30
Low to High Harmony in Life Scale Score
SDP Frequency
71 142 82 a a a
x
2.5 5.0 7.5
Note. DPP = Dot Product Projection. The dots represent the point for visible words. See the online article for the color version of this
figure.
Figure 7
A Two-Dimensional Plot From textProjectionPlot()
Harmony Words Responses (Supervised Dimension Projection)
fear sadness guilt
nature pleasure being
loss
anger depression feelings caring happy well
10 brotherhood
love fair warm good
Low [Link] Age
unfit
scattered
This document is copyrighted by the American Psychological Association or one of its allied publishers.
SDP Frequency
2 37 0
33 44 64 a a a
y
36 37 18
2.5 5.0 7.5
x
Note. A supervised dimension projection plot of words significantly differing between low versus high harmony in life scale score (x-axis) and low versus high age
(y-axis). The font size of the words indicates their frequency. The color indicates whether a word is significant or not significant (gray) when correcting for multiple
comparisons using the false discovery rate (FDR). The color-legend in the lower left corner indicates the color and number of significant words in each part of the fig-
ure (e.g., there are 18 light green words that are significantly high on the x-axis and low on the y-axis). The dots represent the point for visible words. The values on
the x- and y-axes represent the dot product projection value (these should be compared with caution between figures); DPP = Dot product projection. See the online
article for the color version of this figure.
Figure 8 Benoit, K., Watanabe, K., Wang, H., Nulty, P., Obeng, A., Müller, S., &
A Plot From textCentralityPlot() Matsuo, A. (2018). quanteda: An R package for the quantitative analysis
Satisfaction with life word norm: Semantic Centrality Plot
of textual data. Journal of Open Source Software, 3(30), Article 774.
[Link]
friendship family happiness Bird, S., Klein, E., & Loper, E. (2009). Natural Language Processing with
generous purpose education excellent mind strong
comfortable
friends success
warmth
clothes prepared tv plants food happy fun
love excitement
security Python: Analyzing text with the natural language toolkit. O’Reilly
money health Media, Inc.
Blei, D. M., Ng, A. Y., & Jordan, M. I. (2003). Latent Dirichlet allocation.
0.5 0.6 0 .7 0 .8 0.9
Journal of Machine Learning Research, 3, 993–1022.
Satisfaction with Life Semantic Centrality
Bommasani, R., Hudson, D. A., Adeli, E., Altman, R., Arora, S., von Arx, S.,
Frequency
Bernstein, M. S., Bohg, J., Bosselut, A., & Brunskill, E. (2021). On the
a a a a opportunities and risks of foundation models. arXiv, Preprint
10 20 30 40
ArXiv:2108.07258.
Note. A Semantic Centrality Plot illustrating the words composing the
Borg, I., & Groenen, P. J. (2005). Modern multidimensional scaling: Theory
Satisfaction with life word norm. The size of the words represents their fre-
and applications. Springer Science & Business Media.
This article is intended solely for the personal use of the individual user and is not to be disseminated broadly.
quency, the color their position. The values on the x-axes represent the
Bradley, M. M., & Lang, P. J. (1999). Affective norms for English words
This document is copyrighted by the American Psychological Association or one of its allied publishers.
review, quantitative comparison, and recommendations. Psychological Hossain, N., Krumm, J., Gamon, M., & Kautz, H. (2020). Semeval-2020
Methods, 26(4), 398–427. [Link] Task 7: Assessing humor in edited news headlines. arXiv, Preprint
Eichstaedt, J. C., Schwartz, H. A., Kern, M. L., Park, G., Labarthe, D. R., arXiv:2008.00304. [Link]
Merchant, R. M., Jha, S., Agrawal, M., Dziurzynski, L. A., Sap, M., Iliev, R., Dehghani, M., & Sagi, E. (2015). Automated text analysis in psy-
Weeg, C., Larson, E. E., Ungar, L. H., & Seligman, M. E. (2015). chology: Methods, applications, and future developments. Language
Psychological language on Twitter predicts county-level heart disease and Cognition, 7(2), 265–290. [Link]
mortality. Psychological Science, 26(2), 159–169. [Link] James, G., Witten, D., Hastie, T., Tibshirani, R., Sohil, F., Sohali, M. U., &
.1177/0956797614557867 Shabbir, J. (2021). An introduction to statistical learning with applications
Eichstaedt, J. C., Smith, R. J., Merchant, R. M., Ungar, L. H., Crutchley, P., in R. [Link]
Preoţ iuc-Pietro, D., Asch, D. A., & Schwartz, H. A. (2018). Facebook Jawahar, G., Sagot, B., & Seddah, D. (2019). What does BERT learn about
language predicts depression in medical records. Proceedings of the the structure of language? In ACL 2019-57th Annual Meeting of the
National Academy of Sciences of the United States of America, 115(44), Association for Computational Linguistics, July 2019, Florence, Italy
11203–11208. [Link] (pp. 3651–3657). Association for Computational Linguistics.
Erk, K. (2012). Vector space models of word meaning and phrase meaning: Jurafsky, D., & Martin, J. (2020). Speech and language processing: An intro-
A survey. Language and Linguistics Compass, 6(10), 635–653. https:// duction to Natural Language Processing, computational linguistics, and
This article is intended solely for the personal use of the individual user and is not to be disseminated broadly.
Ethayarajh, K. (2019). How contextual are contextualized word representa- Kern, M. L., Park, G., Eichstaedt, J. C., Schwartz, H. A., Sap, M., Smith, L.
tions? Comparing the geometry of BERT, ELMo, and GPT-2 embeddings. K., & Ungar, L. H. (2016). Gaining insights from social media language:
arXiv, Preprint ArXiv:1909.00512. [Link] Methodologies and challenges. Psychological Methods, 21(4), 507–525.
1006 [Link]
Feinerer, I., & Hornik, K. (2019). tm: Text mining package. [Link] Kjell, K., Johnsson, P., & Sikström, S. (2021). Freely generated word
[Link]/web/packages/tm/ responses analyzed with artificial intelligence predict self-reported symp-
Firth, J. R. (1957). A synopsis of linguistic theory 1930–1955. In F. Palmer toms of depression, anxiety, and worry. Frontiers in Psychology, 12,
(Ed.), Studies in linguistic analysis: Philological Society (reprinted in
Article 602581. [Link]
1968: Selected Papers of J. R. Firth). Longman. Kjell, O. N. E., Daukantaitė, D., Hefferon, K., & Sikström, S. (2016). The
Gagné, C. L., Spalding, T. L., & Ji, H. (2005). Re-examining evidence for the
Harmony in Life Scale Complements the Satisfaction with Life Scale:
use of independent relational representations during conceptual combina-
Expanding the conceptualization of the cognitive component of subjective
tion. Journal of Memory and Language, 53(3), 445–455. [Link]
well-being. Social Indicators Research, 126(2), 893–919. [Link]
10.1016/[Link].2005.03.006
10.1007/s11205-015-0903-z
Gagolewski, M. (2020). R package stringi: Character string processing facil-
Kjell, O. N. E., Kjell, K., Garcia, D., & Sikström, S. (2019). Semantic mea-
ities. [Link]
sures: Using Natural Language Processing to measure, differentiate, and
Ganesan, A. V., Matero, M., Ravula, A. R., Vu, H., & Schwartz, H. A.
describe psychological constructs. Psychological Methods, 24(1), 92–
(2021). Empirical evaluation of pre-trained transformers for human-level
115. [Link]
NLP: The role of sample size and dimensionality. arXiv, Preprint
Kjell, O. N. E., Sikström, S., Kjell, K., & Schwartz, H. A. (2022). Natural
ArXiv:2105.03484. [Link]
language analyzed with AI-based transformers predict traditional subjec-
Ganguli, S., & Sompolinsky, H. (2012). Compressed sensing, sparsity, and
dimensionality in neuronal information processing and data analysis. tive well-being measures approaching the theoretical upper limits in accu-
Annual Review of Neuroscience, 35(1), 485–508. [Link] racy. Scientific Reports, 12(1), Article 3918. [Link]
.1146/annurev-neuro-062111-150410 s41598-022-07520-w
Garcia, D., & Sikström, S. (2013). Quantifying the semantic representations Kuhn, M. (2020). tune: Tidy tuning tools. [Link]
of adolescents’ memories of positive and negative life events. Journal of package=tune
Happiness Studies, 14(4), 1309–1323. [Link] Kuhn, M., & Vaughan, D. (2020a). parsnip: A common API to modeling and
012-9385-8 analysis functions. [Link]
Golub, G., & Kahan, W. (1965). Calculating the singular values and Kuhn, M., & Vaughan, D. (2020b). yardstick: Tidy characterizations of
pseudo-inverse of a matrix. Journal of the Society for Industrial and model performance. [Link]
Applied Mathematics, Series B. Numerical Analysis, 2(2), 205–224. Kuhn, M., & Wickham, H. (2020). recipes: Preprocessing tools to create
[Link] design matrices. [Link]
Grolemund, G., & Wickham, H. (2018). R for data science. O’Reilly Media. Kuhn, M., Chow, F., & Wickham, H. (2020). rsample: General resampling
Henry, L., & Wickham, H. (2020a). purrr: Functional programming tools. infrastructure. [Link]
[Link] Lauriola, I., Lavelli, A., & Aiolli, F. (2022). An introduction to Deep
Henry, L., & Wickham, H. (2020b). rlang: Functions for base types and core Learning in Natural Language Processing: Models, techniques, and
R and “Tidyverse” features. [Link] tools. Neurocomputing, 470, 443–456. [Link]
Ho, T. K. (1995). Random decision forests. In Proceedings of 3rd .2021.05.103
International Conference on Document Analysis and Recognition, Lan, Z., Chen, M., Goodman, S., Gimpel, K., Sharma, P., & Soricut, R.
August 1995 (Vol. 1, pp. 278–282). IEEE Computer Society. (2019). Albert: A lite bert for self-supervised learning of language repre-
Hochreiter, S., & Schmidhuber, J. (1997). Long short-term memory. Neural sentations. arXiv preprint arXiv:1909.11942.
Computation, 9(8), 1735–1780. [Link] Libovickỳ , J., Rosa, R., & Fraser, A. (2019). How language-neutral is mul-
.1735 tilingual BERT? arXiv, Preprint ArXiv:1911.03310.
Hoerl, A. E., & Kennard, R. W. (1970). Ridge regression: Biased estimation Liu, Y., Ott, M., Goyal, N., Du, J., Joshi, M., Chen, D., Levy, O., Lewis, M.,
for nonorthogonal problems. Technometrics, 12(1), 55–67. [Link] Zettlemoyer, L., & Stoyanov, V. (2019). Roberta: A robustly optimized
10.1080/00401706.1970.10488634 BERT pretraining approach. arXiv, Preprint ArXiv:1907.11692.
Honnibal, M., & Montani, I. (2017). spaCy 2: Natural language understand- Matero, M., Hung, A., & Schwartz, H. A. (2021). Understanding RoBERTa’s
ing with Bloom embeddings, convolutional neural networks and incre- mood: The role of contextual-embeddings as user-representations for
mental parsing. Advance online publication. depression prediction. arXiv, Preprint ArXiv:2112.13795.
THE TEXT-PACKAGE 19
Matero, M., Idnani, A., Son, Y., Giorgi, S., Vu, H., Zamani, M., Limbachiya, Robinson, D., & Hayes, A. (2020). broom: Convert statistical analysis
P., Guntuku, S. C., & Schwartz, H. A. (2019). Suicide risk assessment with objects into tidy tibbles. [Link]
multi-level dual-context language and BERT. In Proceedings of the sixth Rogers, A., Kovaleva, O., & Rumshisky, A. (2020). A primer in Bertology:
workshop on computational linguistics and clinical psychology (pp. 39– What we know about how bert works. arXiv, Preprint ArXiv:2002.
44). Association for Computational Linguistics. [Link] 12327.
.18653/v1/W19-3005 Sanh, V., Debut, L., Chaumond, J., & Wolf, T. (2019). DistilBERT, a distilled
Mikolov, T., Sutskever, I., Chen, K., Corrado, G. S., & Dean, J. (2013). version of BERT: Smaller, faster, cheaper and lighter. ArXiv, Preprint
Distributed representations of words and phrases and their compositional- ArXiv:1910.01108.
ity. In NIPS’13: Proceedings of the 26th International Conference on Schwartz, H., Eichstaedt, J., Kern, M., Dziurzynski, L., Lucas, R., Agrawal,
Neural Information Processing Systems (pp. 3111–3119). Curran M., Park, G., Lakshmikanth, S., Jha, S., Seligman, M., & Ungar, L. (2013).
Associates, Inc. Characterizing geographic variation in well-being using tweets.
Morishita, T., Morio, G., Ozaki, H., & Miyoshi, T. (2020). Hitachi at Proceedings of the International AAAI Conference on Web and Social
SemEval-2020 task 7: Stacking at scale with heterogeneous language Media, 7(1), 583–591.
models for humor recognition. In Proceedings of the Fourteenth Schwartz, H. A., Giorgi, S., Sap, M., Crutchley, P., Ungar, L., & Eichstaedt,
Workshop on Semantic Evaluation (pp. 791–803). International J. (2017, September). Dlatk: Differential language analysis toolkit. In
This article is intended solely for the personal use of the individual user and is not to be disseminated broadly.
Wickham, H., & Henry, L. (2020). tidyr: Tidy messy data. [Link] Xie, Y., Allaire, J. J., & Grolemund, G. (2018). R markdown: The definitive
[Link]/package=tidyr guide. CRC Press. [Link]
Wickham, H., & Seidel, D. (2020). scales: Scale functions for visualization. Yang, Z., Dai, Z., Yang, Y., Carbonell, J., Salakhutdinov, R. R., & Le, Q. V.
[Link] (2019). Xlnet: Generalized autoregressive pretraining for language under-
Wickham, H., François, R., Henry, L., & Müller, K. (2020). dplyr: A gram- standing. Advances in neural information processing systems, 32.
mar of data manipulation. [Link] Yarkoni, T., & Westfall, J. (2017). Choosing prediction over explanation in
Wilke, C. O. (2019). cowplot: Streamlined plot theme and plot annotations psychology: Lessons from machine learning. Perspectives on
for “ggplot2.” [Link] Psychological Science, 12(6), 1100–1122. [Link]
Wold, S., Esbensen, K., & Geladi, P. (1987). Principal component analysis. 1745691617693393
Chemometrics and Intelligent Laboratory Systems, 2(1–3), 37–52. https:// Zirikly, A., Resnik, P., Uzuner, O., & Hollingshead, K. (2019). CLPsych
[Link]/10.1016/0169-7439(87)80084-9 2019 shared task: Predicting the degree of suicide risk in Reddit posts.
Wolf, T., Debut, L., Sanh, V., Chaumond, J., Delangue, C., Moi, A., Cistac, In Proceedings of the sixth workshop on computational linguistics and
P., Rault, T., Louf, R., & Funtowicz, M. (2019). Huggingface’s transform- clinical psychology (pp. 24–33). ACL.
ers: State-of-the-art Natural Language Processing. ArXiv:1910.03771v1. Zou, H., & Hastie, T. (2005). Regularization and variable selection via the
Xie, Y. (2014). knitr: A comprehensive tool for reproducible research in R. In elastic net. Journal of the Royal Statistical Society. Series B, Statistical
This article is intended solely for the personal use of the individual user and is not to be disseminated broadly.
V. Stodden, F. Leisch, & R. D. Peng (Eds.), Implementing reproducible Methodology, 67(2), 301–320. [Link]
This document is copyrighted by the American Psychological Association or one of its allied publishers.
(Appendix follows)
THE TEXT-PACKAGE 21
Appendix
PCA Plot
Figure A1
A plot from textPCA()
worried anxious
intelligence
angry depressed
unsure
PC2
love
money family happy cheerful lost
food content positive loved
friends
healthy driven
strong
good
loving
−15 −10 −5 0 5 10
PC1
PC Frequency
0 3 2
a a a a
PC2
5 41 2
0 4 1
4 8 12 16
PC1
Note. See the online article for the color version of this figure.