小编典典

Sklearn 0.20+的交叉验证?

python

我正在尝试进行交叉验证,并且遇到一个错误:“找到的输入变量样本数量不一致:[18,1]”

我在熊猫数据框(df)中使用不同的列作为要素,最后一列作为标签。这源自UC
Irvine的机器学习存储库。导入我过去使用过的交叉验证程序包时,我收到了一个错误消息,说明它可能已贬值。我将运行决策树,SVM和K-NN。

我的代码是这样的:

feature = [df['age'], df['job'], df['marital'], df['education'], df['default'], df['housing'], df['loan'], df['contact'],
       df['month'], df['day_of_week'], df['campaign'], df['pdays'], df['previous'], df['emp.var.rate'], df['cons.price.idx'],
       df['cons.conf.idx'], df['euribor3m'], df['nr.employed']]
label = [df['y']]

from sklearn.cross_validation import train_test_split
from sklearn.model_selection import cross_val_score
# Model Training 
x = feature[:]
y = label
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5)

任何帮助将是巨大的!


阅读 202

收藏
2021-01-20

共1个答案

小编典典

cross_validation不推荐使用该模块。新模块model_selection已取代它。因此,您所做的一切cross_validation。现在可在中使用model_selection。然后,您上面的代码将变为:

feature = [df['age'], df['job'], df['marital'], df['education'], df['default'], df['housing'], df['loan'], df['contact'],
       df['month'], df['day_of_week'], df['campaign'], df['pdays'], df['previous'], df['emp.var.rate'], df['cons.price.idx'],
       df['cons.conf.idx'], df['euribor3m'], df['nr.employed']]
label = [df['y']]

from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score

现在,就声明X和y而言,为什么要将它们包装在列表中。像这样使用它们:

feature = df[['age', 'job', 'marital', 'education', 'default', 'housing', 
              'loan', 'contact', 'month', 'day_of_week', 'campaign', 
              'pdays', 'previous', 'emp.var.rate', 'cons.price.idx', 
              'cons.conf.idx', 'euribor3m', 'nr.employed']]
label = df['y']

然后,您可以简单地使用您的代码,而无需进行任何更改。

# Model Training 
x = feature[:]
y = label
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5)

对于您关于交叉验证折叠的最后一个问题,sklearn中有多个类可以做到这一点(取决于任务)。请看一下:

其中包含折叠迭代器。请记住,所有这些都在model_selection包装中。

2021-01-20