Python
print("Hello! 👋")- 1
- This is a simple Python command that prints the text “Hello” to the console. The output appears below the code block.
Hello! 👋
To run or modify the example code yourself, you can open and download the Jupyter notebook underlying this page via the sidebar.
No problem! Explanations for the individual steps of the code are hidden behind the numbers on the right. Simply hover your mouse over the number to see the explanation. Where the respective code is executed (in Python, R, or the terminal) is shown in the header of the code block.
Regardless of the model used, we first load the already-installed packages as well as our text data, and store it in a list object:
Here we use a category-specific encoder model for emotion classification, fine-tuned on the GoEmotions dataset (Demszky et al., 2020). This model is freely available on Hugging Face and can be loaded directly via the pipeline() function. As needed, further parameters can be specified in this function, which can be found in the Hugging Face documentation (e.g., long texts may need to be shortened, depending on the model’s maximum input length; truncation=True). Also, please note that running the pipeline() command can sometimes take a while, especially the first time, since the LLM needs to be downloaded and loaded.
Instead of the model used here, you can also use other category-specific encoder models (usually labeled for “Text Classification”) for different languages and use cases. An overview of available models can be found on Hugging Face. Make sure that the chosen model is suitable for your specific task (e.g. sentiment analysis, topic classification, etc.) and supports the language of your texts.
Since this is a category-specific model, it was trained once on one fixed set of labels — here, the 28 GoEmotions categories. Conveniently, fear is already one of those 28 categories. We request scores for all labels (top_k=None) so we can pick out the fear entry for each text.
Python
fear specifically
Now we apply the model to our list of texts and pick out each text’s fear score.
Python
fear score for each text from that list of 28 scores
fear scores into a DataFrame for a clear overview
text fear_score
0 I feel helpless and afraid like never before 0.860037
1 No commute; sunny day; my kids laughing; being... 0.000854
2 Feeling scared and lonely, can't wait for this... 0.861225
3 It's gonna get tougher but we will get through... 0.008892
4 I am terrified by what is happening. I’m scare... 0.903767
5 Stay inside, stay safe, and this madness will ... 0.005280
6 I am scared that I will get sick and die, and ... 0.896429
7 Feeling relaxed and happy but I understand tha... 0.002808
8 I am very scared and worried about contracting... 0.804676
9 I'm confident we will get through this crisis. 0.007578