python - 如何在 Python 中使用 n-gram 重叠对句子进行聚类?
问题描述
我需要根据它们包含的常见 n-gram 对句子进行聚类。我可以使用 nltk 轻松提取 n-gram,但我不知道如何基于 n-gram 重叠执行聚类。这就是为什么我不能写出如此真实的代码,首先我很抱歉。我写了 6 个简单的句子和预期的输出来说明问题。
import nltk
Sentences= """I would like to eat pizza with her.
She would like to eat pizza with olive.
There are some sentences must be clustered.
These sentences must be clustered according to common trigrams.
The quick brown fox jumps over the lazy dog.
Apples are red, bananas are yellow."""
sent_detector = nltk.data.load('tokenizers/punkt/'+'English'+'.pickle')
sentence_tokens = sent_detector.tokenize(sentences.strip())
mytrigrams=[]
for sentence in sentence_tokens:
trigrams=ngrams(sentence.lower().split(), 3)
mytrigrams.append(list(trigrams))
在此之后我不知道(我什至不确定这部分是否可以。)如何根据常见的三元组对它们进行聚类。我试着做,itertools-combinations
但我迷路了,我不知道如何生成多个集群,因为如果不将每个句子相互比较,就无法知道集群的数量。下面给出了预期的输出,在此先感谢您的帮助。
Cluster1: 'I would like to eat pizza with her.'
'She would like to eat pizza with olive.'
Cluster2: 'There are some sentences must be clustered.'
'These sentences must be clustered according to common trigrams.'
Sentences do not belong to any cluster:
'The quick brown fox jumps over the lazy dog.'
'Apples are red, bananas are yellow.'
编辑:我又尝试了combinations
一次,但它根本没有聚集,只是返回了所有句子对。(显然我做错了什么)。
from itertools import combinations
new_dict = {k: v for k, v in zip(sentence_tokens, mytrigrams)}
common=[]
no_cluster=[]
sentence_pairs=combinations(new_dict.keys(), 2)
for keys, values in new_dict.items():
for values in sentence_pairs:
sentence1= values[0]
sentence2= values[1]
#print(sentence1, sentence2)
if len(set(sentence1) & set(sentence2))!=0:
common.append((sentence1, sentence2))
else:
no_cluster.append((sentence1, sentence2))
print(common)
但即使这段代码有效,它也不会给出我期望的输出,因为我不知道如何基于常见的 n-gram 生成多个集群
解决方案
为了更好地理解您的问题,您可以解释目的和预期结果。
使用 Ngrams 必须非常小心,当使用 ngrams 时,您会增加数据集的维数。
我建议你先使用 TD-IDF,然后如果你没有达到最低命中率,你就去 n-gram。
如果你能更好地解释你的问题,我可以看看我是否可以帮助你。
推荐阅读
- neo4j - 查询联合取决于列表中的变量
- java - H2 内存表未在 Spring Boot 应用程序中填充
- mobile - 如果原生移动应用打开浏览器,它是否与原生浏览器共享本地存储?
- php - Google Analytics API - 返回的行数与返回的总数不同
- javascript - Phaser 3 阵列碰撞
- mysql - Mysql5.6 select语句重复id和set
- python - AttributeError:“NoneType”对象没有“读取”属性?
- python-3.9 - 将 Python 添加到 PATH
- javascript - 未捕获的 TypeError:data.reduce 不是函数
- elasticsearch - 在elasticsearch中按某个字段分组时,我们如何获得每个组的计数?