102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203 | class SpacyTransformer:
nlp_cols: list[str]
"""A transformer class for cleaning text and fitting/applying a gensim LDA model."""
def __init__(self, language: str = "de_core_news_sm"):
"""Initializes the transformer by loading a spaCy language model.
Args:
language (str, optional): The name of the spaCy language model to load. Defaults to "de_core_news_sm".
"""
self.nlp: spacy.language.Language = spacy.load(language)
def model_preprocessing(self, documents: list[list[str]]):
"""Performs basic preprocessing required for gensim models.
This method creates a gensim dictionary and a bag-of-words corpus from the documents.
Args:
documents (list[list[str]]): A list of documents, where each document is a list of tokens.
"""
logger.debug("Performing basic model preprocessing steps")
self.dictionary = corpora.Dictionary(documents)
self.corpus = [self.dictionary.doc2bow(doc) for doc in documents]
def fit_lda(
self, documents: list[list[str]], num_topics: int = 10, random_state: int = 42
):
"""Fits a Latent Dirichlet Allocation (LDA) model to the documents.
This method first performs preprocessing and then fits the LDA model.
Args:
documents (list[list[str]]): A list of documents, where each document is a list of tokens.
num_topics (int, optional): The number of topics for the LDA model. Defaults to 10.
"""
self.model_preprocessing(documents)
logger.debug(f"Fitting LDA topics for {len(documents)}")
self.lda_model = gensim.models.LdaMulticore(
corpus=self.corpus,
id2word=self.dictionary,
num_topics=num_topics,
random_state=random_state,
)
self.lda_topics = {
i: descr
for (i, descr) in self.lda_model.print_topics(num_topics=num_topics)
}
def transform_documents(
self, documents: pl.DataFrame, col: str, label: str = "topic"
) -> pl.DataFrame:
"""Transforms documents into a dense matrix of LDA topic scores.
Args:
documents (pl.DataFrame): A DataFrame containing the documents to be transformed.
col (str): The name of the column containing the tokenized documents.
label (str, optional): A prefix for the new topic score columns. Defaults to "topic".
Returns:
pl.DataFrame: A new DataFrame with columns for each topic's score.
"""
logger.debug("Transforming `documents` to a dense real matrix")
corpus = [self.dictionary.doc2bow(doc) for doc in documents[col]]
scores = list(self.lda_model[corpus])
dense = make_topic_scores_dense(scores) # type: ignore
self.nlp_cols = [f"{label}_{i}" for i in range(dense.shape[1])]
return documents.with_columns(
**{c: pl.Series(dense[:, i]) for i, c in enumerate(self.nlp_cols)}
).drop(col)
def transform(
self,
df: pl.DataFrame,
col: str = "poll_title_nlp_processed",
label: str = "topic",
) -> pl.DataFrame:
"""Applies the fitted LDA model to a DataFrame to get topic scores.
This method joins the topic scores back to the original DataFrame.
Args:
df (pl.DataFrame): The DataFrame to transform.
col (str, optional): The column containing the tokenized documents. Defaults to "poll_title_nlp_processed".
label (str, optional): The prefix for the new topic score columns. Defaults to "topic".
return_new_cols (bool, optional): If True, returns the transformed DataFrame and a list of the new column names. Defaults to False.
Returns:
pl.DataFrame | tuple[pl.DataFrame, list[str]]: The transformed DataFrame, or a tuple of the DataFrame and new column names.
"""
df = df.with_row_index(name="index")
df_lda = self.transform_documents(df.select(["index", col]), col, label=label)
tmp = df.join(df_lda, on="index")
new_cols = [c for c in df_lda.columns if c.startswith(label)]
logger.debug(f"Adding nlp features: {new_cols}")
return tmp
|