我有一个数据框df
与以下字段:weight
,length
和animal
。前2个是连续变量,而animal
是具有值cat
,dog
和snake
的分类变量。评估statsmodels的具体类别的斜率和误差ols fit
我想估计重量和长度之间的关系,但这需要以动物的类型为条件,所以我将长度变量与animal
分类变量相互作用。
model = ols(formula='weight ~ length * animal', data=df)
results = model.fit()
如何以编程方式提取重量和长度之间关系的斜率,例如,蛇?我了解如何手动执行此操作:将系数length
添加到系数animal[T.snake]:length
。但这有点繁琐和手动,并且需要我专门处理基本案例,所以我想自动提取这些信息。
此外,我想估计这个斜率的误差。我相信我理解如何通过结合标准误差和协方差(更准确地说,执行计算here)来计算这一点。但是这比上面更麻烦,我同样想知道是否有快捷方式来提取这些信息。
我的手动方法来计算这些如下。
编辑(2015年6月22日):我的原始代码似乎有一个错误,用于计算错误。 user333700的答案中计算的标准错误与我计算的不同,但我没有花时间去弄清楚为什么。
def get_contained_animal(animals, p):
# This relies on parameters of the form animal[T.snake]:length.
for a in animals:
if a in p:
return a
return None
animals = ['cat', 'dog', 'snake']
slopes = {}
errors = {}
for animal in animals:
slope = 0.
params = []
# If this param is related to the length variable and
# the animal in question, add it to the slope.
for param, val in results.params.iteritems():
ac = get_contained_animal(animals, param)
if (param == 'length' or
('length' in param and
ac is None or ac == animal)):
params.append(param)
slope += val
# Calculate the overall error by adding standard errors and
# covariances.
tot_err = 0.
for i, p1 in enumerate(params):
tot_err += results.bse[p1]*results.bse[p1]
for j, p2 in enumerate(params[i:]):
# add covariance of these parameters
tot_err += 2*results.cov_params()[p1][p2]
slopes[animal] = slope
errors[animal] = tot_err**0.5
此代码似乎有点小题大做,但在我的实际使用情况下,我有一个连续变量有两个单独的分类变量,每一个门类众多的相互作用(与模型中的其他条款沿我需要忽略这些目的)。
标准误差公式对于两个参数总和的情况看起来是正确的。但是,我认为在标准误差计算中不会选择与“斜率”计算相对应的'params'。另外,这个计算不会轻易地推广到其他情况,而不是两个参数的总和。 – user333700