LoginSignup
5
2

More than 3 years have passed since last update.

Pythonでgoogle翻訳を用いた再翻訳によるテキストデータの水増し

Last updated at Posted at 2020-09-03

始めに

精神的に疲れていて、手軽に承認欲求を得たかったので、ここ最近参加していたNLPコンペのSIGNATE Student Cup 2020で使った、google翻訳を使ったPythonでのテキストデータ水増しスクリプトをお手軽に紹介する。
なお、既に似たような記事はたくさんあるので、全く新しさはない。

使用データセット

手軽なのがなかなか見つからなかったが、kaggleのデータセットのこれを使うことにした。Wikipedia Movie Plots

スクリプト

とりあえず英語の文を日本語に翻訳して、また英語に翻訳するスクリプトの紹介を行う。

from googletrans import Translator

def retranslator(text, lang):
    '''英語から他言語に翻訳したあと再度英語に翻訳し直してデータの水増しを狙う
    '''
    translator = Translator()
    translated = translator.translate(text, src='en', dest=lang).text
    retranslated = translator.translate(translated, src=lang, dest='en').text
    return translated, retranslated

こんな感じ。

本当に簡単に説明すると、textが翻訳したいstring、srcが元言語の言語コード、destが翻訳先の言語コードとなる。

google翻訳の言語コードは以下のURLにある言語サポートを参考に好きなのを選んで欲しい。

ちなみに、割とメジャーな言語の方が翻訳の精度がいいと予想されるので、データの水増し目的で使うときは、それなりにメジャーな言語を選んだ方が無難だと思う。
実際にコンペでもフランス語やドイツ語、スペイン語、日本語、中国語なんかを選んで再翻訳して水増しすることが多そうである。

実際に使ってみる

実行コード

import pandas as pd
from googletrans import Translator

data = pd.read_csv('./wiki_movie_plots_deduped.csv')

def retranslator(text, lang):
    '''英語から他言語に翻訳したあと再度英語に翻訳し直してデータの水増しを狙う
    '''
    translator = Translator()
    translated = translator.translate(text, src='en', dest=lang).text
    retranslated = translator.translate(translated, src=lang, dest='en').text
    return translated, retranslated

for i in range(5):
    row = data.iloc[i]

    translated, retranslated = retranslator(row['Plot'], 'ja')

    result = {
        'Original': row['Plot'],
        'translated': translated,
        'retranslated': retranslated
    }
    for key, val in result.items():
        print(key)
        print(val)
        print('')

出力

Original
A bartender is working at a saloon, serving drinks to customers. After he fills a stereotypically Irish man's bucket with beer, Carrie Nation and her followers burst inside. They assault the Irish man, pulling his hat over his eyes and then dumping the beer over his head. The group then begin wrecking the bar, smashing the fixtures, mirrors, and breaking the cash register. The bartender then sprays seltzer water in Nation's face before a group of policemen appear and order everybody to leave.[1]

translated
サロンでバーテンダーが働いており、顧客に飲み物を提供しています。彼が典型的なアイルランド人のバケツをビールで満たした後、キャリー・ネイションと彼女の追随者は中に飛び込みました。彼らはアイルランド人を襲い、彼の帽子を彼の目の上に引っ張り、それから彼の頭の上にビールを捨てた。その後、グループはバーを破壊し、備品、鏡を壊し、レジを壊し始めます。その後、バーテンダーはセルツァー水をネイションの顔にスプレーしてから、警官のグループが現れ、全員に立ち去るように命じます。[1]

retranslated
A bartender works at the salon and serves drinks to customers. Carry Nation and her followers plunge into him after he filled a typical Irish bucket with beer. They attacked the Irish, pulled his hat over his eyes, and then threw the beer over his head. After that, the group destroys the bar, destroys equipment, mirrors, and begins to destroy the cash register. The bartender then sprays Seltzer water on Nation's face, then a group of policemen appears and orders everyone to leave. [1]


Original
The moon, painted with a smiling face hangs over a park at night. A young couple walking past a fence learn on a railing and look up. The moon smiles. They embrace, and the moon's smile gets bigger. They then sit down on a bench by a tree. The moon's view is blocked, causing him to frown. In the last scene, the man fans the woman with his hat because the moon has left the sky and is perched over her shoulder to see everything better.

