【发布时间】:2016-05-08 15:47:50
【问题描述】:
我正在使用TfidfVectorizer 将原始文档集合转换为 TF-IDF 特征矩阵,然后我计划将其输入到 k-means 算法(我将实现)。在该算法中,我将不得不计算质心(文章类别)和数据点(文章)之间的距离。我将使用欧几里得距离,所以我需要这两个实体具有相同的维度,在我的情况下为max_features。这是我所拥有的:
tfidf = TfidfVectorizer(max_features=10, strip_accents='unicode', analyzer='word', stop_words=stop_words.extra_stopwords, lowercase=True, use_idf=True)
X = tfidf.fit_transform(data['Content']) # the matrix articles x max_features(=words)
for i, row in enumerate(X):
print X[i]
但是X 似乎是一个稀疏(?)矩阵,因为输出是:
(0, 9) 0.723131915847
(0, 8) 0.090245047798
(0, 6) 0.117465276892
(0, 4) 0.379981697363
(0, 3) 0.235921470645
(0, 2) 0.0968780456528
(0, 1) 0.495689001273
(0, 9) 0.624910843051
(0, 8) 0.545911131362
(0, 7) 0.160545991411
(0, 5) 0.49900042174
(0, 4) 0.191549050212
...
我认为(0, col) 表示矩阵中的列索引,它实际上就像一个数组,其中每个单元格都指向一个列表。
如何将此矩阵转换为密集矩阵(以便每一行具有相同的列数)?
>print type(X)
<class 'scipy.sparse.csr.csr_matrix'>
【问题讨论】:
-
你能
print type(X)吗? -
很高兴@Will,我更新了我的问题。
标签: python scikit-learn cluster-analysis sparse-matrix tf-idf