Skip to main content

bertopic-ja

日本語の文書から、どんなトピックが話されているかを探索するなら BERTopic です。埋め込み、UMAP、HDBSCAN、c-TF-IDF という今の探索的トピックモデルの手順を、日本語のトピック語が単語になる状態で始められます。

公式のトークナイザは空白で区切るため、分かち書きしない日本語では機能しません。トピック名が単語ではなく、文のかたまりになります。このパッケージはそこを Sudachi に置き換えた入口です。公式 BERTopic のサブプロジェクトではありません。手法と実装の本体は Maarten Grootendorst の BERTopic(論文: arXiv:2203.05794)です。

0.2.0

既定の pos は名詞・形容詞・動詞・形状詞です。

インストール

uv add bertopic-ja
pip install bertopic-ja

使い方

from bertopic_ja import BERTopic

topic_model = BERTopic()
topics, probs = topic_model.fit_transform(docs)
topic_model.get_topic_info()

何も指定しないときの埋め込みは、BERTopic の language="multilingual"(paraphrase-multilingual-MiniLM-L12-v2)です。トピック語は Sudachi(分割モード C)の名詞・形容詞・動詞・形状詞です。動詞と形容詞は正規化形で、活用を戻して出します。「使った」は「使う」、「高かった」は「高い」、「使いにくかった」は「使いにくい」です。可能動詞は Sudachi の正規化に合わせます。「書ける」は「書く」です。「丁寧」「簡単」「静か」のような形状詞も出します。品詞は pos で指定します。pos=["名詞"] とすると名詞だけになります。

仮名だけの1文字、記号だけの1文字、代名詞、数詞は出しません。漢字1文字は出します。「えー」「まあ」のようなフィラーはトピック語から外し、本文には残します。「あの本」の「あの」は消しません。protect に入れた語は、フィラーや仮名1文字でも残します。「見る」「こと」のような語は、初期値では残します。外すときは exclude か stopwords に、正規化形か表層か辞書形を書きます。表示は「為る」「有る」のような正規化形です。出ている表記は get_topic_info() で確認します。

トピックの粗さは min_topic_size です。UMAP と HDBSCAN は自分で組みません。学習済みモデルは save と BERTopic.load で戻せます。pickle と safetensors のどちらでも、exclude、protect、fillers、pos、stopwords は残ります。safetensors で読むときは、学習に使った埋め込みを embedding_model に渡します。

topic_model = BERTopic(min_topic_size=8)

出てきた語を調整する

トピック語から外すだけなら、埋め込みはやり直しません。

topic_model.exclude("天気", "気温")
topic_model.suggest()
topic_model.explain("このレシピって作ったことあります?")
topic_model.preview_exclude(["天気"])

クラスタの数や粗さを変えるときは、保存してある埋め込みで学習し直します。

topic_model.refit(min_topic_size=8)
topic_model.refit(nr_topics=15)

本文からフィラーを消すとクラスタが変わるので、初期値では消しません。消すときだけ fillers= を渡します。

topic_model = BERTopic(fillers=["えー", "あのー"])

品詞を変えるとき、最初から語を外すときは、次のように渡します。

# 名詞だけにする
topic_model = BERTopic(pos=["名詞"])
# 出てくる形を指定して外す。する の正規化形は 為る
topic_model = BERTopic(stopwords=["こと", "為る"])
topic_model.exclude("見る")

別の埋め込みモデルは embedding_model に渡します。長い文書と、接頭辞が要るモデルは次の節です。

長い文書での埋め込みモデルの選び方

発言や記事が長いときは、512 トークン以上入るモデルを embedding_model に渡します。何も指定しない paraphrase-multilingual-MiniLM-L12-v2 は、sentence-transformers の設定で 128 トークンまでです。それより長い文は、先頭だけが埋め込みに入ります。

国会会議録の政府側の答弁 682 件では、このトークナイザで 682 件中 603 件が 128 トークンを超えていました。min_topic_size=15、n_neighbors=15(文書数が 500 以上のときにこのパッケージが使う近傍数)で、UMAP の random_state を 10 通り変えると、トピック数は 2 から 15 まで揺れ、最大のトピックが全体の半分を超えたのが 10 回中 6 回でした。512 トークン以上入る intfloat/multilingual-e5-small、intfloat/multilingual-e5-base、intfloat/multilingual-e5-large、Alibaba-NLP/gte-multilingual-base、cl-nagoya/ruri-v3-130m、cl-nagoya/ruri-v3-310m では 10 回中 0 回でした。入力長が同じく 128 トークンの paraphrase-multilingual-mpnet-base-v2 は、パラメータ数が MiniLM の約 2.4 倍でも 10 回中 8 回潰れました。8192 トークンの BAAI/bge-m3 は 10 回中 1 回潰れました。

