答案是样本分布不均匀造成的。随机森林是一种基于决策树的集成学习算法,它会通过不断地生成新的决策树来减少过拟合的影响。然而,随机森林依旧会受到样本不均衡带来的影响。
在二分类问题中,如果一个类别的样本数量非常少,那么随机森林就可能会更倾向于预测另一个类别,尤其是在训练数据中有大量的0值时。这种情况下,随机森林模型可能会忽略1值,导致预测的1值数量非常少。
为了解决这个问题,可以采用欠采样(undersampling)或过采样(oversampling)的方法来调整样本分布,使得两个类别的样本数量更为接近,从而避免随机森林忽略某一个类
望采纳
原始样本中的1就很少,所以confusion matrix里1的绝对值计数很小是正常的。
你的样本这么imbalance,建议你用AUC做评估指标也看一下,acc其实看不出啥。
另外,你在代码里模型参数部分,已经指定class_weight强行拉到一样的权重了,但这样做有点粗暴,相当于重复正样本的oversampling方法。你可以考虑使用imblearn,借助SMOTE合成样本做上采样效果会好一点。
# 导入需要的库
from sklearn.datasets import make_classification
from imblearn.over_sampling import SMOTE
# 生成样本数据
X, y = make_classification(n_classes=2, class_sep=2, weights=[0.1, 0.9],
n_informative=3, n_redundant=1, flip_y=0,
n_features=20, n_clusters_per_class=1,
n_samples=1000, random_state=10)
# 生成过采样数据
sm = SMOTE(random_state=42)
X_res, y_res = sm.fit_resample(X, y)
题主可根据这个【分类模型评判指标--混淆矩阵】,进行自我评估评测结果是否是过拟合了,还是样本分布不均匀造成的。
链接:https://zhuanlan.zhihu.com/p/111274912
使用遗传算法优化随机森林
def RF(X):
x1, x2, x3, x4, x5 = X
mf = {0: 'auto', 1: 'sqrt', 2: 'log2', 3: None}
rf = RandomForestClassifier(n_estimators=int(x1),
max_depth=int(x2),
min_samples_split=int(x3),
min_samples_leaf=int(x4),
max_features=mf[x5],
random_state=0,
n_jobs=-1)
rf.fit(X_train, Y_train)
pred = rf.predict(X_test)
temp = f1_score(Y_test, pred)
print('F1:', temp, 'n_estimators:', x1, 'max_depth:', x2,
'min_samples_split:', x3, 'min_samples_leaf:', x4, 'max_features:',
mf[x5])
return -temp
ga = GA(
func=RF, # 优化函数
n_dim=5, # 优化参数维度
size_pop=50, # 种群规模
max_iter=10, # 最大迭代次数
lb=[100, 2, 2, 2, 0], # 下界
ub=[1000, 50, 50, 50, 3], # 上界
precision=1) # 整数约束
start_time = time.time()
best_x, best_y = ga.run()
print(time.time() - start_time)
print('best_X:', best_x, '\n', 'best_y:', best_y)