General models
Trained on many corpora at once, for any kind of text.
General models are trained on many corpora at once and work on any kind of text. They differ in whether they know whose emotion is meant (perspective) and in the corpora they were trained on. All four are in the cross-corpus comparison.
| General model | Perspective | Trained on | Predicts | Used in | Download |
|---|---|---|---|---|---|
| No perspective model‡ | none: one fixed token | 27 corpora, labels made by people | categories, valence and arousal, appraisals, components, event check | demo, batch processing, case studies | yes |
| Perspective model‡ | you choose: writer, experiencer, reader, not specified | the same 27 corpora | the same outputs | demo, batch processing | yes |
| 30-corpora model‡ | none | 30 of our and other groups' corpora, also automatically labelled ones | categories | demo, batch processing | yes, for non-commercial research only |
| Our-corpora model | none | our corpora that allow commercial use | categories | download only | yes |
‡ Available in the demo and batch processing. The case studies use the no perspective model.
All four models are also tested on corpora they were trained on, always on other texts, so their overall averages in the cross-corpus comparison do not show how well they work on a new corpus. Below the Emotions table, a separate comparison uses only corpora outside the training data of all four, together with the prompted language models.
Downloads
All model weights are published on Hugging Face.
| Model | Type | Architecture | Language | Labels | Validation macro-F1 | License |
|---|
Each repository on Hugging Face has the weights (in half precision), a README and card.json with the labels, thresholds and training data. Please cite the papers of the corpora a model was trained on.
How to use the no perspective model and the perspective model
The code below is for the no perspective model, which does not distinguish whose emotion is meant: every text starts with the same token, [not-specified]. For the perspective model, use the code in the README of its model folder: it takes the perspective as an argument. Both have output layers for the ratings and for the event check in heads.pt. Appraisals are only meaningful for texts that describe an event.
Show code
import json, torch
from huggingface_hub import hf_hub_download
from transformers import AutoModelForSequenceClassification, AutoTokenizer
repo = "bamnlp/emotionhub-xlmr-base-general-dims"
tokenizer = AutoTokenizer.from_pretrained(repo)
model = AutoModelForSequenceClassification.from_pretrained(repo).float().eval()
card = json.load(open(hf_hub_download(repo, "card.json")))
state = torch.load(hf_hub_download(repo, "heads.pt"), map_location="cpu")
# one small output layer per kind of rating (and one for the event check), on the first token's last hidden state
size = model.config.hidden_size
heads = {}
for task, dims in {**card["aux_dims"], "event_gate": ["event"]}.items():
head = torch.nn.Sequential(torch.nn.Dropout(0.1), torch.nn.Linear(size, size), torch.nn.Tanh(),
torch.nn.Dropout(0.1), torch.nn.Linear(size, len(dims)))
prefix = "heads." + task.replace(":", "__") + ".net."
head.load_state_dict({k[len(prefix):]: v for k, v in state.items() if k.startswith(prefix)})
heads[task] = head.eval()
def predict(texts): # the model knows one prefix only
batch = tokenizer([f"[not-specified] {t}" for t in texts], padding=True, truncation=True, max_length=256,
return_tensors="pt")
with torch.no_grad():
out = model(**batch, output_hidden_states=True)
first = out.hidden_states[-1][:, 0]
return torch.sigmoid(out.logits), {t: torch.sigmoid(h(first)) for t, h in heads.items()}
texts = ["I finally got the letter of acceptance!", "Do you think dogs are better than cats?"]
probs, dims = predict(texts)
for i, text in enumerate(texts):
emotions = [l for l, x in zip(card["labels"], probs[i]) if x >= card["thresholds"][l]]
print(text, emotions or [card["labels"][int(probs[i].argmax())]])
print(" valence, arousal:", [round(v, 2) for v in dims["va"][i].tolist()])
if dims["event_gate"][i, 0] >= card["event_gate"]["threshold"]: # appraisals only for texts that describe an event
print(" appraisals:", {d: round(v, 2) for d, v in zip(card["aux_dims"]["core"], dims["core"][i].tolist())})
else:
print(" no event described: no appraisals")
How to use these models
The models are Transformers for multi-label classification. If your texts differ from the training data and you have a few hundred labelled texts, we recommend tuning the thresholds on them. With fewer than about 100 texts, stick to our thresholds.
Show code
import json, torch
from huggingface_hub import hf_hub_download
from transformers import AutoModelForSequenceClassification, AutoTokenizer
repo = "bamnlp/emotionhub-xlmr-base-general" # or any model below
tokenizer = AutoTokenizer.from_pretrained(repo)
model = AutoModelForSequenceClassification.from_pretrained(repo).float().eval()
card = json.load(open(hf_hub_download(repo, "card.json"))) # labels and tuned thresholds
texts = ["I finally got the letter of acceptance!", "They lied to us, again."]
batch = tokenizer(texts, padding=True, truncation=True, max_length=256, return_tensors="pt")
with torch.no_grad():
probs = torch.sigmoid(model(**batch).logits)
for text, p in zip(texts, probs):
emotions = [l for l, x in zip(card["labels"], p) if x >= card["thresholds"][l]]
print(text, emotions or [card["labels"][int(p.argmax())]]) # at least the most probable one

