如何将稀疏矩阵分割为训练集和测试集?

4

我希望了解如何处理稀疏矩阵。我有一段代码可以生成多标签分类数据集,并将其表示为稀疏矩阵。

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 数组。


1
错误信息本身就提供了解决方案。在调用train_test_split()函数之前,通过调用X.toarray()y.toarray()将稀疏矩阵转换为密集矩阵。 - Chinni
@Chinni:谢谢!你能发表答案吗? - Fluxy
2个回答

1
错误信息本身似乎暗示了解决方案。需要将Xy都转换为密集矩阵。
请执行以下操作,
X = X.toarray()
y = y.toarray()

X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.3)

请问您能否详细解释一下 stratify=y 的含义是什么? - Fluxy
同时,对于我来说,只有这个语句有效:X_train, X_test, y_train, y_test = train_test_split(X.toarray(), y, test_size=0.3) - Fluxy
请问您能否检查一下您正在使用的sklearn版本?- https://dev59.com/XFsW5IYBdhLWcg3wi32j - Chinni
我使用的版本是'0.23.0'。 - Fluxy
当您使用 stratify=y 时,是否遇到任何错误?如果有,请发布或更新您的问题。 - Chinni
显示剩余3条评论

1
问题是由于使用了 stratify=y。如果查看 train_test_split 的文档,我们可以看到:

*arrays

  • 允许输入列表、numpy 数组、scipy 稀疏矩阵或 pandas 数据帧。

stratify

  • 类数组 (没有提到稀疏矩阵)

不幸的是,即使将此数据集转换为密集数组,也无法很好地与 stratify 配合使用:

>>> X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y.toarray(), test_size=0.3)
ValueError: The least populated class in y has only 1 member, which is too few. The minimum number of groups for any class cannot be less than 2.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接