在scipy最小化期间​​打印当前评估的参数 [英] print currently evaluated params during scipy minimization

查看:107
本文介绍了在scipy最小化期间​​打印当前评估的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用scipy.optimize.minimize最小化Python中的函数,以确定四个不同的参数.

I am trying to minimize a function in Python using scipy.optimize.minimize, to determine four distinct parameters.

我想在优化算法的每个步骤中打印当前评估的参数,因此可以使用它们来使我的初始猜测更好.

I would like to print the currently evaluated params at each step of the optimisation algorithm, so I can use them to make my initial guess better.

我该怎么做?

推荐答案

使用callback关键字参数.

scipy.optimize.minimize可以采用关键字参数callback.这应该是一个接受当前参数向量作为输入的函数.每次迭代后都会调用此函数.

scipy.optimize.minimize can take a keyword argument callback. This should be a function that accepts, as input, the current vector of parameters. This function is called after every iteration.

例如,

from scipy.optimize import minimize

def objective_function(xs):
    """ Function to optimize. """
    x, y = xs
    return (x-1)**2 + (y-2)**4

def print_callback(xs):
    """
    Callback called after every iteration.

    xs is the estimated location of the optimum.
    """
    print xs

minimize(objective_function, x0 = (0., 0.), callback=print_callback)

通常,人们希望在回调的不同调用之间保留信息,例如迭代号.一种方法是使用闭包:

Often, one wants to retain information between different calls to the callback, such as, for instance, the iteration number. One way to do this is to use a closure:

def generate_print_callback():
    """
    Generate a callback that prints 

        iteration number | parameter values | objective function

    every tenth iteration.
    """
    saved_params = { "iteration_number" : 0 }
    def print_callback(xs):
        if saved_params["iteration_number"] % 10 == 0:
            print "{:3} | {} | {}".format(
                saved_params["iteration_number"], xs, objective_function(xs))
        saved_params["iteration_number"] += 1
    return print_callback

调用最小化函数:

minimize(objective_function, x0 = (0., 0.), callback=generate_print_callback())

这篇关于在scipy最小化期间​​打印当前评估的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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