gsa*_*ras 7 python cluster-analysis sparse-matrix tf-idf scikit-learn
我正在使用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]
Run Code Online (Sandbox Code Playgroud)
然而,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
...
Run Code Online (Sandbox Code Playgroud)
当我想的(0, col)状态列索引的矩阵,这实际上就像一个阵列,每一个细胞都指向一个列表,其中.
如何将此矩阵转换为密集矩阵(以便每行具有相同的列数)?
>print type(X)
<class 'scipy.sparse.csr.csr_matrix'>
Run Code Online (Sandbox Code Playgroud)
Wil*_*ill 12
这应该很简单:
dense = X.toarray()
Run Code Online (Sandbox Code Playgroud)
TfIdfVectorizer.fit_transform()返回一个SciPy csr_matrix()(压缩稀疏行矩阵),它有一个toarray()方法就是为了这个目的.SciPy中有几种稀疏矩阵格式,但它们都有一种.toarray()方法.
请注意,对于大型矩阵,与稀疏矩阵相比,这将使用大量内存,因此通常尽可能长时间地使其稀疏是一种很好的方法.
| 归档时间: |
|
| 查看次数: |
9880 次 |
| 最近记录: |