MaartenGr / MaartenGr/BERTopic

Potential bug with the PartOfSpeech class due to lower case matching

Open
#2,047 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
7.8k
Forks
920
Avg merge
22h 24m
Merged PRs (30d)
5

Description

As of v0.16.2, there is a potential bug with the PartOfSpeech class (very cool feature by the way!)

Indeed, by default, the CountVectorizer converts the tokens to lower case. In the PartOfSpeech `extract_topics` method, the `candidate_keywords` are searched in the `words_lookup` (`word_indices = [words_lookup.get(keyword) for keyword in candidate_keywords if words_lookup.get(keyword)]`).

However, the `words_lookup` is composed of lower case words by default (since they are generated using the CountVectorizer), while the candidate_keywords have the original case from the documents.

I'm not sure if this is a bug, if users are supposed to convert docs to lower case in the first place, or whether users must use the `CountVectorizer(lowercase=False)` option.

Here's an example to show what's going on:

```
import pandas as pd
from bertopic import BERTopic
from bertopic.representation import PartOfSpeech
from sklearn.feature_extraction.text import CountVectorizer

df = pd.DataFrame(
{
"text": [
"Abraham Lincoln (February 12, 1809 – April 15, 1865) was an American lawyer, politician, and statesman who served as the 16th president of the United States from 1861 until his assassination in 1865.",
"Lincoln led the United States through the American Civil War, defending the nation as a constitutional union, defeating the insurgent Confederacy, playing a major role in the abolition of slavery, expanding the power of the federal government, and modernizing the U.S. economy.",
"Lincoln was born into poverty in a log cabin in Kentucky and was raised on the frontier, mainly in Indiana.",
"He was self-educated and became a lawyer, Whig Party leader, Illinois state legislator, and U.S. representative from Illinois.",
] * 20
}
)

patterns = [
[{"POS": "NOUN"}],
[{"POS": "PROPN"}],
]

topic_model = BERTopic(
representation_model=PartOfSpeech(pos_patterns=patterns, top_n_words=5),
min_topic_size=10
)

topic_model.fit(df["text"])

topic_model.get_topic_info()
```
This results in the following topics:
```
['politician', 'president', 'assassination', 'statesman', 'lawyer']
['nation', 'abolition', 'union', 'economy', 'insurgent']
['log', 'cabin', 'frontier', 'poverty', '']
['leader', 'legislator', 'state', 'representative', 'lawyer']
```
As can be seen, there are no proper nouns here, even though the 3rd topic could only get 4 keywords because it could not find additional words matching the pattern to represent the topic, despite the proper nouns `Kentucky` and `Indiana` being available. This is because by default, `words_lookup` contains the lower case `kentucky` and `indiana`, so `Kentucky` and `Indiana` in the `candidate_keywords` cannot be found.

Note that if we use a custom vectorizer which does not convert the tokens to lower case, then the problem goes away:
```
topic_model = BERTopic(
vectorizer_model=CountVectorizer(lowercase=False),
representation_model=PartOfSpeech(pos_patterns=patterns, top_n_words=5),
min_topic_size=10
)

topic_model.fit(df["text"])

topic_model.get_topic_info()
```
We then get the following topics, which includes both nouns and proper nouns:

```
['April', 'February', 'politician', 'president', 'assassination']
['nation', 'abolition', 'union', 'Civil', 'economy']
['Kentucky', 'log', 'cabin', 'frontier', 'Indiana']
['Illinois', 'Party', 'leader', 'legislator', 'Whig']
```

This is probably not ideal though because we can get the same words with different casing (Civil vs civil)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the PartOfSpeech extract_topics method and inspect how candidate_keywords are matched against words_lookup when CountVectorizer uses its default lowercase behavior. Reproduce the provided BERTopic example, then verify that proper-noun candidates are matched without creating duplicate casing; the existing example's topic output shows the current failure.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, scikit-learn
Domain
machine-learning
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.