【发布时间】:2015-10-20 05:30:42
【问题描述】:
我正在使用 RandomForest 进行分类,我得到了一个不平衡的数据集,如:5830-否,1006-是。我尝试用 class_weight 和 sample_weight 平衡我的数据集,但我做不到。
我的代码是:
X_train,X_test,y_train,y_test = train_test_split(arrX,y,test_size=0.25)
cw='auto'
clf=RandomForestClassifier(class_weight=cw)
param_grid = { 'n_estimators': [10,50,100,200,300],'max_features': ['auto', 'sqrt', 'log2']}
sw = np.array([1 if i == 0 else 8 for i in y_train])
CV_clf = GridSearchCV(estimator=clf, param_grid=param_grid, cv= 10,fit_params={'sample_weight': sw})
但是当使用 class_weight 和 sample_weight 时,我的比率 TPR、FPR、ROC 没有任何改善。
为什么?我做错什么了吗?
不过,如果我使用称为 balance_subsample 的函数,我的比率会得到很大的改善:
def balanced_subsample(x,y,subsample_size):
class_xs = []
min_elems = None
for yi in np.unique(y):
elems = x[(y == yi)]
class_xs.append((yi, elems))
if min_elems == None or elems.shape[0] < min_elems:
min_elems = elems.shape[0]
use_elems = min_elems
if subsample_size < 1:
use_elems = int(min_elems*subsample_size)
xs = []
ys = []
for ci,this_xs in class_xs:
if len(this_xs) > use_elems:
np.random.shuffle(this_xs)
x_ = this_xs[:use_elems]
y_ = np.empty(use_elems)
y_.fill(ci)
xs.append(x_)
ys.append(y_)
xs = np.concatenate(xs)
ys = np.concatenate(ys)
return xs,ys
我的新代码是:
X_train_subsampled,y_train_subsampled=balanced_subsample(arrX,y,0.5)
X_train,X_test,y_train,y_test = train_test_split(X_train_subsampled,y_train_subsampled,test_size=0.25)
cw='auto'
clf=RandomForestClassifier(class_weight=cw)
param_grid = { 'n_estimators': [10,50,100,200,300],'max_features': ['auto', 'sqrt', 'log2']}
sw = np.array([1 if i == 0 else 8 for i in y_train])
CV_clf = GridSearchCV(estimator=clf, param_grid=param_grid, cv= 10,fit_params={'sample_weight': sw})
谢谢
【问题讨论】:
-
我无法在玩具数据集上重现它(我的意思是我的第一个 sn-p 获得了更好的精度/召回率)。您能否发布有关 TP、FP 率等的结果?例如
print(classification_report(y_test, CV_clf.predict(X_test)的输出。我对您的“新代码”感到困惑,因为您在自定义平衡之上仍在使用class_weight和sample_weight。 -
我的错,我没有使用不平衡的类。对于我来说,第一个 sn-p 的 auc 结果仍然比第二个更好,所以如果你能发布你的指标就好了。
-
案例 1:使用 class_weight='auto' 和 sample_weight='1-8' (如代码所示),我得到 TPR=0.17 和 FPR=0.004。案例 2:但是当我使用函数 balance_subsample 时 subsample_size=0.5(如代码所示),我得到 TPR=0.85 和 FPR=0.13。在第二种情况下,我意识到再次尝试使用相同的值,比率会发生很大变化,但总是比 CASE 1 好得多。
标签: class scikit-learn random-forest balance