e5 のトークナイザでは、同じ 682 件のうち 512 トークンを超えたのは 15 件でした。第一候補は intfloat/multilingual-e5-base(最大 512 トークン)です。クラスタリングでは、各入力の先頭に query: (コロンのあとに空白)を付けます。日本語に特化するなら cl-nagoya/ruri-v3-130m(最大 8192 トークン)で、接頭辞は トピック: です。

名前の文字列を渡すと、本文をそのまま埋め込みます。

topic_model = BERTopic(embedding_model="intfloat/multilingual-e5-base")

接頭辞は、埋め込みの encode のときだけ付けます。トピック語を作る本文には付けません。default_prompt_name を指定した SentenceTransformer を embedding_model に渡すと、fit_transform がそのモデルの encode を呼び、接頭辞が付きます。

from sentence_transformers import SentenceTransformer

from bertopic_ja import BERTopic

encoder = SentenceTransformer(
    "intfloat/multilingual-e5-base",
    prompts={"query": "query: "},
    default_prompt_name="query",
)
topic_model = BERTopic(embedding_model=encoder)
topics, probs = topic_model.fit_transform(docs)
encoder = SentenceTransformer(
    "cl-nagoya/ruri-v3-130m",
    prompts={"topic": "トピック: "},
    default_prompt_name="topic",
)
topic_model = BERTopic(embedding_model=encoder)
topics, probs = topic_model.fit_transform(docs)

埋め込みを先に計算して渡すこともできます。embeddings を渡すと、fit_transform は文書の埋め込みを計算し直さず、その配列を使います。トピック語の類似度には embedding_model を使うので、同じ encoder を渡します。

embeddings = encoder.encode(docs)
topic_model = BERTopic(embedding_model=encoder)
topics, probs = topic_model.fit_transform(docs, embeddings=embeddings)

重みのファイルは、e5-base が約 1.1GB、ruri-v3-130m が約 530MB、既定の MiniLM が約 470MB です。CPU だけで政府側 682 件を埋めた計測では、MiniLM が 5.7 秒、e5-base が 48.6 秒、ruri-v3-130m が 35.4 秒でした。

トピック数は UMAP の乱数で揺れます。このパッケージは UMAP を random_state=42、n_jobs=1 で作り、fit_transform のたびに作り直します。乱数用の seed 引数はありません。公式 BERTopic の seed_topic_list は種になる語のリストで、このパッケージのコンストラクタにはありません。上の条件で random_state=42 にすると、政府側は 2 トピック(592 件と 90 件)になりました。数通り見るときは、_make_umap が返す UMAP の random_state を変えます。

class Seeded(BERTopic):
    def __init__(self, seed: int = 42, **kwargs):
        self._seed = seed
        super().__init__(**kwargs)

    def _make_umap(self, n_docs: int):
        model = super()._make_umap(n_docs)
        model.random_state = self._seed
        return model


for seed in (42, 1, 2):
    model = Seeded(
        seed=seed,
        embedding_model=encoder,
        min_topic_size=15,
        n_neighbors=15,
    )
    model.fit_transform(docs)

同じ MiniLM のまま、文を重なりのある窓に分けて埋め込みを平均する方法も試しました。半分を超える潰れは減りましたが、トピックの分かれ方は 512 トークン以上のモデルには及びません。重なりの幅を変えても、効果は幅に対して単調ではありませんでした。

設定ファイル

引数と YAML は同じ項目です。両方あるときは引数が優先されます。

min_topic_size: 10
nr_topics: auto
reduce_outliers: true
embedding_model: null
exclude:
  - 天気
protect:
  - レシピ
fillers: []
pos:
  - 名詞
  - 形容詞
  - 動詞
  - 形状詞
stopwords: []

stopwords を書かないときも空です。書いた語だけを外します。

topic_model = BERTopic.from_yaml("config.yaml", min_topic_size=8)
topic_model.to_yaml("config.yaml")

TIPS

初期値のまま使うときの足し方です。語のリストは任意で、指定しない限り外れません。

機能語を外す

「する」「ある」「なる」「いる」「こと」は残ります。外すときは、出てくる正規化形を exclude か stopwords に書きます。

