!date
!python --version
Tue Apr 22 07:06:03 AM UTC 2025
Python 3.11.12

変更履歴

  • 2025年4月22日: 日本語版BERTのためfugashiをインストール。

36. transformers.pipelineを用いた推定例#

参考

基本的には pipeline(task="タスク名") としてタスクを指定するだけでそれに応じたモデルをダウンロードして利用することができる。しかしモデルは必ずしも日本語には対応していないため、場合によっては想定以上に推定結果が悪くなることもある。このノートブックでは「感情分析(極性推定)」を例にデフォルトのモデルを利用した場合の失敗例を示しつつ、それ以降は「適切に動きそうなモデルを探し、指定して利用する」形での実行例を示す。

from transformers import pipeline
import pandas as pd

36.1. 感情分析(極性推定)#

36.1.1. 失敗例#

タスクを指定し、モデルを指定しない場合にはデフォルトで想定されているモデルが自動でダウンロードされる。 この例では “distilbert/distilbert-base-uncased-finetuned-sst-2-english” が自動で選ばれている。 モデル名から分かるとおり英語で学習したモデルのため、日本語だとうまく推定できない。

# これはモデルマッチしていないため、うまく推定できない例
pipe = pipeline(task="sentiment-analysis")
text = "この映画はとても素晴らしい"
outputs = pipe(text)
outputs
No model was supplied, defaulted to distilbert/distilbert-base-uncased-finetuned-sst-2-english and revision 714eb0f (https://huggingface.co/distilbert/distilbert-base-uncased-finetuned-sst-2-english).
Using a pipeline without specifying a model name and revision in production is not recommended.
/usr/local/lib/python3.11/dist-packages/huggingface_hub/utils/_auth.py:94: UserWarning: 
The secret `HF_TOKEN` does not exist in your Colab secrets.
To authenticate with the Hugging Face Hub, create a token in your settings tab (https://huggingface.co/settings/tokens), set it as secret in your Google Colab and restart your session.
You will be able to reuse this secret in all of your notebooks.
Please note that authentication is recommended but still optional to access public models or datasets.
  warnings.warn(
Xet Storage is enabled for this repo, but the 'hf_xet' package is not installed. Falling back to regular HTTP download. For better performance, install the package with: `pip install huggingface_hub[hf_xet]` or `pip install hf_xet`
WARNING:huggingface_hub.file_download:Xet Storage is enabled for this repo, but the 'hf_xet' package is not installed. Falling back to regular HTTP download. For better performance, install the package with: `pip install huggingface_hub[hf_xet]` or `pip install hf_xet`
Device set to use cpu
[{'label': 'NEGATIVE', 'score': 0.8893206119537354}]

36.1.2. モデルを指定した例#

https://huggingface.co/models からタグ「Text classification」を選び、”sentiment jp” ぐらいのキーワードで絞り込むと5件がヒットする。この中からmr4/bert-base-jp-sentiment-analysisを選んだ。

# 追加インストール
!pip install 'fugashi[unidic-lite]'
Collecting fugashi[unidic-lite]
  Downloading fugashi-1.4.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (6.9 kB)
Collecting unidic-lite (from fugashi[unidic-lite])
  Downloading unidic-lite-1.0.8.tar.gz (47.4 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 47.4/47.4 MB 17.1 MB/s eta 0:00:00
?25h  Preparing metadata (setup.py) ... ?25l?25hdone
Downloading fugashi-1.4.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (698 kB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 698.0/698.0 kB 33.7 MB/s eta 0:00:00
?25hBuilding wheels for collected packages: unidic-lite
  Building wheel for unidic-lite (setup.py) ... ?25l?25hdone
  Created wheel for unidic-lite: filename=unidic_lite-1.0.8-py3-none-any.whl size=47658817 sha256=ad709380a9b25ce135d9a1695170fcb83ff8024326fa2cdf83748d3206139285
  Stored in directory: /root/.cache/pip/wheels/b7/fd/e9/ea4459b868e6d2902e8d80e82dbacb6203e05b3b3a58c64966
Successfully built unidic-lite
Installing collected packages: unidic-lite, fugashi
Successfully installed fugashi-1.4.0 unidic-lite-1.0.8
model_name = "mr4/bert-base-jp-sentiment-analysis"
pipe = pipeline(task="sentiment-analysis", model=model_name)
text = "この映画はとても素晴らしい"
outputs = pipe(text)
outputs
Device set to use cpu
[{'label': 'positive', 'score': 0.9999532699584961}]
# 別例
text = "正直わかりずらい。むだに間があるし。"
outputs = pipe(text)
outputs
[{'label': 'negative', 'score': 0.999911904335022}]

36.2. 全ラベルに対するスコア#

オプションで “return_all_scores=True” を付けることで、全てのラベルに対するスコアを取得できる。

# 別例
text = "正直わかりずらい。むだに間があるし。"
outputs = pipe(text, return_all_scores=True)
outputs
/usr/local/lib/python3.11/dist-packages/transformers/pipelines/text_classification.py:106: UserWarning: `return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.
  warnings.warn(
[[{'label': 'negative', 'score': 0.999911904335022},
  {'label': 'positive', 'score': 8.80625011632219e-05}]]

36.3. テキスト生成#

タグ「Text Generation」を選び、”jp” で絞り込み、「Most downloads」でソート。その中では小さめのモデル(1.3Bならメモリ1GBぐらいあれば動作する)であるllm-jp/llm-jp-1.3b-v1.0を選択。

model_name = "llm-jp/llm-jp-1.3b-v1.0"
pipe = pipeline(task="text-generation", model=model_name)
text = "ようやく晴れてきましたね。どこかに"
outputs = pipe(text)
outputs
Device set to use cpu
[{'generated_text': 'ようやく晴れてきましたね。どこかに 【楽天市場】【送料無料】 【1000円ポッキリ】'}]

36.4. 質問応答#

36.4.1. 失敗例(BERT系)#

タグ「Question Answering」を選び、”jp”で絞り込んだ中から1番目のモデル[jpabbuehl/distilbert-base-uncased-finetuned-squad]を選びました。BERT系は比較的小さなモデルですが、その分あまり精度は良くないかもしれません。(失敗している)

model_name = "jpabbuehl/distilbert-base-uncased-finetuned-squad"
pipe = pipeline(task="question-answering", model=model_name)
question = "先生はどこに住んでいますか?"
context = "病気の都合で車を運転することができなくなりました。徒歩で通勤できると楽になるため、大学の近くに住んでいます。"
outputs = pipe(question=question, context=context)
outputs
Device set to use cpu
{'score': 5.876633076695725e-05,
 'start': 0,
 'end': 24,
 'answer': '病気の都合で車を運転することができなくなりました'}

36.4.2. 少し大きめなtext-generationモデルで回答させてみる#

=> モデルが大きく、同一ノートブックではリソース的に厳しいため別ノートに移行。