Python:将参数传递给函数

标签 python dlib

我正在使用dlibfind_min_global函数,这是一种优化算法,有助于找到最小化函数输出的值。例如

import dlib
def holder_table(x0,x1):
    return -abs(sin(x0)*cos(x1)*exp(abs(1-sqrt(x0*x0+x1*x1)/pi)))

x,y = dlib.find_min_global(holder_table, 
                           [-10,-10],  # Lower bound constraints on x0 and x1 respectively
                           [10,10],    # Upper bound constraints on x0 and x1 respectively
                           80)         # The number of times find_min_global() will call holder_table()

此处,holder_table 函数返回针对 x0x1 的不同值需要最小化的值。

此处,holder_table 函数仅接受需要优化的值,即 x0x1。但我想要与 dlib 函数一起使用的函数需要的不仅仅是 x0 和 x1。函数定义如下

def holder_table(a,b,x0,x1):
    return -abs(sin(b*x0/a)*cos(x1)*exp(abs(1-sqrt(x0*x0+x1*x1)/pi)))

a、b不固定,是另一个函数的输出。现在,我可以直接调用 holder_table 内返回 a, b 的函数,但我不想最终重新计算它们,因为每次 holder_table code> 被调用 a, b 会被重新计算,这个过程很耗时。

如何将 a, b 传递给 holder_table 函数?

最佳答案

您的问题不是 100% 清楚,但看起来您想要 partial application 。在 Python 中,这可以使用专用的 functools.partial 对象来完成,或者非常简单地使用 closure 来完成。 (使用内部函数或 lambda)

def holder_table(a,b,x0,x1):
    return -abs(sin(b*x0/a)*cos(x1)*exp(abs(1-sqrt(x0*x0+x1*x1)/pi)))


def main():
    a, b = some_heavy_function(...)
    holder_table_partial = lambda ax, ay: holder_table(a, b, ax, ay)
    x, y = dlib.find_min_global(
        holder_table_partial, [-10,-10], [10,10], 80
        )    

关于Python:将参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50835068/

相关文章:

python - OpenCV "The function is not implemented. Rebuild the library with Windows"

python - 尝试在 pandas 数据框中跨行插值时出错

python - 如何使用 win32com 模块填充 Excel 中的列表

python - 有没有关于 python-purple 的例子?

c++ - 函数参数上的 "attempting to reference a deleted function"

c++ - 在Qt项目中包含dlib

python - 在具有不同索引的Python中添加两个数据 Pandas 系列

face-detection - 如何将34个面部标志点转换为68个点?

javascript - 用于 JavaScript 的 Dlib

c++ - 找不到Dlib “' dlib/image_processing/frontal_face_detector.h'文件” Xcode C++控制台应用程序