我计划加载我自己的一组非结构化文本数据,数据如下所示:
64.242.88.10 - - [07/Mar/2004:16:05:49 -0800] "GET /twiki/bin/edit/Main/Double_bounce_sender?topicparent=Main.ConfigurationVariables HTTP/1.1" 401 12846
或者它也可以采用以下形式:
/usr/local/etc/snmp/snmpd.conf: line 68: Error: Blank line following agentaddress token.NET-SNMP version 5.3.1
基本上,程序并不关心所给数据的结构。
我已经编辑了scikit中MeanShift示例的代码,以便我的代码可以加载我自己的数据集。在这种情况下,输入文件被命名为input。
for idx, line in enumerate(input): if(len(line) == ''): continue; line = line.strip() tmpNumPy = np.array([line]) print tmpNumPy example = np.append(example, tmpNumPy)# 计算MeanShift聚类# 以下带宽可以使用自动检测bandwidth = estimate_bandwidth(example, quantile=0.2, n_samples=500)ms = MeanShift(bandwidth=bandwidth, bin_seeding=True)ms.fit(X)labels = ms.labels_cluster_centers = ms.cluster_centers_labels_unique = np.unique(labels)n_clusters_ = len(labels_unique)print(labels_unique)print("number of estimated clusters : %d" % n_clusters_)
然而,当我运行这段代码时,它会给我以下错误:
ValueError: data type not understood
我想知道如何将一组文本数据而不是数值加载到scikit中进行MeanShift聚类,或者是否有其他我可以采取的方法?
注意:我已经查看了以下链接,但没有找到解决方案:
Meanshift in scikit learn (python) doesn’t understand datatype
Loading your own text dataset to scikit-learn
回答:
如果你想对文本进行聚类,首先你需要将你的文本数据集表示在向量空间中。标准的方法称为潜在语义分析(LSA)。基本的要点是,你计算一个矩阵,其中每一行代表一个文档,每一列代表一个术语。矩阵的元素是每个术语在每个文档中的词频-逆文档频率(tfidf)值。这个矩阵将非常大且稀疏。你将使用奇异值分解(SVD)来将这个矩阵的维度减少到你选择的“主题”数量。标准的主题数量是200-500。
一个优秀的Python包用于LSA称为Gensim。
一旦你将文本表示为向量,你就可以根据它们之间的余弦距离进行聚类,这代表了任何两个文档在语义上的相似程度。sklearn的MeanShift实现不允许你指定余弦距离,但如果你在聚类前对向量进行归一化,你仍然可以得到一个很好的语义相似性度量。