我很难理解scikit learn的StratifiedKfold
https://scikit-learn.org/stable/modules/cross_validation.html#stratification
并通过添加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%(?我可以从straditifiedfold中看出,n_splits定义了折叠的数量,但我认为不是split。这部分让我很困惑。
为什么当我有
n_splits=5
时,我会得到带有9个0's
和9个1's
的y_ros_test
?根据探索,它应该是50/5=10,所以不是每个分裂中都有5个1's
和5个0's
吗?
关于您的第一个问题:使用交叉验证(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_test
相关的较大的y_ros_test
(此处为18个样本,而不是10个样本(。
从方法上讲,如果你已经对数据进行了过采样以平衡类表示,那么你实际上不需要分层采样。