translated
笑顔で描かれた月が夜公園に垂れ下がる。柵を越えて歩く若いカップルは、手すりについて学び、見上げる。月は微笑む。彼らは抱擁し、月の笑顔が大きくなります。それから彼らは木のそばのベンチに座った。月の視界が遮られ、彼は眉をひそめた。最後のシーンでは、月が空を離れ、肩越しに何もかもよく見えるので、男性は帽子をかぶって女性を扇動します。

retranslated
The moon drawn with a smile hangs in the park at night. A young couple walking over the fence learns about the handrail and looks up. The moon smiles. They hug and make the moon smile bigger. Then they sat on a bench by the tree. The moon's view was blocked and he frowned. In the last scene, the man leaves the sky and sees everything over his shoulder, so men wear hats to incite women.


Original
The film, just over a minute long, is composed of two shots. In the first, a girl sits at the base of an altar or tomb, her face hidden from the camera. At the center of the altar, a viewing portal displays the portraits of three U.S. Presidents—Abraham Lincoln, James A. Garfield, and William McKinley—each victims of assassination.
In the second shot, which runs just over eight seconds long, an assassin kneels feet of Lady Justice.

translated
この映画は1分強で、2つのショットから構成されています。最初は、女の子が祭壇や墓のふもとに座っており、顔はカメラから隠されています。祭壇の中央にある観覧ポータルには、暗殺の犠牲者である3人の米国大統領、エイブラハムリンカーン、ジェームズA.ガーフィールド、ウィリアムマッキンリーの肖像画が表示されています。
セカンドショットは8秒強で、正義の女神の足をひざまずきます。

retranslated
This movie is a little over a minute and consists of two shots. Initially, the girl sits at the base of the altar or grave, with her face hidden from the camera. A viewing portal in the center of the altar shows portraits of three US presidents, Abraham Lincoln, James A. Garfield and William McKinley, who are victims of assassination.
The second shot is just over 8 seconds and kneels on the feet of the goddess of justice.


Original
Lasting just 61 seconds and consisting of two shots, the first shot is set in a wood during winter. The actor representing then vice-president Theodore Roosevelt enthusiastically hurries down a hillside towards a tree in the foreground. He falls once, but rights himself and cocks his rifle. Two other men, bearing signs reading "His Photographer" and "His Press Agent" respectively, follow him into the shot; the photographer sets up his camera. "Teddy" aims his rifle upward at the tree and fells what appears to be a common house cat, which he then proceeds to stab. "Teddy" holds his prize aloft, and the press agent takes notes. The second shot is taken in a slightly different part of the wood, on a path. "Teddy" rides the path on his horse towards the camera and out to the left of the shot, followed closely by the press agent and photographer, still dutifully holding their signs.

translated
わずか61秒の2ショットで構成され、冬の間、最初のショットは森の中で撮影されます。当時、副大統領を務めたセオドアルーズベルトを代表する俳優は、手前の木に向かって丘の中腹を熱狂的に急いでいます。彼は一度倒れるが、自分自身に権利を与え、彼のライフルを撃ち込む。他の2人の男性が、それぞれ「彼の写真家」と「彼の記者代理人」と書かれた標識を付けて、彼を追って撃ちます。カメラマンがカメラをセットアップします。 「テディ」はライフルを木に向け、普通の家猫のように見えるものを倒し、突き刺します。 「テディ」は彼の賞を高く掲げており、記者はメモを取る。セカンドショットは、森の少し異なる部分の小道で撮影されます。 「テディ」は彼の馬の道をカメラに向かってそしてショットの左側に出て行き、プレスエージェントとカメラマンが密接に続いて、まだサインを忠実に保持しています。

retranslated
Consisting of two shots of only 61 seconds, during the winter the first shot is taken in the woods. At the time, the actor, who represented Vice President Theodore Roosevelt, enthusiastically rushed down the hill toward the trees in front. He falls once, but empowers himself and shoots his rifle. Two other men chase him, marking them with "his photographer" and "his reporter agent" respectively. The cameraman sets up the camera. The "teddy" points its rifle at a tree, defeats and sticks what looks like a normal domestic cat. "Teddy" has raised his award high and reporters take notes. The second shot is taken on a path in a slightly different part of the forest. "Teddy" heads his horse towards the camera and out to the left of the shot, closely followed by the press agent and the photographer, still faithfully holding the autograph.


