liveBook · Manning

Machine translation

As explained in Transfer Learning for Natural Language Processing

Machine translation is the automatic translation of text or speech from one natural language to another.

Machine translation converts sentences or documents from one language into another. Pretrained encoder-decoder transformers provide a practical starting point, including for some low-resource languages. section 1.1 section 7.1.4

To translate English into Twi, load a matching pretrained model and tokenizer. The model uses the Marian encoder-decoder architecture. Other available language pairs can be selected by changing the language codes in the model identifier. section 7.1.4

from transformers import MarianMTModel, MarianTokenizer

model = MarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-en-tw")
tokenizer = MarianTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-tw")

Load the English-to-Twi Marian model and its tokenizer. section 7.1.4

text = "My name is Paul"                                      #1
inputs = tokenizer.encode(text, return_tensors="pt")          #2
outputs = model.generate(inputs)                              #3
decoded_output = [tokenizer.convert_ids_to_tokens(int(outputs[0][i])) for i in range(len(outputs[0]))]                               #4
print("Translation:")                                         #5
print(decoded_output)

Encode the English sentence, generate an output, and convert its IDs to tokens for inspection. section 7.1.4

An English-to-Twi introduction

For “My name is Paul,” the model produces tokens including “Me,” “din,” “de,” and “Paul.” The displayed output also contains a special <pad> token and markers before words, so it is not yet a clean sentence. section 7.1.4

Training data matters as well as model availability. The Twi model was trained on JW300, a parallel corpus of religious translations. That data is heavily biased, but the model can serve as an initial baseline for further transfer learning and refinement. Refinement on better data is not demonstrated because suitable datasets are difficult to obtain. section 7.1.4

How Transfer Learning for Natural Language Processing covers it

How deep it goes
Walks through loading a model, generating and inspecting tokens, while leaving refinement on better data for further work.
Examples
Translates “My name is Paul” from English to Twi and inspects the generated tokens.
What you can do after
Apply it via the transformers library to generate a baseline translation with a pretrained Marian model.
How it connects
Connects machine translation to encoder-decoder transformers, tokenization, parallel corpora, and transfer learning.

Also explained in

Compare how 10 books explain machine translation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Transfer Learning for Natural Language Processing. The section links point to the parts of the book it draws on.