Gue*_*est 5 python machine-learning logistic-regression train-test-split smote
我有一个包含以下列的数据文件
'customer', 'calibrat' - 校准样本 = 1; 验证样本 = 0; 'churn', 'churndep', '收入', 'mou',
数据文件包含大约 40000 行,其中 20000 行的校准值为 1。我想将此数据拆分为
X1 = data.loc[:, data.columns != 'churn']
y1 = data.loc[:, data.columns == 'churn']
from imblearn.over_sampling import SMOTE
os = SMOTE(random_state=0)
X1_train, X1_test, y1_train, y1_test = train_test_split(X1, y1, test_size=0.3, random_state=0)
Run Code Online (Sandbox Code Playgroud)
我想要的是,在我的 X1_train 中应该带有 calibrat =1 的校准数据,而在 X1_test 中应该带有用于验证的所有数据 calibrat = 0
sklearn.model_selection
除了 之外还有其他几个选项train_test_split
。其中之一旨在解决您所要求的问题。在这种情况下,您可以使用GroupShuffleSplit
,正如文档中提到的,它提供随机训练/测试索引来根据第三方提供的组分割数据。当您进行交叉验证并且希望在验证训练中多次拆分以确保集合按字段拆分时,这非常有用group
。对于这些情况,您也有GroupKFold
非常有用的。
因此,调整您的示例,这就是您可以做的事情。
假设你有例如:
from sklearn.model_selection import GroupShuffleSplit
cols = ['customer', 'calibrat', 'churn', 'churndep', 'revenue', 'mou',]
X = pd.DataFrame(np.random.rand(10, 6), columns=cols)
X['calibrat'] = np.random.choice([0,1], size=10)
print(X)
customer calibrat churn churndep revenue mou
0 0.523571 1 0.394896 0.933637 0.232630 0.103486
1 0.456720 1 0.850961 0.183556 0.885724 0.993898
2 0.411568 1 0.003360 0.774391 0.822560 0.840763
3 0.148390 0 0.115748 0.089891 0.842580 0.565432
4 0.505548 0 0.370198 0.566005 0.498009 0.601986
5 0.527433 0 0.550194 0.991227 0.516154 0.283175
6 0.983699 0 0.514049 0.958328 0.005034 0.050860
7 0.923172 0 0.531747 0.026763 0.450077 0.961465
8 0.344771 1 0.332537 0.046829 0.047598 0.324098
9 0.195655 0 0.903370 0.399686 0.170009 0.578925
y = X.pop('churn')
Run Code Online (Sandbox Code Playgroud)
您现在可以实例化GroupShuffleSplit
,并像使用 一样执行操作train_test_split
,唯一的区别是指定group
将用于拆分的列X
,y
以便根据组值拆分组:
gs = GroupShuffleSplit(n_splits=2, train_size=.7, random_state=42)
Run Code Online (Sandbox Code Playgroud)
如前所述,当您想要分成多个组(通常用于交叉验证目的)时,这会更方便。正如问题中提到的,这只是如何进行两次拆分的示例:
train_ix, test_ix = next(gs.split(X, y, groups=X.calibrat))
X_train = X.loc[train_ix]
y_train = y.loc[train_ix]
X_test = X.loc[test_ix]
y_test = y.loc[test_ix]
Run Code Online (Sandbox Code Playgroud)
给予:
print(X_train)
customer calibrat churndep revenue mou
3 0.148390 0 0.089891 0.842580 0.565432
4 0.505548 0 0.566005 0.498009 0.601986
5 0.527433 0 0.991227 0.516154 0.283175
6 0.983699 0 0.958328 0.005034 0.050860
7 0.923172 0 0.026763 0.450077 0.961465
9 0.195655 0 0.399686 0.170009 0.578925
print(X_test)
customer calibrat churndep revenue mou
0 0.523571 1 0.933637 0.232630 0.103486
1 0.456720 1 0.183556 0.885724 0.993898
2 0.411568 1 0.774391 0.822560 0.840763
8 0.344771 1 0.046829 0.047598 0.324098
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2452 次 |
最近记录: |