Original
The earliest known adaptation of the classic fairytale, this films shows Jack trading his cow for the beans, his mother forcing him to drop them in the front yard, and beig forced upstairs. As he sleeps, Jack is visited by a fairy who shows him glimpses of what will await him when he ascends the bean stalk. In this version, Jack is the son of a deposed king. When Jack wakes up, he finds the beanstalk has grown and he climbs to the top where he enters the giant's home. The giant finds Jack, who narrowly escapes. The giant chases Jack down the bean stalk, but Jack is able to cut it down before the giant can get to safety. He falls and is killed as Jack celebrates. The fairy then reveals that Jack may return home as a prince.

translated
古典的なおとぎ話の最も初期の知られている適応、この映画は、ジャックが彼の牛を豆と交換すること、彼の母親が彼に前庭にそれらを落とすことを強制し、そして2階に強制されたビーグを示しています。彼が眠っているとき、ジャックは妖精が訪れます。妖精は、彼が豆の茎を登るときに何が待ち受けているかを垣間見せます。このバージョンでは、ジャックは退位した王の息子です。ジャックが目を覚ましたとき、彼は豆の木が成長しているのを発見し、彼は巨人の家に入る頂上に登ります。巨人は、わずかに脱出するジャックを見つけます。巨人はジャックを豆の茎を追いかけますが、巨人が安全になる前にジャックはそれを切り落とすことができます。ジャックが祝うと、彼は転んで殺されます。妖精はジャックが王子として家に帰ることを明らかにします。

retranslated
The earliest known adaptation of the classic fairy tale, this film shows Jack exchanging his cows for beans, his mother forcing him to drop them in the front yard, and upstairs. Shows forced beag. When he is asleep, Jack is visited by fairies. The fairy gives a glimpse of what he is waiting for when he climbs the bean stalk. In this version, Jack is the son of the deposed King. When Jack wakes up, he finds a bean tree growing and he climbs to the top of the giant's house. The giant finds Jack who escapes slightly. The giant chases Jack for the bean stalk, but Jack can chop it off before the giant is safe. When Jack celebrates, he falls and is killed. The fairy reveals that Jack will return home as a prince.

ちょっとあんまり出力結果が見易くはないんだけど、こういう細かいところに気を使う精神力が今あまりないので勘弁して欲しい。

翻訳テキストから、どの映画のプロットか分かっただろうか?気になる人はkaggleのデータセットを除いて各自titleを見てほしい。

日本語の翻訳はん?となる箇所がそこそこある気もするが、再翻訳したものはそ腕もない気がする。ネイティブではないのでなんともいえないけれど。

これで君も、同じ文意の文章をちょっと違う表現で言い表すことで、データの水増しを行うというNLPコンペでよく使われる手法を使えるようになった。
翻訳の質に依存してしまうのが難点ではあるけれども、これは割と手軽にできてそこそこ効く手法だと思うので試してみて欲しい。

おまけの近況

ここ最近(と言ってももう一週間くらい前になるが)SIGNATE Student Cup 2020に参加していた。そこで割と精神力を削られた。参加記はこちら(宣伝を忘れないスタイル)SIGNATE Student Cup 2020【予測部門】参加記(pop-ketle版)

ということで僕が現在Part分けしながら書いてるPythonとFlaskで類似画像を検索できるアプリを作ってみようPart2の更新はもうしばらく待って欲しい。
実は、次はどんな風にアプリを発展させていこうかとか、Flaskの解説をきちんと調べて書くべきか?とか結構次の取り組みに悩んでいたり、他にもやらなきゃいけないことがそこそこあったりで、あんまり記事を書くまとまった時間が取れないというのが現状である。(手軽に頑張った感を得たかったのでこの記事だけ1時間割いて書いた。)では、しばらくさようならみなさん精神力は大事にしてください。

5
2
0

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
  3. You can use dark theme
What you can do with signing up
5
2