我想聚类 160 000 个文档或可变长度。
问题: Spacy LM 模型“en_core_web_lg”没有我文档中出现的所有单词。 创建 Ngrams 还包括 non_present 词来影响 ngram 的向量。
我试过的解决方案: 我覆盖了 TfIdfVectorizer 的 _word_ngrams 方法来处理这个。
import spacy
from sklearn.feature_extraction.text import TfidfVectorizer
class NewTfidfVectorizer(TfidfVectorizer):
def _word_ngrams(self, tokens, stop_words=None):
nlp = spacy.load('en_core_web_lg')
"""Turn tokens into a sequence of n-grams after stop words filtering and removing words which are out of lm model"""
tokens = super(TfidfVectorizer, self)._word_ngrams(tokens, None)
new_tokens = []
for token in tokens:
split_words = token.split(' ')
if len(split_words) == 1:
if nlp.vocab.has_vector(token):
new_tokens.append(token)
for token in tokens:
split_words = token.split(' ')
new_words = []
for word in split_words:
if word in new_tokens:
new_words.append(word)
new_tokens.append(' '.join(new_words))
# Convert the list to a set, which automatically removes duplicates
unique_tokens = set(new_tokens)
# Convert the set back to a list
unique_tokens_list = list(unique_tokens)
return sorted(unique_tokens_list)`
现在的问题:需要大量的时间来适应这个
NGRAM_RANGE = (1, 3)
tfidf_vectorizer = NewTfidfVectorizer(analyzer='word', norm=None, ngram_range=NGRAM_RANGE, stop_words='english', use_idf=True, smooth_idf=True)
tfidf_matrix = tfidf_vectorizer.fit_transform(docs) # sparse matrix
vocab = tfidf_vectorizer.get_feature_names_out()
第 1 步:处理数据:去除停用词、html、xml 标签和词干提取 通过 nltk 停用词和一个个人停用词列表删除停用词、html 和 xml 标签。
Step 2: Tf-Idf fitting: used ngrams_range (1,3)
第三步:归一化tfidf矩阵(weighted_ifidf):“这一步可以忽略”
第 4 步:以此格式创建字典。 {“doc1”:[(“word1”,2.45),(“word2”,3.93454)],“doc2”:{(“word5”,1.395),(“word9”,4.2455)]}}
第五步:基于归一化tfidf矩阵对向量取加权平均:(vector12 + vector23 + vector3*1)/6
第 6 步:使用 HDBSCAN 进行聚类
其他问题:
尽管我在每个点都对 tfidf 使用稀疏矩阵,但第 5 步的过程非常密集。
数据包含人名和公司名称,确实会对集群形成产生影响