我有一篇论文的数据集,但我很难验证他们报告的决定系数 R 平方。我使用了 sklearn 和 scipy 库,但得到了不同的答案。为什么?哪一个更可靠? 附注当我使用 Excel 作为另一种选择时,我得到了与 scipy 相同的答案。
下面是我用来比较 SKlearn 和 Scipy 结果的代码:
import pandas as pd
from scipy import stats
from sklearn.metrics import r2_score
data = pd.read_csv("output.csv", header=None)
y_measured = data.iloc[0, :].values
y_predicted = data.iloc[1, :].values
print(r2_score(y_measured, y_predicted)) # prints 0.708717556205
slope, intercept, r_value, p_value, std_err = stats.linregress(y_measured, y_predicted)
print(r_value**2) # prints 0.731889173485
最佳答案
r2_score
根据给定的 y 值和线性回归线预测的 y 值计算其值,而不是根据给定的 x 和 y 值。
这是一个例子。一、进口:
In [59]: import numpy as np
In [60]: from scipy import stats
In [61]: from sklearn.metrics import r2_score
一些要使用的数据:
In [62]: x = np.array([0, 1, 2, 3, 5, 8, 13])
In [63]: y = np.array([1.2, 1.4, 1.6, 1.7, 2.0, 4.1, 6.6])
使用 scipy.stats.linregress
进行线性回归,然后检查r2:
In [64]: slope, intercept, rvalue, pvalue, stderr = stats.linregress(x, y)
In [65]: rvalue**2
Out[65]: 0.9485915175891462
对于给定的 x
值,计算回归线预测的 y
值:
In [66]: ypred = slope*x + intercept
使用r2_score
再次计算r2:
In [67]: r2_score(y, ypred)
Out[67]: 0.9485915175891464
正如预期的那样,我们得到了相同的值。
我们还可以使用scipy.stats.pearsonr
来计算这个值:
In [68]: pearson_r, pearson_p = stats.pearsonr(x, y)
In [69]: pearson_r**2
Out[69]: 0.9485915175891464
关于python - scikit-learn 和 scipy 库之间的决定系数不同。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50123230/