我有一个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的最佳方法是什么?
StratifiedKFold
要求分裂的数量,.split()
方法使用标签的类分布对样本进行分层。假设您的label
是target
,您将:
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]
sklearn.cross_validation.StratifiedKFold
自0.18版以来已弃用,并将在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]