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:
Unlike category-specific models, task-specific encoder models let us classify any category we like. As an example, we use the NLI model by Laurer et al. (2024) here.
Instead of the model used here, you can also use other task-specific encoder models (usually labeled for “Zero-Shot-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.
For classification with the NLI model, in addition to the model we also specify the category of interest as a candidate label (candidate_labels) and a “hypothesis” that will be checked against the text (hypothesis_template). When the pipeline() command runs, the category value is automatically inserted in place of the curly braces in the hypothesis. To run the classification, we apply the previously defined zeroshot_classifier command to our text data. We then extract the probability assigned to fear. We save the result in a DataFrame object for a clear overview.
Python
fear probabilities into a DataFrame for a clear overview
text fear_score
0 I feel helpless and afraid like never before 0.999899
1 No commute; sunny day; my kids laughing; being... 0.000050
2 Feeling scared and lonely, can't wait for this... 0.997561
3 It's gonna get tougher but we will get through... 0.006027
4 I am terrified by what is happening. I’m scare... 0.999911
5 Stay inside, stay safe, and this madness will ... 0.991620
6 I am scared that I will get sick and die, and ... 0.999891
7 Feeling relaxed and happy but I understand tha... 0.048903
8 I am very scared and worried about contracting... 0.999924
9 I'm confident we will get through this crisis. 0.003629