这个错误的样本有很多,问题通常与数组的维度或数据框的读取方式有关。然而,我使用的是Python列表来表示X和Y。
我尝试使用train_test_split
将我的代码分割为训练和测试集。
我的代码如下:
X, y = file2vector(corpus_dir)assert len(X) == len(y) # 两个列表长度相同print(type(X))print(type(y))seed = 123labels = list(set(y))print(len(labels))print(labels)cont = {}for l in y: if not l in cont: cont[l] = 1 else: cont[l] += 1print(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
X
和y
只是从文件中读取的Python字符串的Python列表,我使用file2vector
进行读取。我运行在Python 3上,回溯信息如下:
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]
回答:
问题出在你的labels
列表上。当stratify
参数被提供给train_test_split
时,它的值会作为y
参数传递给split
方法,这是一个StratifiedShuffleSplit
的实例。正如文档中所述,split
方法的y
参数应该与X
(在这种情况下是你希望分割的数组)的长度相同。因此,为了解决你的问题,应该使用stratify=y
而不是stratify=labels
。