为什么R^2返回负值以及如何解释它们

2024-10-03 09:18:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试应用不同的转换来测试这个数据集的线性回归模型

import pandas as pd
import numpy as np
import seaborn as sns

data = {'Year':  [1830, 1905, 1930, 1947, 1952, 1969],
        'Speed mph': [30,130,400,760,1500,25000],
        'Means of attaining speed': ['Railroad', 'Rairoad'
                                     , 'Airplane', 'Airplane', 'Airplane','Spaceship']
        }

df = pd.DataFrame (data, columns = ['Year','Speed mph','Means of attaining speed'])
x = df['Year'].values
y = df['Speed mph'].values

df['U2'] = np.power(2,df['Speed mph'])

u = df['U2'].values

#regression part
slope, intercept, r_value, p_value, std_err = stats.linregress(x,u)
line = slope*x+intercept
plt.plot(x, line, 'r', label='r_value={:.2f} p_value {:.2f}'.format(r_value,p_value))
#end

plt.scatter(x,u, color="k")
plt.title('${Y^2}$ vs X',fontsize=24)
plt.xlabel('Year,X',fontsize=14)
plt.ylabel('${Y^2}$',fontsize=14)

plt.tick_params(axis='both',labelsize=14)

plt.legend(fontsize=9)

plt.show()

这将返回-0.90的R平方值和p值=0.01。P值很重要,但为什么为负-0.90?希望有人能教育我。 多谢各位


Tags: importdfdatavalueasnppltyear
2条回答

在代码中:

df['U2'] = np.power(2,df['Speed mph'])

np.power函数的应用与预期不同,它将第一行设置为1073741824,其余行为零

print[df]

   Year  Speed mph Means of attaining speed          U2
0  1830         30                 Railroad  1073741824
1  1905        130                  Rairoad           0
2  1930        400                 Airplane           0
3  1947        760                 Airplane           0
4  1952       1500                 Airplane           0
5  1969      25000                Spaceship           0

将该行修改为:

df['U2'] = df['Speed mph'].apply(lambda x: x * x)

df['U2'] = df['Speed mph'].apply(np.square)

因此df变成:

   Year  Speed mph Means of attaining speed         U2
0  1830         30                 Railroad        900
1  1905        130                  Rairoad      16900
2  1930        400                 Airplane     160000
3  1947        760                 Airplane     577600
4  1952       1500                 Airplane    2250000
5  1969      25000                Spaceship  625000000

最后

r_value=0.46 p_value=0.36

现在,一切都很好:)

^{}返回线性相关系数R,而不是R2。后者是实数的平方,不能为负

对于R = −0.9,我们有R2 = 0.81.

负相关系数表示the relationship between the variables is negative(也称为“反相关”,即与不相关相同!)。也就是说,线性回归的斜率为负(在x轴上从左到右向下)

相关问题 更多 >