簡體   English   中英

如何可視化tf-idf向量的數據點以進行kmeans聚類?

[英]How do i visualize data points of tf-idf vectors for kmeans clustering?

我有一份文件清單和整個語料庫中每個獨特單詞的tf-idf分數。 我如何在二維圖上形象化,以便計算出運行k-means需要多少個簇?

這是我的代碼:

sentence_list=["Hi how are you", "Good morning" ...]
vectorizer=TfidfVectorizer(min_df=1, stop_words='english', decode_error='ignore')
vectorized=vectorizer.fit_transform(sentence_list)
num_samples, num_features=vectorized.shape
print "num_samples:  %d, num_features: %d" %(num_samples,num_features)
num_clusters=10

如您所見,我能夠將我的句子轉換為tf-idf文檔矩陣。 但我不確定如何繪制tf-idf分數的數據點。

我剛在想:

  1. 添加更多變量,如文檔長度和其他內容
  2. 做PCA以獲得2維的輸出

謝謝

我正在做類似的事情,試圖在2D,tf-idf分數中繪制文本數據集。 我的方法與其他評論中的建議類似,是使用來自scikit-learn的PCA和t-SNE。

import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE

num_clusters = 10
num_seeds = 10
max_iterations = 300
labels_color_map = {
    0: '#20b2aa', 1: '#ff7373', 2: '#ffe4e1', 3: '#005073', 4: '#4d0404',
    5: '#ccc0ba', 6: '#4700f9', 7: '#f6f900', 8: '#00f91d', 9: '#da8c49'
}
pca_num_components = 2
tsne_num_components = 2

# texts_list = some array of strings for which TF-IDF is being computed

# calculate tf-idf of texts
tf_idf_vectorizer = TfidfVectorizer(analyzer="word", use_idf=True, smooth_idf=True, ngram_range=(2, 3))
tf_idf_matrix = tf_idf_vectorizer.fit_transform(texts_list)

# create k-means model with custom config
clustering_model = KMeans(
    n_clusters=num_clusters,
    max_iter=max_iterations,
    precompute_distances="auto",
    n_jobs=-1
)

labels = clustering_model.fit_predict(tf_idf_matrix)
# print labels

X = tf_idf_matrix.todense()

# ----------------------------------------------------------------------------------------------------------------------

reduced_data = PCA(n_components=pca_num_components).fit_transform(X)
# print reduced_data

fig, ax = plt.subplots()
for index, instance in enumerate(reduced_data):
    # print instance, index, labels[index]
    pca_comp_1, pca_comp_2 = reduced_data[index]
    color = labels_color_map[labels[index]]
    ax.scatter(pca_comp_1, pca_comp_2, c=color)
plt.show()



# t-SNE plot
embeddings = TSNE(n_components=tsne_num_components)
Y = embeddings.fit_transform(X)
plt.scatter(Y[:, 0], Y[:, 1], cmap=plt.cm.Spectral)
plt.show()

PCA是一種方法。 對於TF-IDF,我還使用了Scikit Learn的歧管包來減少非線性尺寸。 我覺得有用的一件事是根據TF-IDF分數標記我的分數。

這是一個例子(需要在開頭插入你的TF-IDF實現):

from sklearn import manifold

# Insert your TF-IDF vectorizing here

##
# Do the dimension reduction
##
k = 10 # number of nearest neighbors to consider
d = 2 # dimensionality
pos = manifold.Isomap(k, d, eigen_solver='auto').fit_transform(.toarray())

##
# Get meaningful "cluster" labels
##
#Semantic labeling of cluster. Apply a label if the clusters max TF-IDF is in the 99% quantile of the whole corpus of TF-IDF scores
labels = vectorizer.get_feature_names() #text labels of features
clusterLabels = []
t99 = scipy.stats.mstats.mquantiles(X.data, [ 0.99])[0]
clusterLabels = []
for i in range(0,vectorized.shape[0]):
    row = vectorized.getrow(i)
    if row.max() >= t99:
        arrayIndex = numpy.where(row.data == row.max())[0][0]
        clusterLabels.append(labels[row.indices[arrayIndex]])
    else:
        clusterLabels.append('')
##
# Plot the dimension reduced data
##
pyplot.xlabel('reduced dimension-1')
pyplot.ylabel('reduced dimension-2')
for i in range(1, len(pos)):
    pyplot.scatter(pos[i][0], pos[i][1], c='cyan')
    pyplot.annotate(clusterLabels[i], pos[i], xytext=None, xycoords='data', textcoords='data', arrowprops=None)

pyplot.show()

我想你正在尋找van der Maaten和Hinton的t-SNE

出版物: http//jmlr.org/papers/volume9/vandermaaten08a/vandermaaten08a.pdf

這鏈接到一個IPython Notebook,用於使用sklearn執行此sklearn

簡而言之,t-SNE就像PCA,但更好的是在2維度的高維空間中對相關對象進行分組。 情節的空間。

根據您的要求,您可以繪制scipy.sparse.csr.csr_matrix

TfidfVectorizer.fit_transform()將為您提供(文檔ID,術語號)tf-idf得分。 現在你可以按術語創建一個numpy矩陣作為你的x軸,將文檔創建為y軸,第二個選項是繪制(temm,tf-tdf得分),或者你可以用(術語,文檔,頻率)繪制3-d在這里你也可以申請PCA。

只需從scipy.sparse.csr.csr_matrix創建一個numpy矩陣並使用matplotlib。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM