问题描述
我很难从 https://scikit-learn.org/stable/modules/cross_validation.html#stratification 中理解 scikit-learn 的 StratifiedKfold
并通过添加 RandomOversample
:
X,y = np.ones((50,1)),np.hstack(([0] * 45,[1] * 5))
from imblearn.over_sampling import RandomOverSampler
ros = RandomOverSampler(sampling_strategy='minority',random_state=0)
X_ros,y_ros = ros.fit_sample(X,y)
skf = StratifiedKFold(n_splits=5,shuffle = True)
for train,test in skf.split(X_ros,y_ros):
print('train - {} | test - {}'.format(
np.bincount(y_ros[train]),np.bincount(y_ros[test])))
print(f"y_ros_test {y_ros[test]}")
train - [36 36] | test - [9 9]
y_ros_test [0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1]
train - [36 36] | test - [9 9]
y_ros_test [0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1]
train - [36 36] | test - [9 9]
y_ros_test [0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1]
train - [36 36] | test - [9 9]
y_ros_test [0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1]
train - [36 36] | test - [9 9]
y_ros_test [0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1]
我的问题:
-
我们在哪里定义训练和测试分割(分层 Kfold 中的 80% 和 20%)? 我可以从 straditifiedkfold 看到 n_splits 定义了折叠数,但不是我认为的拆分。这部分让我很困惑。
-
当我有
y_ros_test
时,为什么我在 90's
和 91's
中得到n_splits=5
? 根据探索它应该是 50/5 = 10 ,所以不是每个分裂中的 51's
和 50's
吗?
解决方法
关于您的第一个问题:使用交叉验证 (CV) 时没有任何训练测试拆分;发生的情况是,在每一轮 CV 中,一个折叠用作测试集,其余用作训练。因此,当 n_splits=5
时,像这里一样,在每一轮中,1/5(即 20%)的数据用作测试集,而剩余的 4/5(即 80%)用于训练。所以是的,确定 n_splits
参数唯一地定义了拆分,并且不需要任何进一步的确定(对于 n_splits=4
,您将获得 75-25 拆分)。
关于您的第二个问题,您似乎忘记了在拆分之前对数据进行了过采样。使用初始 X
和 y
(即没有过采样)运行您的代码确实给出了大小为 50/5 = 10 的 y_test
,尽管这并不平衡(平衡是过采样的结果) ) 但分层(每一折都保留原始数据的类比):
skf = StratifiedKFold(n_splits=5,shuffle = True)
for train,test in skf.split(X,y):
print('train - {} | test - {}'.format(
np.bincount(y[train]),np.bincount(y[test])))
print(f"y_test {y[test]}")
结果:
train - [36 4] | test - [9 1]
y_test [0 0 0 0 0 0 0 0 0 1]
train - [36 4] | test - [9 1]
y_test [0 0 0 0 0 0 0 0 0 1]
train - [36 4] | test - [9 1]
y_test [0 0 0 0 0 0 0 0 0 1]
train - [36 4] | test - [9 1]
y_test [0 0 0 0 0 0 0 0 0 1]
train - [36 4] | test - [9 1]
y_test [0 0 0 0 0 0 0 0 0 1]
由于对少数类进行过采样实际上会增加数据集的大小,因此只能期望您获得与 y_ros_test
相关性更大的 y_test
(此处为 18 个样本,而不是 10 个)。>
从方法论上讲,如果您已经对数据进行过采样以平衡类表示,则实际上不需要分层抽样。