Transformers(5) - テキスト生成

今回は、テキスト生成を行います。

(Transformersのインストールは完了している想定となります。)

テキスト生成

テキスト生成は、入力されたテキストに続くもっともらしいテキストを自動生成する処理です。

ソースとしては、まずタスク名に‘text-generation’を指定したパイプラインを作成します。

パイプラインには次の3つを引数として渡し、テキスト生成処理を行います。

  • 第1引数
    入力するテキスト
  • max_length
    生成するテキストの最大語数
  • min_length
    生成するテキストの最小語数

[Google Colaboratory]

1
2
3
4
5
6
7
8
9
10
from transformers import pipeline

# テキスト生成のパイプライン
text_generator = pipeline('text-generation')

# 入力テキスト
text = 'Once upon a time there was an old man and an old woman.'

# テキスト生成
print(text_generator(text, max_length=100, min_length=50))

実行結果は下記の通りです。

[実行結果]

1
2
3
4
Some weights of GPT2Model were not initialized from the model checkpoint at gpt2 and are newly initialized: ['h.0.attn.masked_bias', 'h.1.attn.masked_bias', 'h.2.attn.masked_bias', 'h.3.attn.masked_bias', 'h.4.attn.masked_bias', 'h.5.attn.masked_bias', 'h.6.attn.masked_bias', 'h.7.attn.masked_bias', 'h.8.attn.masked_bias', 'h.9.attn.masked_bias', 'h.10.attn.masked_bias', 'h.11.attn.masked_bias']
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.
[{'generated_text': 'Once upon a time there was an old man and an old woman. One was a very good maid on whom the women worked while the young men worked in the yard.\n\nThis time in the middle of the night, the young maid ran off the edge of the street, followed by several other girls, and as they approached the old maid came the other to speak to this man. He gave her a call and said he had come for someone. The young maid took the call, and found'}]

生成されたテキストを訳すとだいたい次のような感じです。

Once upon a time there was an old man and an old woman.
昔々、おじいさんとおばあさんがいました。

One was a very good maid on whom the women worked while the young men worked in the yard.
一人は、若い男性が庭で働いている間、女性が働いていたとても良いメイドでした。

This time in the middle of the night, the young maid ran off the edge of the street, followed by several other girls, and as they approached the old maid came the other to speak to this man.
今回は真夜中に、若いメイドが通りの端から逃げ出し、他の何人かの女の子が続き、彼らが近づくと、古いメイドがこの男と話すためにもう一人来ました。

He gave her a call and said he had come for someone. The young maid took the call, and found
彼は彼女に電話をかけ、誰かのために来たと言いました。若いメイドが電話に出て、見つけました。

テキストが生成されるにはされたのですが、なんだか謎が謎をよぶ展開になってます。。。😅

次回は、言語モデルを試してみます。