Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

python - iterating functions definitions, based on a parent function

I am trying to write some code to perform a statistical test called model-reduction. Basically what I want to know is whether each variable in my function makes a meaningful contribution (i.e. significantly explains variance). Say for example my original fit-function looks like this:

full_model(x, a, b, c, d):
    return a + b*x + c*x**3 + sin(d*x)

I want to compare reduced forms of this model. The once I need to check are:

reduced = lambda x, b, c, d: full_model(x, 0, b, c, d)
reduced = lambda x, a, c, d: full_model(x, a, 0, c, d)
reduced = lambda x, a, b, d: full_model(x, a, b, 0, d)
reduced = lambda x, a, b, c: full_model(x, a, b, c, 0)

For each case, I run some sort of test that I don't go into detail:

compare_models(full_model, reduced, x, y)

In reality, my fit function has more parameters, and I want test even further reduced functions. The code will be really messy if I have to explicitly define all possible models. Is there any way to define the reduced function in a for-loop? And is there any existing python module that can achieve what I want to do?

question from:https://stackoverflow.com/questions/65916938/iterating-functions-definitions-based-on-a-parent-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would harness functools.partial for that following way, consider following simplified example:

import functools
def sum3(x, y, z):
    return x+y+z
args = ["x", "y", "z"]
red_dict = {}
for arg in args:
    red_dict[arg] = functools.partial(sum3, **{arg: 0})
print(red_dict["x"](y=10,z=10))
print(red_dict["y"](x=10,z=10))
print(red_dict["z"](x=10,y=10))

Output:

20
20
20

Explanation: args is list of args names you want to zero, in for-loop I use argument unpacking (**) to fix selected argument value to zero, then I store result in red_dict. Use loop is equivalent to doing:

red_dict["x"] = functools.partial(sum3, x=0)
red_dict["y"] = functools.partial(sum3, y=0)
red_dict["z"] = functools.partial(sum3, z=0)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...