Курсы машинного перевода для языков России/Раздел 4

From Apertium
Jump to navigation Jump to search

Цель данного раздела дать описание процессам лексической передачи и лексического выбора. В теоретической части более подробно будет описано почему передаваемый словарь (или двуязычный словарь) не всегда только соответствие между леммами/частями речи в одном языке и леммами/частями речи в другом языке. В практической части мы добавим три записи, The theory section will cover some details of why a transfer lexicon (or bilingual dictionary) cannot always be just correspondences between lemmas/parts-of-speech in one language and lemmas/parts-of-speech in another. In the practice section, we will add three entries, a simple one-to-one entry, a many-to-one entry and a one-to-many entry.

Теория

Существует два аспекта лексической передачи, первая - выбор наиболее подходящего перевода, вторая - выделение в записях тех особых характеристик, которые нужно согласовывать с правилами. the first is choosing the most adequate translation, the second is marking in the entries features which need to be inferred by transfer rules. Например, выбор наиболее подходящего русского перевода для чувашского слова тӳпе, когда существует несколько вариантов переводов, включая вершина, крыша и небо - это пример первого аспекта, а выбор единственного или множественного числа при переводе русского слова брюки на татарский (например чалбар, чалбарлар) - это пример второго аспекта перевода лексики.

Переводные эквиваленты

Простая модель перевода - это когда вы берете по очереди каждое слово из предложения на языке-оригинале, находите переводной эквивалент в языке перевода и заменяете слова. Это модель проблематична, потому что отношения между словами в языке источнике и языке перевода, это не один к одному, а множество к множеству, потому что слова могут быть "полисемичны" (многозначны) и этим значениям могут соответствовать различные переводы. Один из способов расширить эту простую модель перевода - снять омонимию со слов, опираясь на лексическую категорию или принадлежность к части речи. Например, киргизское слово жаз может быть как глаголом, так и существительным, что в свою очередь может на русский язык соответственно переводиться как писать или весна.

Chuvash Russian
тӳпе вершина
тăрă вершина
тӳпе небо
тӳпе крыша
...

Это пример более менее соответствия один к одному, Значения для слова жаз на киргизском и весна на русском соответствуют друг другу. Однако это не всегда так. Может быть что не одно а несколько слов в языке-оригинале будут переводиться одни и тем же словом в языке перевода. Например, оба слова из русского языка вершина и небо могут быть переведены на чувашский как тӳпе. На самом деле, отношения между словами можно описать как многие к многим.

Для машинного перевода не составляет проблемы сказать, что вершина, небо и крыша - все будут переводиться как тӳпе. Но что saison может быть переведено также как temporada и что тӳпе имеет три (или больше) вариантов перевода на русский - это проблема.

Использование знания о части речи для снятия омонимии при переводе может частично, но не полностью решить проблему. Даже после того как снята омонимия с части речи, одно слово может иметь несколько вариантов перевод, как в примере с тӳпе. Итак, как решить проблему с один ко многим. Самый очевидный способ это выбрать наиболее часто встречающиеся, или общий перевод — в данном случае xxx.

