简体   繁体   English

如何在Python中调用scipy.optimize.fmin_cg(func)的函数

[英]How to call function for scipy.optimize.fmin_cg(func) in Python

I will simply explain the problem in short. 我将简单地解释一下这个问题。 This problem is exactly similar as shown in scipy.doc . 此问题与scipy.doc中显示的完全相似。 The problem is on error occurance as float argument required, not numpy.ndarray 问题在于错误发生需要float参数,而不是numpy.ndarray

What I have: 我有的:

  • Function: y = s*z^t 功能: y = s * z ^ t

Variable length/dimensions 可变长度/尺寸

  • t - 1...m, t - 1 ... m,
  • s - 1...m and 1...n. s - 1 ... m和1 ... n。 So, m is row number, n - col number. 所以,m是行号,n - 列号。
  • z - 1...n. z - 1 ... n。
  • y - this can be y 1 , y[2], y[3],..., y[m], y - 这可以是y 1 ,y [2],y [3],...,y [m],
  • T - s[m,n] matrix T - s [m,n]矩阵

Like this : 像这样

  1. y[1] = s[1][1]*z[1]^t[1]+s[1][2]*z[2]^t[1]+...s[1][n]*z[n]^t[1])

  2. y[2] = s[2][1]*z[1]^t[2]+s[2][2]*z[2]^t[2]+...s[2][n]*z[n]^t[2])

    ... ...

  3. y[m] = s[m][1]*z[1]^t[m]+s[m][2]*z[2]^t[2]+...s[m][n]*z[n]^t[m])

Problem: Error occured. 问题:发生错误。

Optimization terminated successfully.

Traceback (most recent call last):
    solution = optimize.fmin_cg(func, z, fprime=gradf, args=args)
  File "C:\Python27\lib\site-packages\scipy\optimize\optimize.py", line 952, in fmin_cg
    res = _minimize_cg(f, x0, args, fprime, callback=callback, **opts)
  File "C:\Python27\lib\site-packages\scipy\optimize\optimize.py", line 1072, in _minimize_cg
    print "         Current function value: %f" % fval
TypeError: float argument required, not numpy.ndarray

Here is the code 这是代码

import numpy as np
import scipy as sp
import scipy.optimize as optimize

def func(z, *args):
    y,T,t = args[0]
    return y - counter(T,z,t)

def counter(T, z, t):
    rows,cols = np.shape(T)
    res = np.zeros(rows)
    for i,row_val in enumerate(T):
        res[i] = np.dot(row_val, z**t[i])
    return res


def gradf(z, *args):
    y,T,t = args[0]
    return np.dot(t,counter(T,z,t-1))

def main():
    # Inputs
    N = 30
    M = 20
    z0 = np.zeros(N) # initial guess
    y = 30*np.random.random(M)
    T = 10*np.random.random((M,N))
    t = 5*np.random.random(M)
    args = [y, T, t]

    solution = optimize.fmin_cg(func, z0, fprime=gradf, args=args)
    print 'solution: ', solution

if __name__ == '__main__':
    main()

I also tried to find similar examples but could not find something very similar. 我也试图找到类似的例子但找不到相似的东西。 Here is the code for your consideration. 以下是供您考虑的代码。 Thanks in advance. 提前致谢。

The root of your problem is that fmin_cg expects the function to return a single scalar value for the misfit instead of an array. 您的问题的根源是fmin_cg期望函数返回fmin_cg而不是数组的单个标量值。

Basically, you want something vaguely similar to: 基本上,你想要的东西模糊地类似于:

def func(z, y, T, t):
    return np.linalg.norm(y - counter(T,z,t))

I'm using np.linalg.norm here because there's no builtin function in numpy for the root-mean-square. 我在这里使用np.linalg.norm ,因为在numpy中没有用于均方根的内置函数。 The actual RMS would be norm(x) / sqrt(x.size) , but for minimization the constant multiplier doesn't make any difference. 实际RMS将是norm(x) / sqrt(x.size) ,但是对于最小化,常数乘数不会产生任何差异。

There are also other minor problems in your code (eg args[0] is going to be a single item. You want y, T, t = args or better yet, just func(z, y, T, t) ). 您的代码中还存在其他一些小问题(例如, args[0]将成为单个项目。您希望y, T, t = args或更好,只需func(z, y, T, t) )。 Your gradient function doesn't make any sense to me, but it's optional regardless. 你的渐变函数对我没有任何意义,但无论如何它都是可选的。 Also, there's no way the solution can produce reasonable values at the moment, as you're testing it against pure noise. 此外,解决方案目前无法产生合理的值,因为您正在测试纯噪声。 I assume those are just meant to be placeholder values, though. 我认为这些只是意味着占位符值。

However, you have a larger problem. 但是,你有一个更大的问题。 You're trying to minimize in 30-dimensional space. 你试图在30维空间中最小化。 Most non-linear solvers aren't going to work well with that high of a dimensionality. 大多数非线性求解器不能很好地处理那么高的维数。 It may work fine, but you're very likely to run into problems. 它可能工作正常,但你很可能遇到问题。

All that having been said, you may find it more intuitive to use the scipy.optimize.curve_fit interface rather than using the others, if you're okay with LM instead of CG (they're fairly similar methods). 所有这一切,你可能会发现使用scipy.optimize.curve_fit界面而不是使用其他界面更直观,如果你对LM而不是CG(它们是相当类似的方法)没问题。


One final thing: You're trying to solve for 30 model parameters with 20 observations. 最后一件事:你试图通过20次观察来解决30个模型参数。 This is an underdetermined problem. 这是一个未确定的问题。 This problem doesn't have a unique solution. 此问题没有唯一的解决方案。 You're going to need to apply some a-priori knowledge to get a reasonable answer. 您将需要应用一些先验知识来获得合理的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM