[英]3D plot for the fitted regression surface with matplotlib
我正在尝试制作一个 3D 图来绘制拟合的回归曲面。 我看过以下例子。
但是,第一个非常过时并且不再工作,第二个是相关的,但是我在生成Z
的值时遇到了一些麻烦。 我能找到的所有示例都是过时的或低级别的模拟数据示例。 可能存在比Z
更多的问题。 请看下面的代码。
import numpy as np
import seaborn as sns
import statsmodels.formula.api as smf
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
df = sns.load_dataset('mpg')
df.dropna(inplace=True)
model = smf.ols(formula='mpg ~ horsepower + acceleration', data=df)
results = model.fit()
x, y = model.exog_names[1:]
x_range = np.arange(df[x].min(), df[x].max())
y_range = np.arange(df[y].min(), df[y].max())
X, Y = np.meshgrid(x_range, y_range)
# Z = results.fittedvalues.values.reshape()
fig = plt.figure(figsize=plt.figaspect(1)*3)
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, alpha = 0.2)
更新:
我把Z
改成以下是对的
Z = results.params[0] + X*results.params[1] + Y*results.params[2]
并附加
ax.scatter(df[x], df[y], df[model.endog_names], s=50)
ax.view_init(20, 120)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
我得到了以下情节,但我不确定它是否正确。
如果可能,我还想为绘制的表面添加投影。
在您链接的答案中,关键步骤是通过提供“外生”数据将模型应用于整个网格。 在这种情况下,您可以通过创建一个包含解开的网格的新数据框并将其作为exog
传递给exog
来statsmodels.regression.linear_model.OLS.predict
这statsmodels.regression.linear_model.OLS.predict
。 使用您的示例对此进行演示:
import numpy as np
import seaborn as sns
import statsmodels.formula.api as smf
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
df = sns.load_dataset('mpg')
df.dropna(inplace=True)
model = smf.ols(formula='mpg ~ horsepower + acceleration', data=df)
results = model.fit()
x, y = model.exog_names[1:]
x_range = np.arange(df[x].min(), df[x].max())
y_range = np.arange(df[y].min(), df[y].max())
X, Y = np.meshgrid(x_range, y_range)
exog = pd.DataFrame({x: X.ravel(), y: Y.ravel()})
Z = results.predict(exog = exog).values.reshape(X.shape)
fig = plt.figure(figsize=plt.figaspect(1)*2)
ax = plt.axes(projection='3d')
ax.scatter(df[x].values, df[y].values, results.fittedvalues.values,
marker='.', label="Fits")
cond = df[model.endog_names].values > results.fittedvalues.values
ax.scatter(df[x][cond].values, df[y][cond].values, df[model.endog_names]
[cond].values, label="Raw")
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, alpha = 0.4)
ax.scatter(df[x][cond == False].values, df[y][cond == False].values,
df[model.endog_names][cond == False].values)
ax.legend()
plt.show()
哪个会给你
除了数据点之外,我还在散点图中包含了各个拟合点,以表明这种方法可以正确生成相应的表面。 我还将数据分为两组:那些应该绘制在表面前面的和那些应该绘制在表面后面的。 这是为了适应 matplotlib 在 3D 渲染中的艺术家分层。 查看几何图形已从默认更改,以尝试最大限度地提高 3D 属性的清晰度。
将回归曲面的投影添加到轴平面之一是相当简单的 - 您只需将一维设置为轴限制来绘制数据,即
ax.plot_surface(X, Y, np.full_like(X, ax.get_zlim()[0]), alpha = 0.2)
然后给你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.