【问题标题】:stats linregress slope and intercept wrong统计 linregress 斜率和截距错误
【发布时间】:2020-08-27 08:43:34
【问题描述】:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats

xx = np.load('./x.npy')
yy = np.load('./y.npy')

fig, ax = plt.subplots()
fig = plt.gcf()
fig.set_size_inches(16, 8)
labels = ['C1', 'C2']
colors = ['r', 'b']

for idx in range(2):

    df = pd.DataFrame({'x': xx, 'y': yy[idx]})
   
    ax.set(xlim=(np.min(df.x), np.max(df.x)),
           ylim=(np.min(df.y), np.max(df.y)))

    p = sns.regplot('x',
                    'y',
                    df,
                    scatter=False,
                    order=2,
                    ax=ax,
                    label=labels[idx],
                    color=colors[idx])

    slope, intercept, r_value, p_value, std_err = stats.linregress(
        x=p.get_lines()[0].get_xdata(),
        y=p.get_lines()[0].get_ydata())
       
    formula = str(slope)     + ' x\N{SUPERSCRIPT TWO} '     + str(intercept)

    print('formula: ', formula)

我正在尝试计算 sns.regplot 拟合线的斜率和截距,它给了我:

formula:  82.53958162912909 x² 130.19916935648575
formula:  82.53958162912909 x² 130.19916935648575

其中:

  1. 您可以看到该图是错误的,对于 x 值 6 ,我们预计 y 值在 60​​0 左右。

  2. 两条线的斜率和截距相同。我们预计会有微小的差异。

你可以找到x,y文件here

【问题讨论】:

    标签: python-3.x scipy seaborn


    【解决方案1】:

    我不知道您为什么要从Line2D 对象中获取数据,即使您已经拥有xxyy 中的数据,但无论如何:

    当您在循环中计算回归时,您将在每次迭代中传递相同的数据集([0] 行)。我猜你的意思是写

    slope, intercept, r_value, p_value, std_err = stats.linregress(
                x=xx,
                y=yy[idx])
    

    【讨论】:

    • 嗨,关于第 [0] 行,您是对的。但即使使用 xx 和 yy[idx],斜率和截距也不符合 y 值。
    • 我不知道怎么做。对于 x=6,82.5*x+130.2 = 625.2,这似乎与您的数据匹配
    • 不是,linregress 计算线性拟合(一阶)
    猜你喜欢
    • 2014-02-28
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    相关资源
    最近更新 更多