python – 是否有可能在任何文本分类上应用PCA?

我正在尝试使用python进行分类.我正在使用Naive Bayes MultinomialNB分类器用于网页(从网络文本中检索数据形式,稍后我将此文本分类为:web分类).

现在,我正在尝试对这些数据应用PCA,但是python会给出一些错误.

我的朴素贝叶斯分类代码:

from sklearn import PCA
from sklearn import RandomizedPCA
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
vectorizer = CountVectorizer()
classifer = MultinomialNB(alpha=.01)

x_train = vectorizer.fit_transform(temizdata)
classifer.fit(x_train, y_train)

这种天真的贝叶斯分类给出了输出:

>>> x_train
<43x4429 sparse matrix of type '<class 'numpy.int64'>'
    with 6302 stored elements in Compressed Sparse Row format>

>>> print(x_train)
(0, 2966)   1
(0, 1974)   1
(0, 3296)   1
..
..
(42, 1629)  1
(42, 2833)  1
(42, 876)   1

比我尝试在我的数据(temizdata)上应用PCA:

>>> v_temizdata = vectorizer.fit_transform(temizdata)
>>> pca_t = PCA.fit_transform(v_temizdata)
>>> pca_t = PCA().fit_transform(v_temizdata)

但这引起了错误:

raise TypeError(‘A sparse matrix was passed, but dense ‘ TypeError: A
sparse matrix was passed, but dense data is required. Use X.toarray()
to convert to a dense numpy array.

我将矩阵转换为densematrix或numpy数组.然后我尝试了新的密集矩阵,但我有错误.

我的主要目的是测试PCA对文本分类的影响.

转换为密集数组:

v_temizdatatodense = v_temizdata.todense()
pca_t = PCA().fit_transform(v_temizdatatodense)

最后尝试classfy:

classifer.fit(pca_t,y_train)

最终classfy的错误:

raise ValueError(“Input X must be non-negative”) ValueError: Input X
must be non-negative

一方面,我的数据(temizdata)只放在Naive Bayes中,另一方面temizdata首先放入PCA(用于减少输入)而不是分类.
__

我不会将稀疏矩阵转换为密集(不鼓励),而是使用scikits-learn’s TruncatedSVD,这是一种类似PCA的降维算法(默认情况下使用随机SVD),适用于稀疏数据:

svd = TruncatedSVD(n_components=5, random_state=42)
data = svd.fit_transform(data) 

并且,引用TruncatedSVD文档:

In particular, truncated SVD works on term count/tf-idf matrices as returned by the vectorizers in sklearn.feature_extraction.text. In that context, it is known as latent semantic analysis (LSA).

这正是你的用例.

翻译自:https://stackoverflow.com/questions/34725726/is-it-possible-apply-pca-on-any-text-classification

转载注明原文:python – 是否有可能在任何文本分类上应用PCA?