文中 出てくる形
する、した 為る
ある、あった 有る
なる、なった 成る
いる、いた 居る
こと こと
もの 物
ため 為

「もの」は「物」、「ため」は「為」と出ます。どちらも漢字1文字です。外すときはその表記を書きます。

topic_model.exclude("為る", "有る", "成る", "居る", "こと", "物", "為")
topic_model = BERTopic(
    stopwords=["為る", "有る", "成る", "居る", "こと", "物", "為"]
)
exclude:
  - 為る
  - 有る
  - 成る
  - 居る
  - こと
  - 物
  - 為

stopwords に同じ語を書いても同じです。

名詞だけにする

topic_model = BERTopic(pos=["名詞"])
pos:
  - 名詞

文書が少ないときは、名詞だけ(pos で絞る)も試せます。

外す語を見てから決める

fit_transform のあと、suggest() で多くのトピックに出る語を見ます。preview_exclude は設定を変えずに、外したあとのトピック語を返します。決めたら exclude します。語を外すのに refit は要りません。refit は min_topic_size や nr_topics でクラスタの粗さだけを変えます。

topic_model.suggest()
topic_model.preview_exclude(["為る", "こと"])
topic_model.exclude("為る", "こと")
topic_model.refit(min_topic_size=8)

除外は出てくる形で書く

Sudachi の正規化形のため、トピック語の表示は「為る」「有る」のような漢字表記になります。exclude、protect、stopwords は、その正規化形と、文中の表層と、辞書形のどれかに一致すれば効きます。「しました」の表示は「為る」で、辞書形は「する」なので、exclude("する") でも外れます。どの表記が出ているかは get_topic_info() を見てください。LLM に除外語を調整させるときも、その結果と、表示が正規化形になる前提を渡してください。

動詞と形容詞は正規化形です。「見た」は「見る」、「高かった」は「高い」、「した」は「為る」です。exclude と stopwords にはその形を書きます。

公式との違い

公式の BERTopic(language="multilingual") は日本語の文をベクトルにできます。トピック語を作るトークナイザは英語向けの空白区切りのままで、日本語では単語に切れません。このパッケージはそのトークナイザを Sudachi に置き換え、品詞とストップワードを設定にし、語の除外とクラスタの再調整をメソッドにしています。

分類器でも、特定の業界向けの分析パイプラインでもありません。ラベルの付いていない文書から話題を探すためのものです。

リリース

PyPI へは、GitHub Release を公開したときに出します。API トークンは使いません。タグを push しただけでは出ません。

  1. PyPI のプロジェクト bertopic-ja に Trusted Publisher を追加する。Owner は Koji-Minami、Repository name は bertopic-ja、Workflow name は release.yml、Environment name は pypi。
  2. GitHub の Settings → Environments に、名前が pypi の環境を作る。シークレットは置かない。公開前に人が承認するなら、Required reviewers を付ける。
  3. この変更を main にマージしたあと、タグ v0.2.0 の GitHub Release を公開する。下書きとプレリリースでは出さない。v を除いた版が、ビルドした sdist と wheel の版と違うときは失敗する。

Metadata

Release files for bertopic-ja 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for bertopic-ja 0.2.0
File Size Uploaded Provenance Actions
bertopic_ja-0.2.0.tar.gz 187.3 kB With provenance Details for bertopic_ja-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for bertopic-ja 0.2.0
File Interpreter ABI Platform Actions
bertopic_ja-0.2.0-py3-none-any.whl Python 3 none any Details for bertopic_ja-0.2.0-py3-none-any.whl

Total release size: 205.6 kB

Release files / bertopic_ja-0.2.0.tar.gz

Download URL bertopic_ja-0.2.0.tar.gz
Size 187.3 kB
Tags Source
SHA-256 checksum
How to use checksums
aa18a4531d71fd42c614a6abd930974090cec149530703d88e4c067bd9716625
BLAKE2b-256 checksum
How to use checksums
4d4ff32824cb79c6db1ac26e33f3f5728164315461a308e2bebbde7db0cfe56c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Release files / bertopic_ja-0.2.0-py3-none-any.whl

Download URL bertopic_ja-0.2.0-py3-none-any.whl
Size 18.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3e06023d4077d302f5147354b2e43df0ffa47d287e67e62a92eef88d3948825c
BLAKE2b-256 checksum
How to use checksums
86db2e9826935d6bc3762f7dfd27fb073eeffbd756024ffa9e26afc12379e2c9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Security for bertopic-ja 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for bertopic_ja-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page