【代码模版】sklearn实现随机森林模型建立与特征重要性评估

# 随机森林模型建立与训练
from sklearn.ensemble import RandomForestRegressor  # 其他模型按需要选择即可
rfr = RandomForestRegressor(n_estimators=100, max_depth=3, random_state=0)  # 参数自己看帮助文档进行选择
rfr.fit(x_train, y_train)  # 训练模型
# 基于模型的特征重要性评估
# 得到特征重要性
importances = list(model_name.feature_importances_)
# 转换格式
feature_importances = [(feature, round(importance, 2)) for feature, importance in zip(list(X.columns), importances)]
# 排序
feature_importances = sorted(feature_importances, key = lambda x: x[1], reverse = True)
# 输出展示
[print('Variable: {:20} Importance: {}'.format(*pair)) for pair in feature_importances]
# 得到特征重要性后,按照相关论文经验,选择特征直到特征重要性累加值达到95%
发布了22 篇原创文章 · 获赞 0 · 访问量 928

猜你喜欢

转载自blog.csdn.net/weixin_44680262/article/details/104609094