gpt4 book ai didi

python - 如何使用 `lmplot` 绘制无截距的线性回归?

转载 作者:行者123 更新时间:2023-12-03 03:01:50 25 4
gpt4 key购买 nike

seaborn 中的 lmplot 通过截距拟合回归模型。然而,有时我想拟合回归模型无截距,即通过原点回归。

例如:

In [1]: import numpy as np
...: import pandas as pd
...: import seaborn as sns
...: import matplotlib.pyplot as plt
...: import statsmodels.formula.api as sfa
...:

In [2]: %matplotlib inline
In [3]: np.random.seed(2016)
In [4]: x = np.linspace(0, 10, 32)
In [5]: y = 0.3 * x + np.random.randn(len(x))
In [6]: df = pd.DataFrame({'x': x, 'y': y})
In [7]: r = sfa.ols('y ~ x + 0', data=df).fit()
In [8]: sns.lmplot(x='x', y='y', data=df, fit_reg=True)
Out[8]: <seaborn.axisgrid.FacetGrid at 0xac88a20>

enter image description here

我想要的数字:

In [9]: fig, ax = plt.subplots(figsize=(5, 5))
...: ax.scatter(x=x, y=y)
...: ax.plot(x, r.fittedvalues)
...:
Out[9]: [<matplotlib.lines.Line2D at 0x5675a20>]

enter image description here

最佳答案

seaborn API 不允许直接更改线性回归模型。

调用链是:

  • 在某个时刻_RegressionPlotter.plot()被调用来生成绘图
  • 调用 _RegressionPlotter.lineplot()执行拟合图
  • 它本身调用 fit_regression位于 regression模块
  • 这又调用了许多seaborn回归方法,例如self.fit_fast(grid)在你的情况下。

要使用不同的回归模型,您可以:

  • 猴子补丁 _RegressionPlotter类并更改 lineplot()行为
  • 猴子补丁 fit_regression()fit_fast()回归模块中的方法

要做这样的seaborn猴子补丁,可以引用an answer I made a while ago that does the same type of hack 。这太糟糕了,圣诞老人可能会不高兴。这意味着您可以根据预期目的动态修改seaborn。

当然,您需要实现自己的回归模型才能在 for y = a * x 中具有规律。而不是 y = (a * x) + bimportanceofbeingernest已经在评论中指出this SO question就此而言。

<小时/>

一种优雅的方法是构建自己的情节,但您已经在自己的问题中回答了该部分。

引用你自己的问题(我没有检查提供的代码):

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.formula.api as sfa

np.random.seed(2016)
x = np.linspace(0, 10, 32)
y = 0.3 * x + np.random.randn(len(x))
df = pd.DataFrame({'x': x, 'y': y})
r = sfa.ols('y ~ x + 0', data=df).fit()
fig, ax = plt.subplots(figsize=(5, 5))
ax.scatter(x=x, y=y)
ax.plot(x, r.fittedvalues)

关于python - 如何使用 `lmplot` 绘制无截距的线性回归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34725835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com