StratifiedKfold在异构DataFrame上

时间:2016-06-24 14:53:04

标签: python pandas machine-learning scikit-learn cross-validation

我有一个pandas DataFrame,它包含字符串和浮点数,需要拆分成平衡切片才能训练sklearn管道。

理想情况下,我会在DataFrame上使用StratifiedKFold来获取较小的数据块以进行交叉验证。但它抱怨说我有不可分类的类型,如:

import pandas as pd
from sklearn.cross_validation import StratifiedKFold

dataset = pd.DataFrame(
    [
        {'title': 'Dábale arroz a la zorra el abad', 'size':1.2, 'target': 1},
        {'title': 'Ana lleva al oso la avellana', 'size':1.0, 'target': 1},
        {'title': 'No te enrollé yornetón', 'size':1.4, 'target': 0},
        {'title': 'Acá sólo tito lo saca', 'size':1.4, 'target': 0},
    ])
skfs = StratifiedKFold(dataset, n_folds=2)

>>>  TypeError: unorderable types: str() > float()

有很多方法可以获得折叠索引并对DataFrame进行切片,但我认为这并不能保证我的类能够平衡。

拆分DataFrame的最佳方法是什么?

2 个答案:

答案 0 :(得分:6)

StratifiedKFold需要分割数量,.split()方法使用标签的类分布来对样本进行分层。假设您的labeltarget,您会:

from sklearn.model_selection import StratifiedKFold
skf = StratifiedKFold(n_splits=2)
X=dataset.drop('target', axis=1)
y=dataset.target
for train_index, test_index in skf.split(X, y):
    X_train, X_test = X.iloc[train_index], X.iloc[test_index]
    y_train, y_test = y.iloc[train_index], y.iloc[test_index]

答案 1 :(得分:3)

自版本0.18起,

sklearn.cross_validation.StratifiedKFold已弃用,将在0.20中删除。所以这是另一种方法:

from sklearn.model_selection import StratifiedKFold

skf = StratifiedKFold(n_splits=2)
t = dataset.target
for train_index, test_index in skf.split(np.zeros(len(t)), t):
    train = dataset.loc[train_index]
    test = dataset.loc[test_index]