当前位置: 代码迷 >> 综合 >> 聚类可视化之前使用pca报错:TypeError: PCA does not support sparse input. See TruncatedSVD for a possible alterna
  详细解决方案

聚类可视化之前使用pca报错:TypeError: PCA does not support sparse input. See TruncatedSVD for a possible alterna

热度:35   发布时间:2023-12-15 06:07:05.0

意思是,PCA不接受稀疏矩阵?

有办法将稀疏矩阵传入PCA么?——试着转为数组形式(toarray)
如不行,那应该如何操作?——使用SVD(scikit-learn中有)

参考代码:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.decomposition import TruncatedSVD
from sklearn.preprocessing import Normalizer
from sklearn.pipeline import make_pipelinedocuments = ["Beautiful is better than ugly.",
"Explicit is better than implicit.",
"Simple is better than complex.",
"Complex is better than complicated.",
"Flat is better than nested.",
"Sparse is better than dense.",
"Readability counts.",
"Special cases aren't special enough to break the rules.",
"Although practicality beats purity.",
"Errors should never pass silently.",
"Unless explicitly silenced.",
"In the face of ambiguity, refuse the temptation to guess.",
"There should be one-- and preferably only one --obvious way to do it.",
"Although that way may not be obvious at first unless you're Dutch.",
"Now is better than never.",
"Although never is often better than *right* now.",
"If the implementation is hard to explain, it's a bad idea.",
"If the implementation is easy to explain, it may be a good idea.",
"Namespaces are one honking great idea -- let's do more of those!"] tfidf_vectorizer = TfidfVectorizer(max_features=1000, stop_words='english', use_idf=True)
X = tfidf_vectorizer.fit_transform(documents)svd = TruncatedSVD(10)
normalizer = Normalizer(copy=False)
lsa = make_pipeline(svd, normalizer) 
Xnew = lsa.fit_transform(X)model = KMeans(n_clusters=3, init='k-means++', max_iter=100, n_init=1, verbose=False)
model.fit(Xnew)
  相关解决方案