Python 3.x Python—获取培训和测试数据的自定义采样

Python 3.x Python—获取培训和测试数据的自定义采样,python-3.x,machine-learning,Python 3.x,Machine Learning,我有一个高度不平衡的数据集 我的数据集包含1450条记录,输出为二进制0和1。输出0有1200条记录,输出1有250条记录 我正在使用这段代码为模型构建测试和培训数据集 from sklearn.cross_validation import train_test_split X = Actual_DataFrame y = Actual_DataFrame.pop('Attrition') X_train, X_test, y_train, y_test = train_test_split

我有一个高度不平衡的数据集

我的数据集包含1450条记录,输出为二进制0和1。输出0有1200条记录,输出1有250条记录

我正在使用这段代码为模型构建测试和培训数据集

from sklearn.cross_validation import train_test_split 
X = Actual_DataFrame
y = Actual_DataFrame.pop('Attrition')
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.20, random_state=42, stratify=y)
但我想通过一个函数来指定培训记录的数量,以及其中有多少百分比需要来自类“0”,有多少百分比需要来自类“1”

So, a function which takes 2 Inputs are needed for creating the training_data:-
Total Number of Records for Training Data,
Number of Records that belongs to Class '1'

这将对解决有偏差的采样数据集问题有很大帮助。

您只需编写一个函数,该函数非常类似于
sklearn
中的
train\u test\u split
。其思想是,通过输入参数
train\u size
pos\u class\u size
,您可以计算出需要多少正类样本和负类样本

def custom_split(X, y, train_size, pos_class_size, random_state=42):
    neg_class_size = train_size = pos_class_size
    pos_df = X[y == 1]
    neg_df = X[y == 0]

    pos_train = pos_df.sample(pos_class_size)
    pos_test = pos_df[~pos_df.index.isin(pos_train.index)]

    neg_train = neg_df.sample(neg_class_size)
    neg_test = neg_df[~neg_df.index.isin(neg_train.index)]

    X_train = pd.concat([pos_train,neg_train], axis=1)
    X_test = pd.concat([pos_test,neg_test], axis=1)

    y_train = y[X_train.index]
    y_test = y[X_test.index]

    return X_train, X_test, y_train, y_test
有一些方法可以节省内存或者运行得更快,我没有用这段代码做任何测试,但它应该可以工作


至少,你应该能够理解背后的想法。

我不理解
neg\u class\u size=train\u size=pos\u class\u size
中的代码。这不是平衡这两个阶级(也许是平等的)的关键吗?所以,如果我想创建一个平衡的train数据集,train_大小不应该等于2*pos_class_大小,也应该等于2*neg_class_大小吗?