Statsmodels Poisson glm与R不同

时间:2014-02-14 16:52:12

标签: python r glm statsmodels poisson

我正在尝试根据R中提供的一些代码来拟合一些模型(空间交互模型)。我已经能够在python框架中使用statsmodel获得一些代码,但是其中一些不匹配一点都不我相信我对R和Python的代码应该给出相同的结果。有没有人看到任何差异?或者是否有一些根本性的差异可能会让事情失去意义? R代码是与教程中给出的数字匹配的原始代码(在此处找到:http://www.bartlett.ucl.ac.uk/casa/pdf/paper181)。

R示例代码:

library(mosaic)
Data = fetchData('http://dl.dropbox.com/u/8649795/AT_Austria.csv')
Model = glm(Data~Origin+Destination+Dij+offset(log(Offset)), family=poisson(link="log"), data = Data)
cor = cor(Data$Data, Model$fitted, method = "pearson", use = "complete")
rsquared = cor * cor
rsquared

R输出:

> Model = glm(Data~Origin+Destination+Dij+offset(log(Offset)), family=poisson(link="log"), data = Data)
Warning messages:
1: glm.fit: fitted rates numerically 0 occurred 
2: glm.fit: fitted rates numerically 0 occurred 
> cor = cor(Data$Data, Model$fitted, method = "pearson", use = "complete")
> rsquared = cor * cor
> rsquared
[1] 0.9753279

Python代码:

import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
import statsmodels.api as sm
from scipy.stats.stats import pearsonr

Data= pd.DataFrame(pd.read_csv('http://dl.dropbox.com/u/8649795/AT_Austria.csv'))
Model = smf.glm('Data~Origin+Destination+Dij', data=Data, offset=np.log(Data['Offset']), family=sm.families.Poisson(link=sm.families.links.log)).fit()

cor = pearsonr(doubleConstrained.fittedvalues, Data["Data"])[0]

print "R-squared for doubly-constrained model is: " + str(cor*cor)

Python输出:

R-squared for doubly-constrained model is: 0.104758481123

1 个答案:

答案 0 :(得分:3)

看起来GLM在statsmodels中存在收敛问题。也许在R中,但R只给出了这些警告。

Warning messages:
1: glm.fit: fitted rates numerically 0 occurred 
2: glm.fit: fitted rates numerically 0 occurred 

这可能意味着Logit / Probit上下文中的完美分离。我不得不考虑Poisson模型。

R正在做一个更好的,如果微妙的工作,告诉你你的装修可能有问题。例如,如果你看一下statsmodels中拟合的可能性,那就是-1.12e27。那应该是一个线索,有些东西已经关闭。

直接使用泊松模型(我总是喜欢GLM的最大可能性),我可以复制R结果(但我收到了收敛警告)。很明显,默认的newton-raphson解算器失败了,所以我使用了bfgs。

import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
import statsmodels.api as sm
from scipy.stats.stats import pearsonr

data= pd.DataFrame(pd.read_csv('http://dl.dropbox.com/u/8649795/AT_Austria.csv'))

mod = smf.poisson('Data~Origin+Destination+Dij', data=data, offset=np.log(data['Offset'])).fit(method='bfgs')

print mod.mle_retvals['converged']