2016-11-11 7 views
7

Я импортировал nltk в python для вычисления показателя BLEU на Ubuntu. Я понимаю, как работает уровень BLEU на уровне предложения, но я не понимаю, как работает уровень BLEU на уровне корпуса.NLTK: уровень уровня bleu vs на уровне предложения BLEU

Ниже приведен код для корпуса уровня балла BLEU:

import nltk 

hypothesis = ['This', 'is', 'cat'] 
reference = ['This', 'is', 'a', 'cat'] 
BLEUscore = nltk.translate.bleu_score.corpus_bleu([reference], [hypothesis], weights = [1]) 
print(BLEUscore) 

По какой-то причине, оценка бьет является 0 для указанной выше коды. Я ожидал, что уровень BLEU на уровне корпуса не менее 0,5.

Вот мой код для предложения уровня BLEU оценка

import nltk 

hypothesis = ['This', 'is', 'cat'] 
reference = ['This', 'is', 'a', 'cat'] 
BLEUscore = nltk.translate.bleu_score.sentence_bleu([reference], hypothesis, weights = [1]) 
print(BLEUscore) 

Здесь счет BLEU предложение на уровне 0,71, который я ожидал, принимая во внимание краткость-штраф и пропущенное слово «а». Тем не менее, я не понимаю, как работает уровень BLEU на уровне корпуса.

Любая помощь будет оценена по достоинству.

+0

Надеюсь, документация и доктрина est/unittest в коде поможет вам. Но, пожалуйста, потяните последнюю версию 'nltk', чтобы иметь стабилизированную версию BLEU. На самом деле, как вы используете эту функцию, это не совсем правильно, объясните в ответе =) – alvas

+0

из википедии, может быть интересна этой линии опроса. «BLEU предназначен для оценки человеческого суждения на уровне корпуса и плохо работает, если используется для оценки качества отдельных предложений». Может быть, линия опроса не относится к метрике. –

ответ

11

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 
+0

Как насчет верхних букв и низких букв – tktktk0711

+0

См. Https://stackoverflow.com/questions/5541745/get-rid-of-stopwords-and-punctuation – alvas

+0

Попробуйте это для себя; P Также обратите внимание, что BLEU был никогда не предназначался для вычисления уровня предложения. Это метрика уровня тела. – alvas

3

Давайте посмотрим:

>>> help(nltk.translate.bleu_score.corpus_bleu) 
Help on function corpus_bleu in module nltk.translate.bleu_score: 

corpus_bleu(list_of_references, hypotheses, weights=(0.25, 0.25, 0.25, 0.25), smoothing_function=None) 
    Calculate a single corpus-level BLEU score (aka. system-level BLEU) for all 
    the hypotheses and their respective references. 

    Instead of averaging the sentence level BLEU scores (i.e. marco-average 
    precision), the original BLEU metric (Papineni et al. 2002) accounts for 
    the micro-average precision (i.e. summing the numerators and denominators 
    for each hypothesis-reference(s) pairs before the division). 
    ... 

Вы находитесь в лучшем положении, чем я, чтобы понять описание алгоритма, так что я не буду пытаться «объяснить» это вам. Если докштрина не до конца разобралась, взгляните на the source. Или найти его на месте:

>>> nltk.translate.bleu_score.__file__ 
'.../lib/python3.4/site-packages/nltk/translate/bleu_score.py' 
+0

Очень приятно, должен был посмотреть исходный код. Помогло мне разобраться –