File size: 12,402 Bytes
5febdea
 
 
 
 
 
 
 
 
 
 
 
 
1d59f5a
5febdea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d59f5a
5febdea
 
 
 
 
1d59f5a
5febdea
1d59f5a
 
 
 
 
 
5febdea
1d59f5a
 
 
 
 
 
 
 
 
 
 
 
5febdea
1d59f5a
 
5febdea
1d59f5a
5febdea
 
1d59f5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5febdea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d59f5a
 
5febdea
 
1d59f5a
5febdea
1d59f5a
5febdea
 
 
 
 
 
 
 
1d59f5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5febdea
1d59f5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5febdea
1d59f5a
 
 
 
 
 
 
 
 
 
 
 
5febdea
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Segmentation scores evaluation metrics"""

import evaluate
import datasets


# TODO: Add BibTeX citation
_CITATION = """\
@InProceedings{huggingface:module,
title = {A great new module},
authors={huggingface, Inc.},
year={2020}
}
"""

# TODO: Add description of the module here
_DESCRIPTION = """\
This module computes segmentation scores for a list of predicted segmentations and gold segmentations.
"""


# TODO: Add description of the arguments of the module here
_KWARGS_DESCRIPTION = """
Calculates how good are predicted segmentations, using boundary, token and type scores.
Args:
    predictions: list of segmented utterances to score. Each predictions
        should be a string with phonemes separated by spaces and estimated word boundaries
        denoted by the token ';eword'.
    references: list of segmented utterances to score. Each predictions
        should be a string with phonemes separated by spaces and gold word boundaries
        denoted by the token ';eword'.
Returns:
    type_fscore: lexicon f1 score
    type_precision: lexicon precision
    type_recall: lexicon recall
    token_fscore: token f1 score
    token_precision: token precision
    token_recall: token recall
    boundary_all_fscore: boundary f1 score, including utterance boundaries
    boundary_all_precision: boundary precision, including utterance boundaries
    boundary_all_recall: boundary recall, including utterance boundaries
    boundary_noedge_fscore: boundary f1 score, excluding utterance boundaries
    boundary_noedge_precision: boundary precision, excluding utterance boundaries
    boundary_noedge_recall: boundary recall, excluding utterance boundaries
Examples:
    >>> segmentation_scores = evaluate.load("transformersegmentation/segmentation_scores")
    >>> results = segmentation_scores.compute(references=["w ɛ ɹ ;eword ɪ z ;eword ð ɪ s ;eword", "l ɪ ɾ əl ;eword aɪ z ;eword"], predictions=["w ɛ ɹ ;eword ɪ z ;eword ð ɪ s ;eword", "l ɪ ɾ əl ;eword aɪ z ;eword"])
    >>> print(results)
    {'type_fscore': 1.0, 'type_precision': 1.0, 'type_recall': 1.0, 'token_fscore': 1.0, 'token_precision': 1.0, 'token_recall': 1.0, 'boundary_all_fscore': 1.0, 'boundary_all_precision': 1.0, 'boundary_all_recall': 1.0, 'boundary_noedge_fscore': 1.0, 'boundary_noedge_precision': 1.0, 'boundary_noedge_recall': 1.0}
