テキストのperplexityを求めるのに、
HuggingFaceを使って簡単に求めることができたので手順をメモしておきます。

やっていることは、以下のページの通りです。

Metric: perplexity | HuggingFace Spaces
https://huggingface.co/spaces/evaluate-metric/perplexity

Transformersのインストール

以下の手順に従ってTransformersをインストールします。

Installation | HuggingFace Transformers
https://huggingface.co/docs/transformers/installation

私の環境で実行したコマンドは以下の通り(pyenvを利用)。

$ mkdir huggingface-study && cd $_
$ pyenv install 3.12.11
$ pyenv local 3.12.11
$ python -m venv .venv
$ . .venv/bin/activate
$ pip install --upgrade pip
$ pip install 'transformers[torch]'

以下のコマンドを実行して、インストールできているかを確認します。

$ python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('hugging face is the best'))"
[{'label': 'POSITIVE', 'score': 0.999839186668396}]

Evaluateのインストール

以下のコマンドを実行して、Evaluateをインストールします。

$ pip install evaluate

perplexityを求める

perplexityを求めるコードを用意します。

main.py

from evaluate import load

perplexity = load("perplexity", module_type="metric")
model_name = "gpt2"
predictions = [
    "おはようございます",
    "およはうございます",
    "おやすみなさい",
    "やおすみなさい",
]

results = perplexity.compute(predictions=predictions, model_id=model_name)
print(results)

コードを実行して、perplexityを求めます。

$ python main.py
{'perplexities': [14.583911895751953, 19.69840431213379, 34.38338851928711, 45.93952178955078], 'mean_perplexity': np.float64(28.651306629180908)}

以下のように、誤ったテキストの方がperplexityが高くなっていることを確認できます。

  • おはようございます(正): 14.583911895751953
  • およはうございます(誤): 19.69840431213379
  • おやすみなさい(正): 34.38338851928711
  • やおすみなさい(誤): 45.93952178955078

perplexity以外のmetricsを求めたい場合は、以下のページが参考になります。

Evaluate Metric | HuggingFace
https://huggingface.co/evaluate-metric

以上。