列车测试拆分,以确保所有类别都包含在列车组中



假设数据中有大约20个分类列,每个列都有一组不同的唯一分类值。现在必须进行列车测试拆分,并且需要确保所有独特的类别都包含在列车集中。如何做到这一点?我还没有尝试过,但所有这些列都应该包括在分层论证中吗?

是。这是正确的。

为了演示,我使用墨尔本住房数据集。

import pandas as pd
from sklearn.model_selection import train_test_split
Meta = pd.read_csv('melb_data.csv')
Meta = Meta[["Rooms", "Type", "Method", "Bathroom"]]
print(Meta.head())
print("nBefore split -- Method feature distributionn")
print(Meta.Method.value_counts(normalize=True))
print("nBefore split -- Type feature distributionn")
print(Meta.Type.value_counts(normalize=True))
train, test = train_test_split(Meta, test_size = 0.2, stratify=Meta[["Method", "Type"]])
print("nAfter split -- Method feature distributionn")
print(train.Method.value_counts(normalize=True))
print("nAfter split -- Type feature distributionn")
print(train.Type.value_counts(normalize=True))

输出

Rooms Type Method  Bathroom
0      2    h      S       1.0
1      2    h      S       1.0
2      3    h     SP       2.0
3      3    h     PI       2.0
4      4    h     VB       1.0
Before split -- Method feature distribution
S     0.664359
SP    0.125405
PI    0.115169
VB    0.088292
SA    0.006775
Name: Method, dtype: float64
Before split -- Type feature distribution
h    0.695803
u    0.222165
t    0.082032
Name: Type, dtype: float64
After split -- Method feature distribution
S     0.664396
SP    0.125368
PI    0.115151
VB    0.088273
SA    0.006811
Name: Method, dtype: float64
After split -- Type feature distribution
h    0.695784
u    0.222202
t    0.082014
Name: Type, dtype: float64

您希望所有分类变量中的所有类别都在您的train split中。

使用:

train, test = train_test_split(Meta, test_size = 0.2, stratify=Meta[["Method", "Type"]])

确保所有类别都在列车拆分和测试拆分中。这比你想要的要多。

必须注意的是,你对分类变量进行的分层越多,一个类别的组合就越有可能只有一个相关的记录。如果发生这种情况,就不会进行拆分。

错误消息:

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.

最新更新