【问题标题】:How to split sparse matrix into train and test sets?如何将稀疏矩阵拆分为训练集和测试集?
【发布时间】:2020-01-11 14:48:30
【问题描述】:

我想了解如何使用稀疏矩阵。我有这段代码可以将多标签分类数据集生成为稀疏矩阵。

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

【问题讨论】:

  • 错误消息本身提出了解决方案。通过调用X.toarray()y.toarray() 将稀疏矩阵转换为密集矩阵后运行train_test_split() 函数
  • @Chinni:谢谢!你能发布答案吗?

标签: python numpy scikit-learn sparse-matrix


【解决方案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是什么意思吗?
  • 另外,对我来说只有这句话有效:X_train, X_test, y_train, y_test = train_test_split(X.toarray(), y, test_size=0.3)
  • 能否请您检查一下您使用的是哪个版本的 sklearn? - stackoverflow.com/questions/34842405/…
  • 我用的是'0.23.0'版本
  • 您在使用stratify=y 时是否遇到任何错误?如果是这样,您能否发布或更新您的问题?
【解决方案2】:

问题是由于stratify=y。如果您查看train_test_split 的文档,我们可以看到

*arrays

  • 允许的输入是列表、numpy 数组、scipy-sparse 矩阵或 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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 2017-07-17
    • 1970-01-01
    • 2017-06-11
    • 2015-02-18
    • 2019-05-01
    • 1970-01-01
    相关资源
    最近更新 更多