LoginSignup
5

More than 1 year has passed since last update.

posted at

updated at

【自然言語処理/NLP】Pythonで簡単に機械翻訳による逆翻訳(back translation)をする方法

NLPのコンペティションなどで、データの水増し(Data Augmentation)のために、逆翻訳をPythonでしたい時ありませんか?

例えば、Kaggleの「Toxic Comment Classification Challenge」では 1st place solution にこの手法が用いられていたりします。
https://www.kaggle.com/c/jigsaw-toxic-comment-classification-challenge/discussion/52557

この記事では、Pythonで機械翻訳を用いて、簡単に逆翻訳をする方法について説明します。

機械翻訳による逆翻訳
機械翻訳による逆翻訳の例
引用: https://amitness.com/2020/05/data-augmentation-for-nlp/

概要

googletrans を使えば、APIキーなど不要で、簡単に逆翻訳ができます。

googletrans のインストール

環境は Python3 を想定しています。

$pip install googletrans

逆翻訳のプログラム

from googletrans import Translator

def BackTranslation(text, original_lang, via_lang):
    translator = Translator()
    return translator.translate(translator.translate(text, dest=via_lang).text, dest=original_lang).text

引数の text には原文、original_lang には原文の言語、via_lang には経由したい言語を指定します。

lang に指定できる言語については、以下のgoogletransのドキュメントを参考にしてください。
https://py-googletrans.readthedocs.io/en/latest/

使用例

「The destiny of man is in his own soul.」
という英語の文章を日本語を経由して逆翻訳してみます。

text = "The destiny of man is in his own soul."
BackTranslation(text, "en", "ja")

返り値(逆翻訳の結果)は以下のようになります。

逆翻訳の結果
'The fate of man lies in his own soul.'

また、中継した言語(日本語)を出力させると、以下のようになります。

中継した言語
人間の運命は彼自身の魂にあります。

参考文献

A Visual Survey of Data Augmentation in NLP
https://amitness.com/2020/05/data-augmentation-for-nlp/

Googletrans: Free and Unlimited Google translate API for Python
https://py-googletrans.readthedocs.io/en/latest/

逆翻訳は機械翻訳の錬金術師か?
http://deeplearning.hatenablog.com/entry/back_translation

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
5