我想了解如何使用稀疏矩阵。我有这段代码可以生成多标签分类数据集作为稀疏矩阵。
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)
并收到错误消息:
类型错误:传递了稀疏矩阵,但需要密集数据。使用
X.toarray() 转换为密集 numpy 数组。