- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
给定一些随机生成的数据
使用R,可以这样实现泊松glm和诊断图:
> col=2
> row=50
> range=0:100
> df <- data.frame(replicate(col,sample(range,row,rep=TRUE)))
> model <- glm(X2 ~ X1, data = df, family = poisson)
> glm.diag.plots(model)
在Python中,这将为我提供线预测器与残差图:
import numpy as np
import pandas as pd
import statsmodels.formula.api
from statsmodels.genmod.families import Poisson
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.randint(100, size=(50,2)))
df.rename(columns={0:'X1', 1:'X2'}, inplace=True)
glm = statsmodels.formula.api.gee
model = glm("X2 ~ X1", groups=None, data=df, family=Poisson())
results = model.fit()
并用 Python 绘制诊断图:
model_fitted_y = results.fittedvalues # fitted values (need a constant term for intercept)
model_residuals = results.resid # model residuals
model_abs_resid = np.abs(model_residuals) # absolute residuals
plot_lm_1 = plt.figure(1)
plot_lm_1.set_figheight(8)
plot_lm_1.set_figwidth(12)
plot_lm_1.axes[0] = sns.residplot(model_fitted_y, 'X2', data=df, lowess=True, scatter_kws={'alpha': 0.5}, line_kws={'color': 'red', 'lw': 1, 'alpha': 0.8})
plot_lm_1.axes[0].set_xlabel('Line Predictor')
plot_lm_1.axes[0].set_ylabel('Residuals')
plt.show()
但是当我尝试获取厨师统计数据时,
# cook's distance, from statsmodels internals
model_cooks = results.get_influence().cooks_distance[0]
它抛出一个错误:
AttributeError Traceback (most recent call last)
<ipython-input-66-0f2bedfa1741> in <module>()
4 model_residuals = results.resid
5 # normalized residuals
----> 6 model_norm_residuals = results.get_influence().resid_studentized_internal
7 # absolute squared normalized residuals
8 model_norm_residuals_abs_sqrt = np.sqrt(np.abs(model_norm_residuals))
/opt/conda/lib/python3.6/site-packages/statsmodels/base/wrapper.py in __getattribute__(self, attr)
33 pass
34
---> 35 obj = getattr(results, attr)
36 data = results.model.data
37 how = self._wrap_attrs.get(attr)
AttributeError: 'GEEResults' object has no attribute 'get_influence'
有没有办法像在 R 中一样在 Python 中绘制所有 4 个诊断图?
如何使用 statsmodels
在 Python 中检索拟合模型结果的 Cook 统计数据?
最佳答案
广义估计方程 API 应该会给出与 R 的 GLM 模型估计不同的结果。要在 statsmodels 中获得类似的估计,您需要使用类似以下内容的内容:
import pandas as pd
import statsmodels.api as sm
# Read data generated in R using pandas or something similar
df = pd.read_csv(...) # file name goes here
# Add a column of ones for the intercept to create input X
X = np.column_stack( (np.ones((df.shape[0], 1)), df.X1) )
# Relabel dependent variable as y (standard notation)
y = df.X2
# Fit GLM in statsmodels using Poisson link function
sm.GLM(y, X, family = Poisson()).fit().summary()
编辑——这是关于如何在泊松回归中获得库克距离的其余答案。这是我根据 R 中生成的一些数据编写的脚本。我将我的值与 R 中使用 cooks.distance 函数计算的值进行了比较,并且值匹配。
from __future__ import division, print_function
import numpy as np
import pandas as pd
import statsmodels.api as sm
PATH = '/Users/robertmilletich/test_reg.csv'
def _weight_matrix(fitted_model):
"""Calculates weight matrix in Poisson regression
Parameters
----------
fitted_model : statsmodel object
Fitted Poisson model
Returns
-------
W : 2d array-like
Diagonal weight matrix in Poisson regression
"""
return np.diag(fitted_model.fittedvalues)
def _hessian(X, W):
"""Hessian matrix calculated as -X'*W*X
Parameters
----------
X : 2d array-like
Matrix of covariates
W : 2d array-like
Weight matrix
Returns
-------
hessian : 2d array-like
Hessian matrix
"""
return -np.dot(X.T, np.dot(W, X))
def _hat_matrix(X, W):
"""Calculate hat matrix = W^(1/2) * X * (X'*W*X)^(-1) * X'*W^(1/2)
Parameters
----------
X : 2d array-like
Matrix of covariates
W : 2d array-like
Diagonal weight matrix
Returns
-------
hat : 2d array-like
Hat matrix
"""
# W^(1/2)
Wsqrt = W**(0.5)
# (X'*W*X)^(-1)
XtWX = -_hessian(X = X, W = W)
XtWX_inv = np.linalg.inv(XtWX)
# W^(1/2)*X
WsqrtX = np.dot(Wsqrt, X)
# X'*W^(1/2)
XtWsqrt = np.dot(X.T, Wsqrt)
return np.dot(WsqrtX, np.dot(XtWX_inv, XtWsqrt))
def main():
# Load data and separate into X and y
df = pd.read_csv(PATH)
X = np.column_stack( (np.ones((df.shape[0], 1)), df.X1 ) )
y = df.X2
# Fit model
model = sm.GLM(y, X, family=sm.families.Poisson()).fit()
# Weight matrix
W = _weight_matrix(model)
# Hat matrix
H = _hat_matrix(X, W)
hii = np.diag(H) # Diagonal values of hat matrix
# Pearson residuals
r = model.resid_pearson
# Cook's distance (formula used by R = (res/(1 - hat))^2 * hat/(dispersion * p))
# Note: dispersion is 1 since we aren't modeling overdispersion
cooks_d = (r/(1 - hii))**2 * hii/(1*2)
if __name__ == "__main__":
main()
关于python - statsmodels 和 R 中的泊松回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47686227/
是否有 statsmodels API 可以从 statsmodels 时间序列模型中检索预测区间? 目前,我正在使用以下方法手动计算预测区间: 这是我的代码。首先,获取一些示例数据... ! pyt
我有:statsmodels 0.5.0(正式名称为 scikits.statsmodels) Pandas 0.12.0。(全部从源安装) 我收到这个错误: File "/home/userna
所有内容的格式都与 Statsmodels 网站上的一样,但是 Spyder 以某种方式返回了这个: TypeError: ztest_ind() got multiple values for ar
所有内容的格式都与 Statsmodels 网站上的一样,但是 Spyder 以某种方式返回了这个: TypeError: ztest_ind() got multiple values for ar
谁能给我解释一下 statsmodel.formula.api 中的 ols 和 statsmodel.api 中的 ols 之间的区别? 使用 ISLR 文本中的广告数据,我使用两者运行了一个 ol
我用python处理一个线性回归模型,json数据如下: {"Y":[1,2,3,4,5],"X":[[1,43,23],[2,3,43],[3,23,334],[4,43,23],[232,234,
我正在使用 Python 中的 statsmodels MixedLM 包估计一个混合线性模型。拟合模型后,我现在想进行预测,但很难理解“预测”方法。 statsmodels 文档 (http://w
使用状态模型的逻辑回归模型: log_reg = st.logit(formula = 'label ~ pregnant + glucose + bp + insulin + bmi + pedig
我有一个包含 3 列的数据框 ['X', 'Y', 'Z'] 我想研究一下 X 和 Y影响Z的分布。为此,我想使用 nadaraya watson 的非参数回归器。在 statsmodels 中有一个
我正在尝试使用 statsmodel 中的 statsmodels.discrete.conditional_models.ConditionalLogit 类。 在jupyter笔记本中导入模块时,
我安装 statsmodels: apt-get install python python-dev python-setuptools python-numpy python-scipy curl
import statsmodels.formula.api as sm import numpy as np import pandas url = "http://vincentarelbundo
我正在尝试在 x-y 数据的简单测试集上使用 statsmodels 中的稳健线性模型。然而,作为 model.params 的返回值,我只得到一个值。如何获得拟合的斜率和截距?最小示例(其中我试图从
我正在使用库statsmodels.tsa.stattools.grangercausalitytests来测试两个时间序列之间的相似性。我知道列表 a 和 b 都是合法列表,没有任何 None 或
以下代码使用 statsmodels 拟合了一个过度简化的广义线性模型 model = smf.glm('Y ~ 1', family=sm.families.NegativeBinomial(),
在Python库Statsmodels中,可以用print(results.summary())打印出回归结果,如何打印出超过的摘要一张表中的一个回归,以便更好地比较? 线性回归,代码取自 stats
我有一个 pandas DataFrame,其行包含多种类型的数据。我想使用 statsmodels.formula.api 根据这些数据拟合一个模型,然后做出一些预测。对于我的应用程序,我想一次预测
我正在尝试使用 statsmodels 中的 logit 模块对包含 bool 值(“默认”)目标变量和两个特征(“fico_interp”、“home_ownership_int”)的数据集执行逻辑
这个问题类似于confidence and prediction intervals with StatsModels但有一个额外的细微差别: 我的数据是异方差的,我想使用 statsmodels 提
我正在使用 Pandas 的混合物和 StatsModels绘制时间序列分解图。我关注了this answer但是当我调用 plot() 时,它似乎在绘制一个副本。 我的 DataFrame 看起来像
我是一名优秀的程序员,十分优秀!