我有一个非常不平衡的数据集。我使用sklearn.train_test_split函数来提取训练数据集。现在我想对训练数据集进行过采样,所以我过去常常计算type1的数量(我的数据集有两个类别和类型(type1和tupe2),但我的所有训练数据都是type1。所以我不能过度抽样。
以前,我用我编写的代码拆分训练测试数据集。在所有type1数据编码0.8和所有type2数据的0.8在训练数据集中。
如何将此方法与train_test_split函数或sklearn中的其他拆分方法一起使用?
*我应该只使用sklearn或我自己的书面方法。
发布于 2020-05-19 15:23:14
你在寻找分层。Why?
在方法train_test_split
中有一个参数stratify
,您可以为其提供标签列表,例如:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,
stratify=y,
test_size=0.2)
发布于 2020-07-29 10:37:42
看起来我们在这里都有类似的问题。不幸的是,不平衡学习并不总是你需要的,并且scikit不能提供你想要的功能。您将希望实现您自己的代码。
这是我为我的应用程序想出来的。请注意,我没有大量的时间来调试它,但我相信,从我所做的测试来看,它是有效的。希望它能有所帮助:
def equal_sampler(classes, data, target, test_frac):
# Find the least frequent class and its fraction of the total
_, count = np.unique(target, return_counts=True)
fraction_of_total = min(count) / len(target)
# split further into train and test
train_frac = (1-test_frac)*fraction_of_total
test_frac = test_frac*fraction_of_total
# initialize index arrays and find length of train and test
train=[]
train_len = int(train_frac * data.shape[0])
test=[]
test_len = int(test_frac* data.shape[0])
# add values to train, drop them from the index and proceed to add to test
for i in classes:
indeces = list(target[target ==i].index.copy())
train_temp = np.random.choice(indeces, train_len, replace=False)
for val in train_temp:
train.append(val)
indeces.remove(val)
test_temp = np.random.choice(indeces, test_len, replace=False)
for val in test_temp:
test.append(val)
# X_train, y_train, X_test, y_test
return data.loc[train], target[train], data.loc[test], target[test]
对于输入,classes期望一个可能的值列表,data期望用于预测的数据框列,target期望目标列。
注意,由于三重for循环(list.remove需要线性时间),算法可能不是非常有效。尽管如此,它应该是相当快的。
发布于 2021-05-30 18:00:56
您还可以按如下方式查看分层的shuffle拆分:
# We use a utility to generate artificial classification data.
from sklearn.datasets import make_classification
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.svm import SVC
from sklearn.pipeline import make_pipeline
X, y = make_classification(n_samples=100, n_informative=10, n_classes=2)
sss = StratifiedShuffleSplit(n_splits=5, test_size=0.5, random_state=0)
for train_index, test_index in sss.split(X, y):
print("TRAIN:", train_index, "TEST:", test_index)
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
clf = make_pipeline(StandardScaler(), SVC(gamma='auto'))
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
https://stackoverflow.com/questions/61885259
复制相似问题