【问题标题】:resample - can't create training and test sets separatelyresample - 不能分别创建训练和测试集
【发布时间】:2019-12-03 22:32:46
【问题描述】:

我正在使用引导技术来评估 MLPClassifier,并且我正在使用 scikit.utils.resample 来获取不同的随机样本,但 x_testy_test 返回的是空的:

seeds = [50,51,52,53,54]
for i in range(5): # number of bootstrap samples
    X_train, y_train = resample(X, y, n_samples=len(X), random_state=seeds[i], stratify=y)
    X_test = [x for x in X if x not in X_train] # test = samples that weren't selected for train
    y_test = [y for y in y if y not in y_train] # test = samples that weren't selected for train

    X_test
    # []

我做错了什么? /有没有更好的方法来做到这一点?很难相信sklearn 没有提供更好的方法。

【问题讨论】:

  • 你的初始 Xy 是列表还是 numpy 数组?
  • Xy 是 numpy 数组
  • 回答没有帮助?
  • 我会测试,我可能出错了,因为y_test 是空的。
  • 在下面的回答中做了一些细微的更正 - y_test 不需要转换为列表,它应该按原样工作(前提是它确实是一个 1D numpy 数组)。

标签: python arrays numpy scikit-learn resampling


【解决方案1】:

您的第一个列表推导在这里不起作用,因为 in 运算符不适用于 2D numpy 数组。

让我们首先用虚拟数据重现您的问题:

from sklearn.utils import resample
import numpy as np

X = np.array([[1., 0.], [2., 1.], [0., 0.]])
y = np.array([0, 1, 2])

X_train, y_train = resample(X, y, random_state=0)
X_train
# result
array([[ 1.,  0.],
       [ 2.,  1.],
       [ 1.,  0.]])

到目前为止一切顺利;但是,正如我所说,列表理解不起作用,因为您已经发现自己:

X_test = [x for x in X if x not in X_train]
X_test
# []

原因是 in 运算符不适用于二维 numpy 数组。

将您的初始 X 转换为列表可解决问题:

X = X.tolist()

X_train, y_train = resample(X, y, random_state=0)
X_train
# [[1.0, 0.0], [2.0, 1.0], [1.0, 0.0]] # as previous result
X_test = [x for x in X if x not in X_train]
X_test
# [[0.0, 0.0]]

正如预期的那样,我们在X_test 中得到了初始X 中唯一不存在于X_train 中的元素,即[[0.0, 0.0]]

相反,y 是一维 numpy 数组,列表推导中的 in 运算符将起作用:

y_test = [y for y in y if y not in y_train]
y_test
# [2]

【讨论】:

  • 听起来不错,但在我的实际数据中却抛出了这个错误:TypeError: Expected sequence or array-like, got <class 'builtin_function_or_method'>
  • @joann2555 你导入numpy了吗?如果是,请编辑您的帖子以包含您的初始 X 数据示例。
  • 没关系,我明白了。但是出现了另一个问题:我应该在引导之前拆分xy吗?如果我之前拆分,y_test 将始终为空。
  • @joann2555 对不起,我没听懂;你使用resample 的方式,你的y_test 永远不会是空的。在任何情况下,cmets 都不是此类后续问题的正确位置,与 OP 无关;如果答案解决了您所面临的特定编码问题,请接受它,我们总是非常欢迎您提出可能存在新问题的新问题。
猜你喜欢
  • 2017-11-01
  • 2019-03-21
  • 2017-09-11
  • 2016-04-04
  • 1970-01-01
  • 2018-06-03
  • 1970-01-01
  • 2015-07-16
  • 1970-01-01
相关资源
最近更新 更多