当我将真实值与其均值进行比较时,为 r2_score() 获取非零值

问题描述

我使用 r2_score() 方法,使用 scikit learn 评估回归问题。 正如我们所知,对于预测的决定系数 R^2,我们应该得到 0.0。 但是当我这样做时,我得到了 2.220446049250313e-16。

这是代码

from sklearn.ensemble import RandomForestRegressor
from sklearn.datasets import load_boston
import pandas as pd

boston=load_boston()
target=boston['target']
boston=pd.DataFrame(data=boston['data'],columns=boston['feature_names'])
boston['target']=target

x=boston.drop('target',axis=1)
y=boston['target']

np.random.seed(42)
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)
model=RandomForestRegressor().fit(x_train,y_train)
model.score(x_test,y_test,)

代码段返回:

0.873969014117403

和这个代码段:

from sklearn.metrics import r2_score
y_preds=model.predict(x_test)
r2_score(y_test,y_preds)

也返回:

0.873969014117403

但是当我运行这段代码时,我将测试值的平均值与其平均值进行比较:

y_test_mean=np.full(len(y_test),y_test.mean())
r2_score(y_test,y_test_mean)

我得到了值(这是一个错误):

2.220446049250313e-16

因为,根据 the scikit learn documentation,它应该是 0.0。这是那里的代码片段:

>>> y_true = [1,2,3]
>>> y_pred = [2,2]
>>> r2_score(y_true,y_pred)
0.0

我正在使用 google colaboratory 进行工作。任何人都可以帮我弄清楚,为什么会出现错误? 谢谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)