Xaver Maria Krückl commited on
Predict fix
Browse files
README.md
CHANGED
|
@@ -86,20 +86,38 @@ model.eval()
|
|
| 86 |
### Inference
|
| 87 |
|
| 88 |
```python
|
| 89 |
-
|
| 90 |
-
inputs = tokenizer(text, return_tensors="pt", return_offsets_mapping=False)
|
| 91 |
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
|
| 96 |
-
tags = [id2label[i] for i in tag_ids[0]]
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
```
|
| 101 |
|
| 102 |
-
> **Note:**
|
| 103 |
|
| 104 |
## Limitations
|
| 105 |
|
|
|
|
| 86 |
### Inference
|
| 87 |
|
| 88 |
```python
|
| 89 |
+
import torch
|
|
|
|
| 90 |
|
| 91 |
+
text = "The cat sat on the mat. It looked around the room."
|
| 92 |
+
encoding = tokenizer(text, return_tensors="pt")
|
| 93 |
+
|
| 94 |
+
with torch.no_grad():
|
| 95 |
+
tag_ids = model.predict(encoding["input_ids"], encoding["attention_mask"])
|
| 96 |
|
| 97 |
+
id2label = config.id2label # {0: "B-EDU", 1: "I-EDU", 2: "O"}
|
|
|
|
| 98 |
|
| 99 |
+
# During training only the *first* sub-token of each word received a real label;
|
| 100 |
+
# subsequent sub-tokens were masked (-100, treated as O by the CRF).
|
| 101 |
+
# Use word_ids() to collapse sub-token predictions back to word level.
|
| 102 |
+
raw_tag_ids = tag_ids[0]
|
| 103 |
+
word_ids = encoding.word_ids(batch_index=0)
|
| 104 |
+
|
| 105 |
+
words, word_tags = [], []
|
| 106 |
+
prev_word_idx = None
|
| 107 |
+
for pos, word_idx in enumerate(word_ids):
|
| 108 |
+
if word_idx is None:
|
| 109 |
+
continue # skip [CLS] / [SEP]
|
| 110 |
+
if word_idx != prev_word_idx:
|
| 111 |
+
word = tokenizer.decode(encoding["input_ids"][0, pos]).strip()
|
| 112 |
+
words.append(word)
|
| 113 |
+
word_tags.append(id2label[raw_tag_ids[pos]])
|
| 114 |
+
prev_word_idx = word_idx
|
| 115 |
+
|
| 116 |
+
for word, tag in zip(words, word_tags):
|
| 117 |
+
print(f"{word:20s} {tag}")
|
| 118 |
```
|
| 119 |
|
| 120 |
+
> **Note:** `model.predict()` returns one tag per sub-token. Because non-first sub-tokens were masked during training they are always predicted as `O` and should be ignored — the snippet above reads only the first sub-token of each word via `word_ids()`. `B-EDU` marks the start of a new situation-entity segment; `I-EDU` marks its continuation; `O` marks tokens outside any segment.
|
| 121 |
|
| 122 |
## Limitations
|
| 123 |
|