如何将相似的列表聚集在一起?
How to cluster similar lists together?
我正在寻找一种能够对内容几乎相同的字符串列表进行分组的算法。
这是一个列表示例。总共有5个不同的词。
A = ['first', 'second', 'third']
B = ['first', 'forth']
C = ['second', 'third']
D = ['first', 'third']
E = ['first', 'fifth']
F = ['fourth', 'fifth']
你可以看到A、C、D有很多共同点,B、E、F也有很多共同点。
我想到了一种聚类算法,它能够为几乎相同的列表提供相同的聚类。
我想要两个聚类,确保一个词至少在一个聚类中。
在此示例中,列表 A、C 和 D 应具有簇 1
和 B、E 和 F 集群 2。
Python中是否有可用于此类问题的算法(或机器学习)?
这看起来是 Latent Dirichlet allocation 模型的一个很好的用例。
A LDA
是一个无监督模型,它在一组观察中找到相似的组,然后您可以使用它为每个观察分配一个 Topic。
您可以按照以下方式进行操作:
from sklearn.feature_extraction.text import CountVectorizer
import lda
拟合 CountVectorizer
以从字符串列表中获取标记计数矩阵:
l = [' '.join(i) for i in [A,B,C,D,E,F]]
vec = CountVectorizer(analyzer='word', ngram_range=(1,1))
X = vec.fit_transform(l)
使用lda
and fit a model on the result from the CountVectorizer
(there are also other modules with a lda
model implementation, such as in gensim)
model = lda.LDA(n_topics=2, random_state=1)
model.fit(X)
并为 2
创建的主题分配一个组号:
doc_topic = model.doc_topic_
for i in range(len(l)):
print(f'Cluster {i}: Topic ', doc_topic[i].argmax())
Cluster 0: Topic 1 # -> A
Cluster 1: Topic 0
Cluster 2: Topic 1 # -> C
Cluster 3: Topic 1 # -> D
Cluster 4: Topic 0
Cluster 5: Topic 0
我正在寻找一种能够对内容几乎相同的字符串列表进行分组的算法。
这是一个列表示例。总共有5个不同的词。
A = ['first', 'second', 'third']
B = ['first', 'forth']
C = ['second', 'third']
D = ['first', 'third']
E = ['first', 'fifth']
F = ['fourth', 'fifth']
你可以看到A、C、D有很多共同点,B、E、F也有很多共同点。
我想到了一种聚类算法,它能够为几乎相同的列表提供相同的聚类。
我想要两个聚类,确保一个词至少在一个聚类中。
在此示例中,列表 A、C 和 D 应具有簇 1
和 B、E 和 F 集群 2。
Python中是否有可用于此类问题的算法(或机器学习)?
这看起来是 Latent Dirichlet allocation 模型的一个很好的用例。
A LDA
是一个无监督模型,它在一组观察中找到相似的组,然后您可以使用它为每个观察分配一个 Topic。
您可以按照以下方式进行操作:
from sklearn.feature_extraction.text import CountVectorizer
import lda
拟合 CountVectorizer
以从字符串列表中获取标记计数矩阵:
l = [' '.join(i) for i in [A,B,C,D,E,F]]
vec = CountVectorizer(analyzer='word', ngram_range=(1,1))
X = vec.fit_transform(l)
使用lda
and fit a model on the result from the CountVectorizer
(there are also other modules with a lda
model implementation, such as in gensim)
model = lda.LDA(n_topics=2, random_state=1)
model.fit(X)
并为 2
创建的主题分配一个组号:
doc_topic = model.doc_topic_
for i in range(len(l)):
print(f'Cluster {i}: Topic ', doc_topic[i].argmax())
Cluster 0: Topic 1 # -> A
Cluster 1: Topic 0
Cluster 2: Topic 1 # -> C
Cluster 3: Topic 1 # -> D
Cluster 4: Topic 0
Cluster 5: Topic 0