【问题标题】:Python scipy optimize fmin from matlab fminsearch errorPython scipy从matlab fminsearch错误中优化fmin
【发布时间】:2014-04-18 01:56:44
【问题描述】:

我正在将此 matlab 函数句柄转换为 python 并在 python 中收到此错误(ValueError: setting an array element with a sequence.)。如果有明显的错误,我对python很抱歉。

在matlab中:

P = [1 1; 6 1; 6 5]
fh = @(x) sqrt(sum((ones(3,1)*x - P).^2, 2))
[x,fval] = fminsearch(@(x) max(fh(x)),[0 0])

在python中:

P = np.matrix([[1, 1],[ 6, 1],[ 6, 5]])
fh = lambda x:np.sqrt(sum(np.power((np.ones((3,1))*x - P),2),axis = 0))
xopt = scipy.optimize.fmin(func=fh,x0 = np.matrix([0, 0]))

该代码在 matlab 中有效,但在 python 中无效。

【问题讨论】:

    标签: python matlab


    【解决方案1】:

    在您的 matlab 代码中,fminsearch 正在最小化 fh(x)max。因此,在 Python 代码中,传递给 fminfunc 也应该是 fhmax

    import numpy as np
    from scipy import optimize
    
    P = np.array([[1, 1],[ 6, 1],[ 6, 5]])
    
    def fh(x):
        return np.max(np.sqrt(np.sum((x - P)**2, axis=1)))
    
    xopt = optimize.fmin(func=fh, x0=np.array([0, 0]))
    print(xopt)
    

    产量

    Optimization terminated successfully.
             Current function value: 3.201562
             Iterations: 117
             Function evaluations: 222
    [ 3.50007127  2.99991092]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-08
      • 1970-01-01
      • 1970-01-01
      • 2013-10-04
      • 1970-01-01
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      相关资源
      最近更新 更多