TL; DR:
>>> import nltk
>>> hypothesis = ['This', 'is', 'cat']
>>> reference = ['This', 'is', 'a', 'cat']
>>> references = [reference] # list of references for 1 sentence.
>>> list_of_references = [references] # list of references for all sentences in corpus.
>>> list_of_hypotheses = [hypothesis] # list of hypotheses that corresponds to list of references.
>>> nltk.translate.bleu_score.corpus_bleu(list_of_references, list_of_hypotheses)
0.6025286104785453
>>> nltk.translate.bleu_score.sentence_bleu(references, hypothesis)
0.6025286104785453
(Примечание: Вы должны вытащить последнюю версию NLTK на develop
ветви для того, чтобы получить стабильную версию осуществление счет BLEU)
В Лонг:
Фактически, если в вашем корпусе есть только одна ссылка и одна гипотеза, то оба corpus_bleu()
и sentence_bleu()
должны возвращать то же значение, что и в приведенном выше примере.
В коде, мы видим, что sentence_bleu
is actually a duck-type of corpus_bleu
:
def sentence_bleu(references, hypothesis, weights=(0.25, 0.25, 0.25, 0.25),
smoothing_function=None):
return corpus_bleu([references], [hypothesis], weights, smoothing_function)
И если мы посмотрим на параметры для sentence_bleu
:
def sentence_bleu(references, hypothesis, weights=(0.25, 0.25, 0.25, 0.25),
smoothing_function=None):
""""
:param references: reference sentences
:type references: list(list(str))
:param hypothesis: a hypothesis sentence
:type hypothesis: list(str)
:param weights: weights for unigrams, bigrams, trigrams and so on
:type weights: list(float)
:return: The sentence-level BLEU score.
:rtype: float
"""
Вход для sentence_bleu
ссылок «s является list(list(str))
.
Итак, если у вас есть строка предложения, например. "This is a cat"
, вы должны сделать это, чтобы получить список строк, ["This", "is", "a", "cat"]
и так как он позволяет использовать несколько ссылок, это должен быть список списка строк, например.если у вас есть вторая ссылка, «Это кошачий», ваш вход sentence_bleu()
будет:
references = [ ["This", "is", "a", "cat"], ["This", "is", "a", "feline"] ]
hypothesis = ["This", "is", "cat"]
sentence_bleu(references, hypothesis)
Когда дело доходит до corpus_bleu()
list_of_references параметров, это в основном a list of whatever the sentence_bleu()
takes as references:
def corpus_bleu(list_of_references, hypotheses, weights=(0.25, 0.25, 0.25, 0.25),
smoothing_function=None):
"""
:param references: a corpus of lists of reference sentences, w.r.t. hypotheses
:type references: list(list(list(str)))
:param hypotheses: a list of hypothesis sentences
:type hypotheses: list(list(str))
:param weights: weights for unigrams, bigrams, trigrams and so on
:type weights: list(float)
:return: The corpus-level BLEU score.
:rtype: float
"""
Другое не смотреть в доктрине в nltk/translate/bleu_score.py
вы также можете взглянуть на unittest на nltk/test/unit/translate/test_bleu_score.py
, чтобы узнать, как использовать каждый из компонентов в пределах bleu_score.py
.
Кстати, поскольку sentence_bleu
импортируется как bleu
в (nltk.translate.__init__.py
] (https://github.com/nltk/nltk/blob/develop/nltk/translate/init.py#L21), используя
from nltk.translate import bleu
будет такой же, как:
from nltk.translate.bleu_score import sentence_bleu
и в коде:
>>> from nltk.translate import bleu
>>> from nltk.translate.bleu_score import sentence_bleu
>>> from nltk.translate.bleu_score import corpus_bleu
>>> bleu == sentence_bleu
True
>>> bleu == corpus_bleu
False
Надеюсь, документация и доктрина est/unittest в коде поможет вам. Но, пожалуйста, потяните последнюю версию 'nltk', чтобы иметь стабилизированную версию BLEU. На самом деле, как вы используете эту функцию, это не совсем правильно, объясните в ответе =) – alvas
из википедии, может быть интересна этой линии опроса. «BLEU предназначен для оценки человеческого суждения на уровне корпуса и плохо работает, если используется для оценки качества отдельных предложений». Может быть, линия опроса не относится к метрике. –