使用K-Means聚类对Python中的带分数文档进行分类

问题描述 投票:-2回答:1

我正在按照有关K均值聚类技术的教程对文档进行分类,这些文档分别进行了评分:https://towardsdatascience.com/applying-machine-learning-to-classify-an-unsupervised-text-document-e7bb6265f52

我随身携带的文档(document.csv)由摘要行组成,摘要的得分如下:

分数,摘要

3.2,这是抽象1。

3.0,The是另一个摘要,但有点不同。

2.5,又是另一个摘要。

1.5,为此编写另一个摘要毫无意义,但我必须这样做。


我正在尝试使用k-means聚类来基于上述摘要对输入的(用户)摘要进行分类。例如,如果用户插入了一个新的摘要,例如“还有另一个摘要,但有所不同”。那么应将其分类为最接近摘要的3.0分。我该如何实现?

使用上面的k均值聚类的示例,我不仅试图对吸引物进行分类,而且还将其与最接近的摘要得分相关联。

我有以下代码,以及如何对其进行调整以实现上述目标:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
import numpy as np
import pandas as pd
from csv import reader,writer
import operator as op
import string

r = reader(open('document.csv','r'))
document = []
row_count = 0
for row in list(r)[1:]:
  institute,score,abstract = row
  if len(abstract.split()) > 0:
    score = float(score)
    abstract = abstract.translate(string.punctuation)
    document.append(abstract)
    row_count = row_count + 1

print("Total rows in the document::\n %d\n" % row_count)

vectorizer = TfidfVectorizer(stop_words='english')
X = vectorizer.fit_transform(document)

#use k-mean to fit the vectorized doc into the model
true_k = row_count #true_k is equal to the number of rows of abstract
model = KMeans(n_clusters=true_k, init='k-means++', max_iter=150, n_init=1)
model.fit(X)

#get centroids and features
order_centroids = model.cluster_centers_.argsort()[:, ::-1] #centroids
terms = vectorizer.get_feature_names() #term features

#predict
abstract_input = "Yet another abstract but different."
abstract_input = abstract_input.translate(string.punctuation)
print("\n\nPrediction::\n")
X = vectorizer.transform([abstract_input])
predicted = model.predict(X)
print(predicted)

发布问题的道歉(对某些人来说可能很容易),但是,我没有在文本上使用机器学习的经验,因此,我们将不胜感激。预先谢谢你。

python machine-learning cluster-analysis k-means document
1个回答
0
投票

请勿将聚类用作最近的邻居分类器。

© www.soinside.com 2019 - 2024. All rights reserved.