【问题标题】:Why R^2 return negative and how to interpret them为什么 R^2 返回负数以及如何解释它们
【发布时间】:2021-03-16 09:58:09
【问题描述】:

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

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?希望有人可以请教我。 非常感谢

【问题讨论】:

    标签: python statistics linear-regression


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案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
      

      现在,一切都很好:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-13
        • 2020-01-20
        • 2021-10-27
        • 2022-06-20
        • 2023-03-13
        • 2021-07-17
        • 2011-08-03
        • 1970-01-01
        相关资源
        最近更新 更多