不理解scipy.optimize.brute语法

2024-06-01 14:00:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我根本不懂scipy.optimize.brute的语法。如果我有一个列表,比如说[-1, 0, 1],和一个单变量函数x**2,我如何使它最小化?我读了the documentation,不知道该通过什么。元组不起作用,列表也不起作用,我不知道“切片对象”是什么,也不知道为什么要将它传递给两个切片对象

MWE:

import scipy.optimize as spopt

def f(x):
    return x**2

print(spopt.brute(f, ([-1, 0, 1])))

给我TypeError: object of type 'int' has no len()


Tags: the对象函数import列表documentationas语法
1条回答
网友
1楼 · 发布于 2024-06-01 14:00:56

^{}最小化给定范围内的函数。
错误依赖于传递ranges参数的方式。如文件所述:

Each component of the ranges tuple must be either a “slice object” or a range tuple of the form (low, high).

这里有一个例子

>>> res = spopt.brute(func=f, ranges=(slice(-1,2,1),), full_output=True)
>>> res
(array([ 0.]), 0.0, array([-1,  0,  1]), array([1, 0, 1]))
>>> res[0]
array([ 0.]) # global minimum
>>> res[1]
0.0 # function value at global minimum

相关问题 更多 >