pianofisica

Mathematics & Physics, Maxima, a bit Python & Wolfram, and Arts

Pythonで学ぶ機械学習:Transformerを使ったテキスト生成

機械学習の具体的な問題にPythonを使って、機械学習Pythonも同時に学んでしまいましょう。今回はTransformerを使ったテキスト生成についてまとめました。Transformerは、ChatGPTやBERTの基盤となるモデルで、自然言語処理(Natural Languege Processing, NLP)において非常に重要です。その特徴は、自己注意機構(Self-Attention)によって文の重要な部分にフォーカスできること、並列計算が可能で従来のRNNよりも高速に学習できることです。

この記事では transformers ライブラリおよび Pytorch ライブラリを用います。適宜

pip install transformers torch

などによってダウンロード・インストールしてください。ただしPythonのバージョンによってはうまく実行されないこともあります。場合によっては uv などの仮想環境で対処する必要があります。




 

テキスト生成の実装

transformers ライブラリを使って、GPT-2 による文章生成を行ってみます。

from transformers import pipeline

# テキスト生成モデル(GPT-2)をロード
generator = pipeline("text-generation", model="gpt2")

# 文章生成
prompt = "The long and winding road that leads to your door"
generated_texts = generator(prompt, max_length=50, num_return_sequences=3)

# 結果表示
for i, text in enumerate(generated_texts):
    print(f"生成された文章 {i+1}:\n{text['generated_text']}\n")

 

  • 生成された文章 1:
    • The long and winding road that leads to your door is just another hurdle in making the journey a true adventure for all of you. Here's the video guide you'll need to navigate the dark tunnel that led into the castle...How do you
  • 生成された文章 2:
    • The long and winding road that leads to your door takes you to a great view of Lake Zurich. L.A. The best view of LA, from the back is the spectacular Hotel San Gabriel in the heart of downtown. It
  • 生成された文章 3:
    • The long and winding road that leads to your door is called "Equestria and the Kingdom", where you will take in the gorgeous castle scene from Huckleberry Finn who plays the titular king in an episode of "Frozen".


ポイント

  • pipeline("text-generation", model="gpt2")
    • GPT-2 を使って文章生成を行う
  • generator(prompt, max_length=50, num_return_sequences=3)
    • 最大50単語の文章を3つ生成する

 

 



 
 


キーワード機械学習Python、基礎

プライバシーポリシー