在函数内调用patsy时出现命名空间问题 [英] Namespace issues when calling patsy within a function

查看:91
本文介绍了在函数内调用patsy时出现命名空间问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为statsmodels公式API写一个包装器(这是一个简化版本,该函数的作用还不止于此):

I am attempting to write a wrapper for the statsmodels formula API (this is a simplified version, the function does more than this):

import statsmodels.formula.api as smf

def wrapper(formula, data, **kwargs):
    return smf.logit(formula, data).fit(**kwargs)

如果我将此功能提供给用户,然后用户尝试定义自己的功能:

If I give this function to a user, who then attempts to define his/her own function:

def square(x):
    return x**2

model = wrapper('y ~ x + square(x)', data=df)

它们将收到一个NameError,因为patsy模块正在wrapper的命名空间中查找功能square.有没有一种安全的Python方式可以处理这种情况,而无需先验地知道函数的名称是什么或将需要多少个函数?

they will receive a NameError because the patsy module is looking in the namespace of wrapper for the function square. Is there a safe, Pythonic way to handle this situation without knowing a priori what the function names are or how many functions will be needed?

仅供参考:这适用于Python 3.4.3.

FYI: This is for Python 3.4.3.

推荐答案

statsmodels使用patsy包来解析公式并创建设计矩阵. patsy允许用户函数作为公式的一部分,并在用户名称空间或环境中获取或评估用户函数.

statsmodels uses the patsy package to parse the formulas and create the design matrix. patsy allows user functions as part of formulas and obtains or evaluates the user function in the user namespace or environment.

作为参考,请参见 http://patsy.readthedocs.org/中的eval_env关键字zh/latest/API-reference.html

from_formula是用于实现patsy的公式接口的模型方法.它使用eval_env向patsy提供必要的信息,默认情况下,patsy是用户的呼叫环境.用户可以使用相应的关键字参数将其覆盖.

from_formula is the method of models that implements the formula interface to patsy. It use eval_env to provide the necessary information to patsy, which by default is the calling environment of the user. This can be overwritten by the user with the corresponding keyword argument.

定义eval_env的最简单方法是使用整数,该整数指示patsy应该使用的堆栈级别. from_formula对其进行递增以考虑statsmodels方法中的附加级别.

The simplest way to define the eval_env is as an integer that indicates the stacklevel that patsy should use. from_formula is incrementing it to take account of the additional level in the statsmodels methods.

根据注释,eval_env = 2将使用创建模型的级别中的下一个更高级别,例如与model = smf.logit(..., eval_env=2).

According to the comments, eval_env = 2 will use the next higher level from the level that creates the model, e.g. with model = smf.logit(..., eval_env=2).

这将创建模型,调用patsy并创建设计矩阵,model.fit()将对其进行估计并返回结果实例.

This creates the model, calls patsy and creates the design matrix, model.fit() will estimate it and returns the results instance.

这篇关于在函数内调用patsy时出现命名空间问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