【问题标题】:Invalid number of arguments during code refactoring scipy SLSQP代码重构 scipy SLSQP 期间的参数数量无效
【发布时间】:2023-04-10 18:33:01
【问题描述】:

我正在尝试使用 scipy.optimize.minimize. 优化目标函数

最初,我一直收到错误

TypeError: numpy boolean subtract, the - operator, is deprecated, use the bitwise_xor, the ^ operator, or the logical_xor function instead.

在寻找解决方案后,我发现我的scipy\optimize\slsqp.py 文件中需要进行代码重构。我把-操作符改成了np.subtract(),如下图,

jac[i] = (func(*((x0+dx,)+args)) - f0)/epsilon # This was the error line

jac[i] = np.subtract((func(*((x0+dx,)+args)), f0))/epsilon # which I changed to this

但现在我不断收到错误消息, ValueError: invalid number of arguments 在同一行

我不明白,因为我已经尝试使用示例参数 np.subtract,它似乎工作正常。

任何帮助将不胜感激。

【问题讨论】:

  • 如果您在指定的行中得到TypeError,这似乎意味着您的目标函数func 正在返回一个类型为bool 的值。您是否检查过 func 确实返回浮点值,正如 SciPy 中的最小化器所期望的那样?

标签: python numpy scipy-optimize scipy-optimize-minimize


【解决方案1】:

使用布尔 dtype 数组:

In [131]: x = np.ones(4, bool)

你的第一个错误:

In [132]: x-x
Traceback (most recent call last):
  File "<ipython-input-132-966d70d4047a>", line 1, in <module>
    x-x
TypeError: numpy boolean subtract, the `-` operator, is not supported, use the bitwise_xor, the `^` operator, or the logical_xor function instead.

为什么funcf0 是布尔值?

至于你的第二个错误,你有多余的():

In [133]: np.subtract((x,x))
Traceback (most recent call last):
  File "<ipython-input-133-d710885b85a3>", line 1, in <module>
    np.subtract((x,x))
ValueError: invalid number of arguments

使用正确的参数 (2),您仍然会遇到布尔错误:

In [134]: np.subtract(x,x)
Traceback (most recent call last):
  File "<ipython-input-134-76169c24bdd5>", line 1, in <module>
    np.subtract(x,x)
TypeError: numpy boolean subtract, the `-` operator, is not supported, use the bitwise_xor, the `^` operator, or the logical_xor function instead.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 2020-06-04
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    相关资源
    最近更新 更多