You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Scikit-Learn随机森林回归器出现预测结果全相同的问题

随机森林回归器预测结果全为同一数值的原因分析

问题描述

我正在使用Scikit-Learn 1.1.1版本针对数据集构建随机森林回归器,但每次运行后返回的预测结果均完全相同。以下是我使用的代码:

# Set target and feature variables
target = merged_df[target_variable]
merged_df.drop(target_variable, axis=1, inplace=True)

features_list = list(merged_df.columns)

# Adjust features being used based on user input
if (features == all):
    features_list = features_list
elif (type(features) == list):
    using_features = []
    for element in features:
        using_features.append(features_list.index(element))
    features_list = using_features
    
X = merged_df
y = target

# Set training and testing groups
train_features, test_features, train_target, test_target = train_test_split(X, y, random_state=rdm_state)
print(train_features)
print(test_features)
print(train_target)
print(test_target)
# Train model

rf = RandomForestRegressor()
rf.fit(train_features, train_target)

# Make predictions and calculate error
predictions = rf.predict(test_features)

最终predictions是一个所有元素均为同一数值的数组,请问这是什么原因导致的?


可能的原因及排查方案

  • 特征选择逻辑未生效
    代码中当features为列表时,仅生成了特征索引列表using_features并赋值给features_list,但并未将筛选逻辑应用到X上——X = merged_df仍然使用了全部特征。此外,if (features == all):的判断完全错误,all是Python内置函数,这里应该判断features == "all"(假设用户输入的全特征标识是字符串"all"),否则该分支永远不会触发。

  • 数据本身存在极端分布

    • 检查train_target和test_target的分布:如果目标变量本身绝大多数甚至全部样本取值相同,模型自然会输出单一预测值;
    • 检查特征区分度:用merged_df.describe()查看各特征的方差,方差为0的特征是常量,无法为模型提供有效信息,导致模型只能输出训练集目标的均值。
  • 模型参数或训练逻辑问题

    • 若数据集极小,或者min_samples_split/min_samples_leaf的默认值相对数据来说过大,会导致所有决策树无法分裂,最终输出单一值;
    • 用单个DecisionTreeRegressor测试,如果单棵树也输出相同结果,说明问题出在数据而非集成逻辑。
  • 数据预处理缺失
    确认所有特征均为数值型,若存在未处理的非数值特征(如字符串),随机森林会直接报错,但如果是隐性问题(如特征全部为常量),则会导致模型无法学习到有效模式。


快速修复建议

  1. 修正特征选择逻辑:当features为列表时,执行X = merged_df.iloc[:, using_features]筛选特征;将if (features == all):改为if features == "all":;
  2. 检查数据分布:用print(train_target.value_counts())查看目标变量分布,用merged_df.var()查看特征方差;
  3. 调整模型参数:尝试增加n_estimators,或设置max_depth为5、10等数值,观察预测结果是否变化。

内容的提问来源于stack exchange,提问作者collegestudent8

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 13:54:22