首页 文章

ValueError:找到具有不一致样本数的输入变量

提问于
浏览
0

此错误中有大量样本,其中的问题与数组的大小或数据帧的读取方式有关 . 但是,我只使用X和Y的python列表 .

我正在尝试将我的代码拆分为火车并使用train_test_split进行测试 .

我的代码是这样的:

X, y = file2vector(corpus_dir)
assert len(X) == len(y) # both lists same length
print(type(X))
print(type(y))
seed = 123
labels = list(set(y))
print(len(labels))
print(labels)
cont = {}
for l in y:
    if not l in cont:
        cont[l] = 1
    else:
        cont[l] += 1

print(cont)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=seed, stratify=labels)

输出是:

<class 'list'> # type(X)
<class 'list'> # type(y)
2 # len(labels)
['I', 'Z'] # labels
{'I': 18867, 'Z': 13009} # cont

Xy 只是我从带有 file2vector 的文件中读取的Python字符串的Python列表 . 我在python 3上运行,backtrace如下:

Traceback (most recent call last):
  File "/home/rodrigo/idatha/no_version/imm/classifier.py", line 28, in <module> X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=seed, stratify=labels)
  File "/home/rodrigo/idatha/no_version/imm/.env/lib/python3.5/site-packages/sklearn/model_selection/_split.py", line 2056, in train_test_split train, test = next(cv.split(X=arrays[0], y=stratify))
  File "/home/rodrigo/idatha/no_version/imm/.env/lib/python3.5/site-packages/sklearn/model_selection/_split.py", line 1203, in split X, y, groups = indexable(X, y, groups)
  File "/home/rodrigo/idatha/no_version/imm/.env/lib/python3.5/site-packages/sklearn/utils/validation.py", line 229, in indexable check_consistent_length(*result)
  File "/home/rodrigo/idatha/no_version/imm/.env/lib/python3.5/site-packages/sklearn/utils/validation.py", line 204, in check_consistent_length " samples: %r" % [int(l) for l in lengths])
ValueError: Found input variables with inconsistent numbers of samples: [31876, 2]

1 回答

  • 1

    问题出在您的 labels 列表中 . 在 stratify 被提供给 train_test_split 的内部,该值作为 y 参数传递给StratifiedShuffleSplit实例的split方法 . 正如您在 split 方法的文档中所看到的, y 应该与 X 的长度相同(在这种情况下是您要拆分的数组) . 所以为了解决你的问题而不是传递 stratify=labels ,只需使用 stratify=y

相关问题