【问题标题】:Recurrent problem using scipy.optimize.fmin使用 scipy.optimize.fmin 经常出现的问题
【发布时间】:2020-06-02 23:30:09
【问题描述】:

我在将以下代码从 MATLAB 转换为 Python 时遇到了一些问题:

matlab代码sn-p:

   x=M_test %M_test is a 1x3 array that holds the adjustment points for the function
   y=R_test %R_test is also a 1x3 array
   >> M_test=[0.513,7.521,13.781]
   >> R_test=[2.39,3.77,6.86]

   expo3= @(b,x) b(1).*(exp(-(b(2)./x).^b(3)));
   NRCF_expo3= @(b) norm(y-expo3(b,x));
   B0_expo3=[fcm28;1;1];
   B_expo3=fminsearch(NRCF_expo3,B0_expo3);
   Data_raw.fcm_expo3=(expo3(B_expo3,Data_raw.M));

翻译后的(python)代码:

   expo3=lambda x,M_test: x[0]*(1-exp(-1*(x[1]/M_test)**x[2]))
   NRCF_expo3=lambda R_test,x,M_test: np.linalg.norm(R_test-expo3,ax=1)
   B_expo3=scipy.optimize.fmin(func=NRCF_expo3,x0=[fcm28,1,1],args=(x,))

为了清楚起见,对象函数“expo3”想要通过 M_test 定义的调整点。 'NRCF_expo3'是想要最小化的函数,基本上就是R_test和绘制的指数函数的误差。

当我运行代码时,我收到以下错误消息:

B_expo3=scipy.optimize.fmin(func=NRCF_expo3,x0=[fcm28,1,1]),args=(x,))
NameError: name 'x' is not defined

我已经阅读了很多类似的问题。

如果我从优化函数中删除“args”,numpy/scipy analog of matlab's fminsearch 似乎表明没有必要,我会收到错误:

line 327, in function_wrapper
return function(*(wrapper_args+args))
TypeError: <lambda>() missing 2 required positional arguments: 'x' and 'M_test'

我尝试了很多其他修改,例如 Using scipy to minimize a function that also takes non variational parametersOpen source examples 中的示例,但对我没有任何效果。

我希望这可能很明显,但我对 Python 很陌生,我觉得我正在大海捞针。 我没看到什么?

任何帮助将不胜感激。如果有必要,我还可以提供更多代码。

【问题讨论】:

    标签: python matlab scipy-optimize fminsearch


    【解决方案1】:

    我认为您不应该在代码中使用 lambda,而是使用您的三个参数创建一个目标函数(请参阅 PEP8)。你的帖子中有很多缺失的信息,但据我所知,你想要这样的东西:

    from scipy.optimize import fmin
    
    # Define parameters
    
    M_TEST = np.array([0.513, 7.521, 13.781])    
    X_ARR = np.array([2.39,3.77,6.86])
    X0 = np.array([10, 1, 1])  # whatever your variable fcm28 is
    
    def nrcf_exp3(r_test, m_test, x): 
        expo3 = x[0] * (1 - np.exp(-(x[1] / m_test) ** x[2])) 
        return np.linalg.norm(r_test - expo3)
    
    fmin(nrcf_exp3, X0, args=(M_TEST, X_ARR))
    

    【讨论】:

    • 太棒了。非常感谢。为了在同一页面上,您正在互换使用大写字母和非大写字母?还是您故意将 m_test 和 M_TEST 称为不同?
    • 这又是因为PEP8 命名风格。这只是提高代码可读性的指南。它不会影响代码的执行方式。如果您是 Python 新手,Flake8Pylint 等工具可以帮助您掌握这种编码风格习惯。干杯伙伴。
    猜你喜欢
    • 1970-01-01
    • 2020-10-04
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    相关资源
    最近更新 更多