【发布时间】:2020-10-24 21:58:59
【问题描述】:
我有以下数据集:
Date Text
0 05/26/2020 è morto all'improvviso jk, aveva...
1 05/26/2020 è morto a 51 anni jk, attore, co...
2 05/26/2020 aveva 51 anni e si trovava in Italia. il rico...
3 05/26/2020 arriva a milano nel 1990 per una serie di conc...
4 05/26/2020 jk, l'attore e comico, e...
5 05/26/2020 spettacolo.it ha appreso che jk, l'...
6 05/26/2020 e' morto all'improvviso jk. cant...
7 05/26/2020 addio a jk . una morte improvvis...
8 05/26/2020 lutto nel mondo della televisione. è morto a 5...
9 05/26/2020 è morto all'età di 51 anni ...
10 05/26/2020 è morto all'età di 51 anni ...
11 05/26/2020 all'improvviso se ne è andato ...
12 05/26/2020 è andato al supermercato ...
13 05/26/2020 jk è morto improvvisamente a 51 ...
14 05/26/2020 è morto, a menfi, il 51enne jk...
15 05/26/2020 muore a cinquantuno anni jk, il ...
我想使用聚类(k-mean)来创建标签来对文本进行分类。 我做了如下:
import re
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
import nltk
from nltk.corpus import stopwords
stop_words = stopwords.words('italian')
def preprocessing(line):
line = re.sub(r"[^a-zA-Z]", " ", line.lower())
words = word_tokenize(line)
words_lemmed = [WordNetLemmatizer().lemmatize(w) for w in words if w not in stop_words]
return words_lemmed
vect =TfidfVectorizer(tokenizer=preprocessing)
vectorized_text=vect.fit_transform(df['Text'])
kmeans =KMeans(n_clusters=2).fit(vectorized_text)
然后
import string as st
from pandas import Series, DataFrame
cl=kmeans.predict(vectorized_text)
df['Cluster']=pd.Series(cl, index=df.index)
df.groupby("Cluster").count()
我想知道如何可视化结果。 我试过如下:
plt.scatter(vectorized_text, cl)
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=300, c='red')
plt.show()
但我有这个错误:
ValueError: x 和 y 的大小必须相同
由于plt.scatter(vectorized_text, cl),所以那里出了点问题。在网上查看可能的解决方案时,我通过使用 PCA 找到了一些东西。我应该考虑吗?
谢谢
更新:收到下面的答案后,我尝试了:
plt.scatter(vectorized_text[:, 0] ,cl)
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=300, c='red')
plt.show()
很遗憾,我仍然收到错误消息:
ValueError: x 和 y 的大小必须相同
【问题讨论】:
-
vectorized_text和cl的形状是什么? -
@Hugolmn:为
vectorized_text:<209x1245 sparse matrix of type '<class 'numpy.float64'>' with 4718 stored elements in Compressed Sparse Row format> -
如何查看 cl 的形状?
-
cl.shape 或 len(cl) 应该可以工作
-
谢谢。所以cl的形状是(209,)
标签: python pandas cluster-analysis k-means