LDA прогнозирует одинаковые темы для всех данныхPython

Программы на Python
Anonymous
LDA прогнозирует одинаковые темы для всех данных

Сообщение Anonymous »

Я использую набор данных о немецкой политической речи для обучения модели LDA. Моя цель здесь — разделить каждое выступление на несколько тем. но проблема в том, что сгенерированные темы слишком похожи, и все прогнозы речи предсказывают одну и ту же тему.
пробовал поиграть с параметрами, не вижу никаких изменений.
Предварительная обработка: стоп-слово, используемое из nltk+ некоторые из них, сгенерированные GPT + некоторые общие слова темы, сгенерированные lda (проба и ошибка)

Код: Выделить всё

def basic_preprocess_text(text):
# Lowercase the text
text = text.lower()

# Replace umlauts and ß
text = text.replace('ä', 'ae').replace('ö', 'oe').replace('ü', 'ue').replace('ß', 'ss')

return text

stopwords = set(basic_preprocess_text(word) for word in stopwords)

def regex_filter(text) :
# Remove everything before ":" if the pattern matches
text = re.sub(r'.*\[.*\]:\s*', '', text)

# Replacing poilitical term F.D.P as FDP
text = re.sub(r'\b([A-Z]{1})\.?([A-Z]{1})\.?([A-Z]{1})\b', r'\1\2\3', text)

# replace occurrences of "Nordrhein Westfalen" with "NRW"
# text = re.sub(r'nordrhein[- .]?westfalen', 'NRW', text, flags=re.IGNORECASE)
text = re.sub(r'nordrhein[- .]?westfalen', '', text, flags=re.IGNORECASE)

#removing special charater
text = re.sub(r'[^a-zA-Zäöüß]', ' ', text)

return text

# Preprocessing function
def preprocess_text(text):

text = regex_filter(text)

# Tokenize the text
tokens = word_tokenize(text, language='german')

# Lemmatize the text & Basic preprocessing
doc = nlp(' '.join(tokens))
lemmatized_token = [basic_preprocess_text(token.lemma_) for token in doc if len(token.lemma_) > 2]

# Remove stopwords
lemmatized_text = ' '.join([word for word in lemmatized_token if word not in stopwords])

return lemmatized_text
#return tokens
Нграмм:

Код: Выделить всё

# Ensure 'Preprocessed_Speech' is treated as a list of tokens
df['Preprocessed_tokens'] = df['Preprocessed_Speech'].apply(lambda x: x.split())

# Create bigrams and trigrams
bigram = Phrases(df['Preprocessed_tokens'], min_count=3, threshold=5)
trigram = Phrases(bigram[df['Preprocessed_tokens']], min_count=3, threshold=5)

bigram_mod = Phraser(bigram)
trigram_mod = Phraser(trigram)

# Form Bigrams and Trigrams
texts = [trigram_mod[bigram_mod[text]] for text in df['Preprocessed_tokens']]

TF-IDF: я пытался взвесить какое-то слово вручную, но остановился на этом

Код: Выделить всё

# Create TF-IDF matrix
texts_joined = [' '.join(text) for text in texts]
tfidf_vectorizer = TfidfVectorizer(max_df=0.50, min_df=5, ngram_range=(1, 2))
tfidf = tfidf_vectorizer.fit_transform(texts_joined)

# Convert TF-IDF matrix to a Gensim corpus
corpus = Sparse2Corpus(tfidf, documents_columns=False)

# Create the dictionary
id2word = {v: k for k, v in tfidf_vectorizer.vocabulary_.items()}

Поезд LDA:

Код: Выделить всё

# Apply LDA with adjusted parameters
num_topics = 50  # Adjust number of topics for faster experimentation
passes = 20  # Increase number of passes
iterations = 1000  # Adjust number of iterations per pass
alpha = 'auto'  # Let gensim determine the optimal alpha
eta = 'auto'  # Let gensim determine the optimal eta

lda_model = models.LdaModel(corpus, num_topics=num_topics, id2word=id2word, passes=passes, iterations=iterations, alpha=alpha, eta=eta)
я что-то делаю не так? или набор данных не подходит для этой модели?

Подробнее здесь: https://stackoverflow.com/questions/787 ... r-all-data

Вернуться в «Python»