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

作物产量预测随机森林建模执行np.arange报真值歧义错误如何解决

报错原因

  • indp = df.iloc[:,1:6].values 得到的是形状为(样本数, 5)的二维数组,包含你选的5个特征。min(indp)、max(indp)会返回每个特征对应的最小/最大值,是包含5个元素的一维数组,而np.arange要求起始值、终止值都是单个标量,传入数组就会触发你遇到的布尔值歧义报错。
  • 就算解决了np.arange的报错,后续你生成的x_grid是只有1列的数组,和随机森林训练用的5个特征维度不匹配,调用reg.predict(x_grid)时还会报错特征数不一致。

解决方案

根据你的需求选择对应方案:

方案1:绘制单个特征和产量的随机森林拟合曲线

如果需要展示单个特征对产量的影响,固定其余特征为数据集均值即可,示例代码如下(以绘制降水量Precipitation为例):

# 替换原报错行及之后的所有绘图代码
# 选择要绘制的特征索引,0对应Precipitation,1对应Min_Temp,2对应Cloud_Cover,3对应Vapour_pressure,4对应Area
feature_idx = 0
feature_name = X.columns[feature_idx]

# 生成单特征的网格序列
x_grid = np.arange(indp[:, feature_idx].min(), indp[:, feature_idx].max(), 0.01)
# 构造符合模型输入要求的5特征数组,其余特征固定为数据集平均值
X_grid = np.tile(indp.mean(axis=0), (len(x_grid), 1))
X_grid[:, feature_idx] = x_grid

# 绘图
plt.scatter(indp[:, feature_idx], dep, color = 'red')
plt.plot(x_grid, reg.predict(X_grid), color ='blue')
plt.title(f'Random forest regression ({feature_name} Vs Production)')
plt.xlabel(feature_name)
plt.ylabel('Production')
plt.show()

方案2:绘制真实值与预测值对比图评估模型效果

多特征回归模型更适合用真实值和预测值的散点图直观展示拟合效果,代码如下:

# 替换原报错行及之后的所有代码
y_pred_reg = reg.predict(indp)
plt.scatter(dep, y_pred_reg, color='red')
# 绘制y=x参考线,点越靠近参考线说明拟合效果越好
min_val = min(dep.min(), y_pred_reg.min())
max_val = max(dep.max(), y_pred_reg.max())
plt.plot([min_val, max_val], [min_val, max_val], color='blue', label='Reference line: y=x')
plt.title('Random forest regression: True Vs Predicted Production')
plt.xlabel('True Production')
plt.ylabel('Predicted Production')
plt.legend()
plt.grid()
plt.show()

# 输出模型拟合得分
print(f'Random forest R2 score: {r2_score(dep, y_pred_reg)}')

额外优化提示

  • 你当前的代码流程是先划分训练集测试集,再做数据预处理,会出现数据泄露问题,正确流程应为先完成全量数据预处理,再划分训练集、测试集。
  • 预处理函数中的df.reset_index()需要添加inplace=True参数,或者赋值为df = df.reset_index(drop=True),否则索引重置不会生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:06:04