"""

class TokenEvaluation(object):
    """Evaluation of token f-score, precision and recall"""

    def __init__(self):
        self.test = 0
        self.gold = 0
        self.correct = 0
        self.n = 0
        self.n_exactmatch = 0

    def precision(self):
        return float(self.correct) / self.test if self.test != 0 else None

    def recall(self):
        return float(self.correct) / self.gold if self.gold != 0 else None

    def fscore(self):
        total = self.test + self.gold
        return float(2 * self.correct) / total if total != 0 else None

    def exact_match(self):
        return float(self.n_exactmatch) / self.n if self.n else None

    def update(self, test_set, gold_set):
        self.n += 1

        if test_set == gold_set:
            self.n_exactmatch += 1

        # omit empty items for type scoring (should not affect token
        # scoring). Type lists are prepared with '_' where there is no
        # match, to keep list lengths the same
        self.test += len([x for x in test_set if x != "_"])
        self.gold += len([x for x in gold_set if x != "_"])
        self.correct += len(test_set & gold_set)

    def update_lists(self, test_sets, gold_sets):
        if len(test_sets) != len(gold_sets):
            raise ValueError(
                "#words different in test and gold: {} != {}".format(
                    len(test_sets), len(gold_sets)
                )
            )

        for t, g in zip(test_sets, gold_sets):
            self.update(t, g)


class TypeEvaluation(TokenEvaluation):
    """Evaluation of type f-score, precision and recall"""

    @staticmethod
    def lexicon_check(textlex, goldlex):
        """Compare hypothesis and gold lexicons"""
        textlist = []
        goldlist = []
        for w in textlex:
            if w in goldlex:
                # set up matching lists for the true positives
                textlist.append(w)
                goldlist.append(w)
            else:
                # false positives
                textlist.append(w)
                # ensure matching null element in text list
                goldlist.append("_")

        for w in goldlex:
            if w not in goldlist:
                # now for the false negatives
                goldlist.append(w)
                # ensure matching null element in text list
                textlist.append("_")

        textset = [{w} for w in textlist]
        goldset = [{w} for w in goldlist]
        return textset, goldset

    def update_lists(self, text, gold):
        lt, lg = self.lexicon_check(text, gold)
        super(TypeEvaluation, self).update_lists(lt, lg)


class BoundaryEvaluation(TokenEvaluation):
    @staticmethod
    def get_boundary_positions(stringpos):
        return [{idx for pair in line for idx in pair} for line in stringpos]

    def update_lists(self, text, gold):
        lt = self.get_boundary_positions(text)
        lg = self.get_boundary_positions(gold)
        super(BoundaryEvaluation, self).update_lists(lt, lg)


class BoundaryNoEdgeEvaluation(BoundaryEvaluation):
    @staticmethod
    def get_boundary_positions(stringpos):
        return [{left for left, _ in line if left > 0} for line in stringpos]


class _StringPos(object):
    """Compute start and stop index of words in an utterance"""

    def __init__(self):
        self.idx = 0

    def __call__(self, n):
        """Return the position of the current word given its length `n`"""
        start = self.idx
        self.idx += n
        return start, self.idx
    


@evaluate.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
class segmentation_scores(evaluate.Metric):
    """TODO: Short description of my evaluation module."""

    def _info(self):
        # TODO: Specifies the evaluate.EvaluationModuleInfo object
        return evaluate.MetricInfo(
            # This is the description that will appear on the modules page.
            module_type="metric",
            description=_DESCRIPTION,
            citation=_CITATION,
            inputs_description=_KWARGS_DESCRIPTION,
            # This defines the format of each prediction and reference
            features=datasets.Features({
                'predictions': datasets.Value('string'),
                'references': datasets.Value('string'),
            }),
            # Homepage of the module for documentation
            homepage="https://huggingface.co/spaces/transformersegmentation/segmentation_scores",
            # Additional links to the codebase or references
            codebase_urls=["http://github.com/codebyzeb/transformersegmentation"],
            reference_urls=["http://path.to.reference.url/new_module"]
        )

    def _download_and_prepare(self, dl_manager):
        """Optional: download external resources useful to compute the scores"""
        # TODO: Download external resources if needed
        pass

    def _process_data(self, text):
        """ Load text data for evaluation
        Parameters
        ----------
        text : list of str
            The list of utterances to read for the evaluation.

        Returns
        -------
        (words, positions, lexicon) : three lists
            where `words` are the input utterances with word separators
            removed, `positions` stores the start/stop index of each word
            for each utterance, and `lexicon` is the list of words.
        """
        words = []
        positions = []
        lexicon = {}

        # ignore empty lines
        for utt in (utt for utt in text if utt.strip()):
            # list of phones in the utterance with word seperator removed
            phone_in_utterance = [
                phone for phone in utt.split(" ") if phone != ";eword"
            ]
            words_in_utterance = (
                "".join(
                    " " if phone == ";eword" else phone for phone in utt.split(" ")
                )
                .strip()
                .split(" ")
            )

            words.append(phone_in_utterance)
            for word in words_in_utterance:
                lexicon[word] = 1
            idx = _StringPos()
            positions.append({idx(len(word)) for word in words_in_utterance})

        # return the words lexicon as a sorted list
        lexicon = sorted([k for k in lexicon.keys()])
        return words, positions, lexicon
    
    def _compute(self, predictions, references):
        """Scores a segmented text against its gold version
        Parameters
        ----------
        predictions : sequence of str
            A suite of word utterances, each string using ';eword' as as word separator.
        references : sequence of str
            A suite of word utterances, each string using ';eword' as as word separator.

        Returns
        -------
        scores : dict
            A dictionary with the following entries:
            * 'type_fscore'
            * 'type_precision'
            * 'type_recall'
            * 'token_fscore'
            * 'token_precision'
            * 'token_recall'
            * 'boundary_all_fscore'
            * 'boundary_all_precision'
            * 'boundary_all_recall'
            * 'boundary_noedge_fscore'
            * 'boundary_noedge_precision'
            * 'boundary_noedge_recall'

        Raises
        ------
        ValueError
            If `gold` and `text` have different size or differ in tokens
        """
        text_words, text_stringpos, text_lex = self._process_data(predictions)
        gold_words, gold_stringpos, gold_lex = self._process_data(references)

        if len(gold_words) != len(text_words):
            raise ValueError(
                "gold and train have different size: len(gold)={}, len(train)={}".format(
                    len(gold_words), len(text_words)
                )
            )

        for i, (g, t) in enumerate(zip(gold_words, text_words)):
            if g != t:
                raise ValueError(
                    'gold and train differ at line {}: gold="{}", train="{}"'.format(
                        i + 1, g, t
                    )
                )

        # token evaluation
        token_eval = TokenEvaluation()
        token_eval.update_lists(text_stringpos, gold_stringpos)

        # type evaluation
        type_eval = TypeEvaluation()
        type_eval.update_lists(text_lex, gold_lex)

        # boundary evaluation (with edges)
        boundary_eval = BoundaryEvaluation()
        boundary_eval.update_lists(text_stringpos, gold_stringpos)

        # boundary evaluation (no edges)
        boundary_noedge_eval = BoundaryNoEdgeEvaluation()
        boundary_noedge_eval.update_lists(text_stringpos, gold_stringpos)

        return {
            "token_precision": token_eval.precision(),
            "token_recall": token_eval.recall(),
            "token_fscore": token_eval.fscore(),
            "type_precision": type_eval.precision(),
            "type_recall": type_eval.recall(),
            "type_fscore": type_eval.fscore(),
            "boundary_all_precision": boundary_eval.precision(),
            "boundary_all_recall": boundary_eval.recall(),
            "boundary_all_fscore": boundary_eval.fscore(),
            "boundary_noedge_precision": boundary_noedge_eval.precision(),
            "boundary_noedge_recall": boundary_noedge_eval.recall(),
            "boundary_noedge_fscore": boundary_noedge_eval.fscore(),
        }