在train_test_split命令中,y的索引存在问题(在设置stratify时出现问题)。

9 浏览
0 Comments

在train_test_split命令中,y的索引存在问题(在设置stratify时出现问题)。

为了划分训练和测试数据:

X_train, X_test, y_train, y_test = train_test_split(X, y.iloc[:,1], test_size=0.3,random_state=seed, stratify=y)

但是当我运行时,出现了以下错误:(我已经写了x和y的大小)

Traceback (most recent call last):
  ...
   , in 
   X_train, X_test, y_train, y_test = train_test_split(X, y.iloc[:,1], test_size=0.3,random_state=seed, stratify=y)
    AttributeError: 'numpy.ndarray' object has no attribute 'iloc'


编辑:

形状如下:

Shape(X)= (284807, 28)
Shape(y)= (284807,)

然后我使用了:

X_train, X_test, y_train, y_test = train_test_split(X, y[:,1], test_size=0.3,random_state=seed, stratify=y)

但是我看到了:

IndexError: too many indices for array

如何解决这个问题?

0
0 Comments

问题出现的原因:train_test_split函数中的参数y需要是一个数组,但是在使用df.iloc[:,1]获取数据时,返回的结果是一个Series对象,并不是一个数组。

解决方法:可以使用Series对象的to_numpy()方法将其转换为数组,然后传递给train_test_split函数。

整理成一篇文章:

在使用train_test_split函数时,有时会遇到一种问题,即在设置stratify时出现问题。具体问题出现的原因是,在获取数据时使用了df.iloc[:,1],但是该方法返回的是一个Series对象,并不是一个数组。而train_test_split函数中的参数y需要是一个数组,因此就会出现问题。

解决这个问题的方法是,可以使用Series对象的to_numpy()方法将其转换为数组。具体的操作如下:

import pandas as pd
df = pd.DataFrame(nda)
y = df.iloc[:,1].to_numpy() #将选定的Series对象转换为数组

通过以上操作,就可以将获取到的数据转换为数组,并将其传递给train_test_split函数,从而解决问题。

在使用train_test_split函数时,如果遇到了设置stratify时出现问题的情况,可以考虑使用Series对象的to_numpy()方法将数据转换为数组,然后再传递给train_test_split函数即可。这样就可以解决这个问题,顺利进行后续的操作。

0
0 Comments

在使用train_test_split函数时出现了问题,问题是设置stratify参数时出错。出错的原因是stratify参数的大小必须是2 * len(arrays)的形式,而数组array可以是X或者y。

解决方法是将y.iloc[:,1]替换为y,即将y的索引改为整个y。具体代码如下:

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

在问题中提到了使用print(y.shape)来检查y的形状,新的错误信息表明y是一个一维向量,而你试图选择2个维度。关于这个问题的更多解释,可以参考IndexError: too many indices for array

此外,问题中还提到了使用[:,1]来改变y的形状,但是没有成功。

在问题的最后,还出现了另一个错误信息: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. 这个错误是由于stratify参数引起的。根据文档的建议,stratify参数的大小必须是2 * len(arrays)的形式。

最后,问题中提到了在聊天室中继续讨论这个问题的链接:continue this discussion in chat

0