File size: 7,213 Bytes
622a08e
 
 
 
 
 
 
 
 
fbc7132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32cb66f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbc7132
 
 
 
 
39ad3df
fbc7132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1cef5ad
fbc7132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94368bd
fbc7132
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
---
datasets:
- AU-STANDBY/annotated_constructive_dataset_DA_EN
language:
- en
- da
base_model:
- intfloat/multilingual-e5-large
pipeline_tag: text-classification
---

# Multilingual Multi-task Classifier for Constructive Speech, Hateful Speech, and Agreement

## Model description

This model is a multilingual, multi-task classifier developed as part of the STANDBY research project. It is designed to classify text along three dimensions:

1) Hateful speech

2) Constructive speech

3) Agreement

The classifier is designed to capture these dimensions independently rather than treating them as mutually exclusive categories. Consequently, a text can for example simultaneously be classified as hateful and constructive.

The model supports both English and Danish.

## Model variants

Two model variants are available:

1) Non-context-enriched: Classifies a response independently, without additional conversational context.

2) Context-enriched: Classifies a response using both the reference text and the response, allowing the model to take the conversational context into account.

For the context-enriched model, the input should be formatted as:

[reference text] [SEP] [response text]

where [SEP] is the tokenizer's separator token.

The non-context-enriched model can be found [here](https://huggingface.co/AU-STANDBY/constructive_classifier_EN_DA_non_context_enriched)

## Base model

The classifier is built on top of intfloat/multilingual-e5-large.

## Labels and model outputs

The model produces nine output logits, divided into three separate classification tasks. A softmax function is applied independently to each task, resulting in three probability distributions.


| Task | Class 0 | Class 1 | Class 2 |
|---|---|---|---|
| Hateful speech | Not Hateful | Hateful | Unclassifiable Hateful |
| Constructive speech | Not Constructive | Constructive | Unclassifiable Constructive |
| Agreement | Agree | Disagree | Unclear |

Each task produces:

1) Label: The predicted class (the class with the highest probability).

2) Score: The probability assigned to the predicted class.

3) Probabilities: The probabilities for all three classes within that task.

## Model performance

<table>
  <thead>
    <tr>
      <th colspan="4">Constructive</th>
      <th colspan="4">Hate</th>
      <th colspan="4">Agree</th>
      <th>Avg. F1</th>
    </tr>
    <tr>
      <th>Y</th>
      <th>N</th>
      <th>U</th>
      <th>F1</th>
      <th>Y</th>
      <th>N</th>
      <th>U</th>
      <th>F1</th>
      <th>A</th>
      <th>D</th>
      <th>U</th>
      <th>F1</th>
      <th>&nbsp;</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>.79</td>
      <td>.93</td>
      <td>.60</td>
      <td><b>.88</b></td>
      <td>.67</td>
      <td>.91</td>
      <td>.62</td>
      <td><b>.86</b></td>
      <td>.74</td>
      <td>.81</td>
      <td>.54</td>
      <td><b>.72</b></td>
      <td><b>.82</b></td>
    </tr>
  </tbody>
</table>

The table presents the model's performance across three classification tasks: constructive speech, hate speech, and agreement. For constructive and hate speech, Y = Yes, N = No, and U = Unclassifiable. For agreement, A = Agree, D = Disagree, and U = Unclear. F1 scores are reported for each task, alongside the average F1 score across all three tasks.

## Data preprocessing

For optimal consistency with the training data, it is recommended to apply the same text preprocessing before classification.

```python
import re
def preprocess_text(text):
    #e.g. @PeterNice123 -> @user
    text = re.sub(r'@\w+', '@user', text)
    # https -> <link>
    text = re.sub(r'http\S+', '<link>', text)
    return text

df['text'] = df['text'].apply(preprocess_text)
```


## Usage

The following code demonstrates how to load and use the model on example texts.

```python
import pandas as pd
import numpy as np
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification

model_id = "AU-STANDBY/constructive_classifier_EN_DA_context_enriched"

tokenizer = AutoTokenizer.from_pretrained(model_id, token=True)
model = AutoModelForSequenceClassification.from_pretrained(
    model_id,
    token=True
)

model.eval()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)

label_classes = {
    "hateful": [
        "Not Hateful",
        "Hateful",
        "Unclassifiable Hateful"
    ],
    "constructive": [
        "Not Constructive",
        "Constructive",
        "Unclassifiable Constructive"
    ],
    "agree": [
        "Agree",
        "Disagree",
        "Unclear"
    ]
}


def predict_texts(rep_texts, ref_texts, tokenizer, model):

    # Tokenize reference and response as a pair,
    # following the exact structure used during training
    encoded_data = tokenizer(
        ref_texts,
        rep_texts,
        padding="max_length",
        truncation=True,
        max_length=512,
        return_attention_mask=True,
        return_tensors="pt"
    )

    input_ids = encoded_data["input_ids"].to(device)
    attention_mask = encoded_data["attention_mask"].to(device)

    with torch.inference_mode():
        outputs = model(
            input_ids=input_ids,
            attention_mask=attention_mask
        )

    logits = outputs.logits

    # Split the 9 logits into the three classification tasks
    logits_groups = {
        "hateful": logits[:, :3],
        "constructive": logits[:, 3:6],
        "agree": logits[:, 6:9]
    }

    # Calculate probabilities separately for each task
    probabilities = {
        task: torch.softmax(group_logits, dim=1).cpu().numpy()
        for task, group_logits in logits_groups.items()
    }

    results = []

    for i, (rep_text, ref_text) in enumerate(zip(rep_texts, ref_texts)):

        row = {
            "text": rep_text,
            "ref_text": ref_text
        }

        for task, probs in probabilities.items():

            # Predicted class and its probability
            pred_idx = np.argmax(probs[i])
            pred_score = probs[i][pred_idx]

            row[f"{task}_label"] = label_classes[task][pred_idx]
            row[f"{task}_score"] = float(pred_score)

            # Probability for each of the three labels
            for k, label in enumerate(label_classes[task]):
                row[f"{task}_prob_{k}"] = float(probs[i][k])

        results.append(row)

    return results

rep_texts = [
    "I appreciate your perspective, and I think you make a good point.",
    "You are completely wrong and your argument makes no sense.",
    "I strongly disagree with what you are saying.",
    "Thank you for sharing your opinion. I understand where you are coming from."
]

ref_texts = [
    "I think we should consider both sides of the issue before making a decision.",
    "Everyone who disagrees with me is an idiot.",
    "This policy is clearly the best solution to the problem.",
    "I don't think your argument is supported by the evidence."
]

predictions_df = pd.DataFrame(
    predict_texts(rep_texts, ref_texts, tokenizer, model)
)

```

## Citation

If you use this model, please cite:

[LINK]

## Contact

For questions please contact:

- Ida Dencker / ida3mail@gmail.com
- Simon Karg / simonkarg@ps.au.dk