機械学習・ディープラーニング

PythonのTransformersライブラリでできること!pipelineの使い方について解説!

記事内に広告が含まれています。

はるか
Transformersをpythonで使いたい。

ふゅか
pipelineを使うと様々なタスクにTransformersを使用できるわ。

PythonのTransformersとは?

PythonのTransformersライブラリは、自然言語処理(NLP)のタスクを簡単に、効率的に処理するためのツールです。このライブラリは、Hugging Face社によって提供されており、様々な事前訓練済みモデルを活用することができます。主に「pipeline」という機能を用いることで、コードの記述を最小限に抑えつつ、強力なNLPタスクを実行することが可能です。今回は、その主な用途について解説します。

インストール方法

transfomersを次のコマンドでインストールしましょう。

pip install transformers[sentencepiece,torch]

pytorchをインストールしていない場合

pytorchをインストールしていない場合、pytorchをインストールしましょう。

pip install torch

感情分析

感情分析は、テキストがポジティブ(肯定的)な感情を含んでいるか、ネガティブ(否定的)な感情を含んでいるかを判断するプロセスです。Transformersライブラリのpipelineを使用することで、数行のコードでこれを実現できます。例えば、ユーザーのレビューやフィードバックから感情の傾向を分析することが可能です。

はるか
文章がネガティブかポジティブかの判定ができる。

感情分析のpythonコード

from transformers import pipeline

# 感情分析モデルのロード
classifier = pipeline("sentiment-analysis")

# 分析対象のテキスト
text = "I love using Transformers. It's so powerful and easy to use!"

# 感情分析の実行
result = classifier(text)
print(result)

文章生成

文章生成は、与えられたテキストに基づいて新しいテキストを自動生成するタスクです。この機能は、物語の自動作成、ユーザーからの質問に対する自動回答など、多岐にわたる応用が考えられます。Transformersライブラリの中でも、特にGPTシリーズのモデルがこの用途に適しています。

はるか
GPTはデコーダー。

文章生成のpythonコード

ふゅか
As a wizard, Iの次の文章を策せしてみましょう!
from transformers import pipeline, set_seed

# 生成モデルのロード
generator = pipeline("text-generation", model="gpt2")

# シード設定(オプション)
set_seed(42)

# プロンプトテキスト
prompt = "As a wizard, I"

# テキスト生成の実行
result = generator(prompt, max_length=50, num_return_sequences=1)
print(result[0]['generated_text'])

ふゅか
GPT2は無料で利用できます!

文章要約

文章要約は、長いテキストを短く要約することで、その内容のエッセンスを簡潔に伝えるタスクです。

文章要約のpythonコード

from transformers import pipeline

# 要約モデルのロード
summarizer = pipeline("summarization")

# 要約するテキスト
article = """
    The recent advancements in AI have led to significant improvements in various fields including 
    healthcare, finance, and transportation. These technologies are now 
    capable of analyzing large datasets quickly and accurately, enabling better decision-making and efficiency. 
    In healthcare, AI is used to predict patient outcomes, personalize treatment plans, and improve diagnostic accuracy. 
    Financial institutions leverage AI for fraud detection, risk management, and customer service optimization. 
    In transportation, AI-driven algorithms optimize route planning, reduce traffic congestion, and enhance safety features 
    in autonomous vehicles. As AI continues to evolve, 
    its integration into these sectors promises even more groundbreaking developments and solutions to complex challenges.
"""

# テキストの要約の実行
summary = summarizer(article, max_length=130, min_length=30, do_sample=False)
print(summary[0]['summary_text'])

質問応答

質問応答システムは、ユーザーからの具体的な質問に対して正確な回答を提供する機能です。このシステムは、FAQの自動化、カスタマーサポート、教育ツールとして有用です。

質問応答のpythonコード

from transformers import pipeline

# 質問応答モデルのロード
qa_pipeline = pipeline("question-answering")

# テキストコンテキストと質問
context = """
    Transformers can be used for various NLP tasks such as text generation, summarization, and question answering.
"""

question = "What can transformers be used for?"

# 質問応答の実行
answer = qa_pipeline(question=question, context=context)
print(f"Answer: {answer['answer']}")

ふゅか
transformersが何に使えるのかという質問に対して、「様々なNPLのタスク」という解答が得られました!

Transformersに関連する書籍

最後に、Transformersに関連する書籍についてまとめました!

機械学習エンジニアのためのTransformers ―最先端の自然言語処理ライブラリによるモデル開発
大規模言語モデル入門

-機械学習・ディープラーニング
-,