我希望了解如何处理稀疏矩阵。我有一段代码可以生成多标签分类数据集,并将其表示为稀疏矩阵。
from sklearn.datasets import make_multilabel_classification
X, y = make_multilabel_classification(sparse = True, n_labels = 20, return_indicator = 'sparse', allow_unlabeled = False)
这段代码以以下格式给出X:
<100x20 sparse matrix of type '<class 'numpy.float64'>'
with 1797 stored elements in Compressed Sparse Row format>
y:
<100x5 sparse matrix of type '<class 'numpy.int64'>'
with 471 stored elements in Compressed Sparse Row format>
现在我需要将X和y分成X_train,X_test,y_train和y_test,使得训练集占70%。我该怎么做?
这是我尝试的方法:
X_train, X_test, y_train, y_test = train_test_split(X.toarray(), y, stratify=y, test_size=0.3)
我收到了以下错误信息:
TypeError: 传递了一个稀疏矩阵,但需要密集数据。使用 X.toarray() 将其转换为密集的 numpy 数组。
train_test_split()
函数之前,通过调用X.toarray()
和y.toarray()
将稀疏矩阵转换为密集矩阵。 - Chinni