В данное время Apertium имеет экспериментальный модуль для решения проблемы лексического выбора, то есть выбора наиболее подходящего перевода лексической формы языка-источника, предлагая контекст, использования мультислов тоже может быть частичным решением, например в случаях, когда существуют часто встречающиеся словосочетания, которые отличаются от общего перевода (например, с испанского на французский) that is choosing the most appropriate translation of a source language lexical form given its context, but the use of multiwords can also offer a partial solution, for example in the cases where there are frequent collocations which are exceptions to the general translation (for example, Spanish to French: estación del añosaison de l'année).

Диалектные формы

Часто бывает желательно перевести диалектные формы одного языка на нормативный стиль другого языка. Например, из русского языка слово мясо "meat" может быть переведено на чувашский язык как аш, какай, или аш-какай. Первые два варианты перевода считаются более диалектными и в основном употребляются в разговорном языке. Третий вариант более нормативный и более подходит для письменного варианта.

Грамматическая дивергенция

Еще одна проблема лексической передачи - грамматическое различие между двумя языками

  • Слова могут при переводе менять род и число (например, русское слово брюки — множественного числа переводятся на башкирский салбар — единственного числа)
  • Слова в языке-источнике могут иметь омонимию в числе (французское слово temps на испанское tiempo или tiempos) или роде (испанское слово estudiante — может быть мужского или женского рода во французским étudiant, мужской род, étudiante, женский род).
  • Другие характеристики, которые могут быть полезными при лексической передаче между двумя языками, это является ли переводное существительное абстрактif the target noun is mass or count — for example to decide if an article should be inserted when translating from a language without articles to a language with articles.
  • Also, for languages that have both adjectives which inflect for comparison, and adjectives which don't — it is useful to specify this in the bilingual dictionary.

All of these need to be taken care of in the transfer lexicon (bilingual dictionary).

Practice

For this practical, the examples will be from the Tatar--Bashkir language pair, so navigate to the directory apertium-tt-ba. The bilingual dictionary (or transfer lexicon) is in the file apertium-tt-ba.tt-ba.dix. Open it.

One to one

You may remember that we added the word чалбар to the Tatar dictionary in the first session, we'll keep with this example for the simple one-to-one bilingual dictionary entries.

So, for example, search for the entry >песи<,

    <e><p><l>песи<s n="n"/></l><r>бесәй<s n="n"/></r></p></e>

Copy the entry and change the lexical forms on the source and target side, so you have something that looks like:

    <e><p><l>песи<s n="n"/></l><r>бесәй<s n="n"/></r></p></e>

    <e><p><l>чалбар<s n="n"/></l><r>салбар<s n="n"/></r></p></e>

Save the dictionary and exit out of the text editor, and we can compile the dictionary with the following command:

$ lt-comp lr apertium-tt-ba.tt-ba.dix tt-ba.autobil.bin

We can test it as follows:

$ echo "чалбар" | hfst-proc tt-ba.automorf.hfst  | apertium-tagger -g tt-ba.prob  |\
  apertium-pretransfer | lt-proc -b tt-ba.autobil.bin 
^чалбар<n><nom>/салбар<n><nom>$

This command shows you the input lexical form, and the output lexical form after having been passed through the bilingual dictionary.

Many to one

The next job is to perform a translation from many words, to one word. The word морон in Tatar can be transated as борын in Bashkir, but this word is not currently in the dictionaries. We first want to search for the word борын in the file apertium-tt-ba.tt-ba.dix, and we'll find the following entry:

    <e><p><l>борын<s n="n"/></l><r>танау<s n="n"/></r></p></e>

We can add an entry to translate моронборын, but in order to do this we need to also add a direction restriction, so that that this entry only applies when translating from Bashkir to Tatar. Restriction are added to the <e> element with the r attribute and come in two flavours, LR or left-to-right and RL or right-to-left. The file is called apertium-tt-ba.tt-ba.dix with Tatar on the left and Bashkir on the right. So, if we want to translate only from Bashkir to Tatar we need to add a right-to-left (RL) direction restriction. Copy the entry and paste it below, then change the lemma and add the restriction.

    <e><p><l>борын<s n="n"/></l><r>танау<s n="n"/></r></p></e>
    <e r="RL"><p><l>борын<s n="n"/></l><r>морон<s n="n"/></r></p></e>

For the importance of direction restrictions, see Session 7. Now compile the dictionary and test the new entry:

$ lt-comp rl apertium-tt-ba.tt-ba.dix ba-tt.autobil.bin 
main@standard 1228 1995

$ lt-comp lr apertium-tt-ba.tt-ba.dix tt-ba.autobil.bin 
main@standard 1226 1990

$ echo "борын" | hfst-proc tt-ba.automorf.hfst  | apertium-tagger -g tt-ba.prob  |\
    apertium-pretransfer | lt-proc -b tt-ba.autobil.bin 
^борын<n><nom>/танау<n><nom>$

$ echo "танау" | hfst-proc ba-tt.automorf.hfst | apertium-tagger -g ba-tt.prob  |\
   apertium-pretransfer | lt-proc -b ba-tt.autobil.bin 
^танау<n><nom>/борын<n><nom>$

$ echo "морон" | hfst-proc ba-tt.automorf.hfst | apertium-tagger -g ba-tt.prob  |\
   apertium-pretransfer | lt-proc -b ba-tt.autobil.bin 
^морон<n><nom>/борын<n><nom>$

We use the direction restrictions when we never want to be able to translate a word in that direction, e.g. in the case of dialect or substandard forms. But sometimes it might be desirable to have two possible translations.

One to many

Finnish North Sámi
pitää doallat
pitää berret
pitää liikot
pitää coakcut
pitää galgat

For this section of the practical, you need to be in the apertium-sme-fin directory. The bilingual dictionary is apertium-sme-fin.sme-fin.dix

In this subsection we will add some entries for lexical forms with more than one translation, and write lexical selection rules to select the non-default translations.

If we take the example of pitää in Finnish, we find that it can also be translated with several words in North Sámi, so if we want to add some non-default translations of it, we can do it as follows:

  <e c="hold (acc)"><p><l>doallat<s n="V"/><s n="TV"/></l><r>pitää<s n="V"/></r></p><par n="V_V"/></e>
  <e c="ought to"><p><l>berret<s n="V"/><s n="IV"/></l><r>pitää<s n="V"/></r></p><par n="V_V"/></e>
  <e c="like (ela)"><p><l>liikot<s n="V"/><s n="IV"/></l><r>pitää<s n="V"/></r></p><par n="V_V"/></e>
  <e c="get a foothold"><p><l>coakcut<s n="V"/><s n="IV"/></l><r>pitää<s n="V"/></r></p><par n="V_V"/></e>

If we also want to add a translation from galgatpitää, then we need to add another entry, this time marking it with LR for translating only from North Sámi to Finnish.

  <e r="LR"><p><l>galgat<s n="V"/><s n="IV"/></l><r>pitää<s n="V"/></r></p><par n="V_V"/></e>--><!-- skulle, should -->

Compile the dictionary in the usual way:


$ lt-comp rl apertium-sme-fin.sme-fin.dix fin-sme.autobil.bin 
main@standard 15454 19523

And try out the new entries as follows:

$ echo "Minä pidän kirjan." | hfst-proc fin-sme.automorf.hfst  | cg-proc fin-sme.rlx.bin  | apertium-tagger -g fin-sme.prob  | lt-proc -b fin-sme.autobil.bin 
^Mikä<Pron><Interr><Sg><Ess>/Mii<Pron><Interr><Sg><Ess>$ 
^pitää<V><Act><Ind><Prs><Sg1><@+FMAINV>/berret<V><IV><Ind><Prs><Sg1><@+FMAINV>/liikot<V><IV><Ind><Prs><Sg1><@+FMAINV>/doallat<V><TV><Ind><Prs><Sg1><@+FMAINV>/coakcut<V><IV><Ind><Prs><Sg1><@+FMAINV>$ 
^kirja<N><Sg><Gen><@←OBJ>/girji<N><Sg><Gen><@←OBJ>$^.<Punct><CLB>/.<CLB>$

In the case of ambiguity in the lexical transfer, the transfer component will pick the first translation to continue with, if the first translation is not the desired translation, a lexical selection rule can be made which chooses a different one:

Make a file apertium-sme-fin.fin-sme.lrx, and paste the following text

<rules>
  <rule> 
    <match lemma="pitää" tags="V.*">
      <select lemma="doallat" tags="V.TV.*"/>
    </match>
  </rule>
</rules>

You can compile this rule using apertium-lrx-comp:

$ apertium-lrx-comp apertium-sme-fin.fin-sme.lrx fin-sme.lrx.bin
1
Written 1 rules, 2 patterns.

And test it as follows:

$ echo "Minä pidän kirjan." | hfst-proc fin-sme.automorf.hfst  | cg-proc fin-sme.rlx.bin  | apertium-tagger -g fin-sme.prob  | lt-proc -b fin-sme.autobil.bin | apertium-lrx-proc fin-sme.lrx.bin 
^Mikä<Pron><Interr><Sg><Ess>/Mii<Pron><Interr><Sg><Ess>$ 
^pitää<V><Act><Ind><Prs><Sg1><@+FMAINV>/doallat<V><TV><Ind><Prs><Sg1><@+FMAINV>$ 
^kirja<N><Sg><Gen><@←OBJ>/girji<N><Sg><Gen><@←OBJ>$^.<Punct><CLB>/.<CLB>$

As you can see the default translation doallat has been chosen. But what if we want to choose a non-default translation in certain contexts ? With an elative following as opposed to an accusative/genitive, a better translation is liikot, so let's add a rule for that:

  <rule>
    <match lemma="pitää" tags="V.*">
      <select lemma="liikot" tags="V.*"/>
    </match>
    <match tags="*.Ela"/>
  </rule>

You can compile it again, and try this rule with a sentence like Minä pidän sinusta. "I like you" .

Lexical selection

There is a separate handout on using lexical selection rules.

See also

Further reading