【发布时间】:2015-06-20 00:12:12
【问题描述】:
我有一个数据框 df,其中包含以下字段:weight、length 和 animal。前两个是连续变量,而animal 是一个分类变量,其值为cat、dog 和snake。
我想估计体重和长度之间的关系,但这需要以动物的类型为条件,因此我将长度变量与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
此代码可能看起来有点矫枉过正,但在我的实际用例中,我有一个连续变量与两个单独的分类变量交互,每个分类变量都有大量类别(以及模型中我需要忽略的其他术语)用于这些目的)。
【问题讨论】:
-
对于两个参数之和的情况,标准误差公式看起来是正确的。但是,我认为您没有在与
slope计算相对应的标准错误计算中选择params。此外,除了两个参数的总和之外,这种计算不会轻易推广到其他情况。
标签: python pandas statsmodels