简体   繁体   English

SciPy optimize.fmin ValueError:零大小数组到减少操作最大值,没有标识

[英]SciPy optimize.fmin ValueError: zero-size array to reduction operation maximum which has no identity

UPDATE2: A better title (now that I understand the problem) would be: What is the proper syntax for input in scipy optimize.fmin? UPDATE2:一个更好的标题(现在我理解这个问题)将是:scipy optimize.fmin中输入的正确语法是什么?

UPDATE: runnable code was requested, so the function definitions have been replaced with runnable code. 更新:请求了可运行代码,因此函数定义已替换为可运行代码。 Sample input data has been hard-encoded as the numpy array 'data'. 样本输入数据已被硬编码为numpy数组'data'。

I'm trying to optimize a function with scipy, but am really stuck, and must beg for help. 我正在尝试用scipy来优化一个函数,但我确实陷入困境,必须求助。 A zero-length array is being passed to a method in the optimizer, and I cannot understand why, nor how to overcome this problem. 一个零长度数组被传递给优化器中的方法,我无法理解为什么,也不知道如何克服这个问题。

A brief outline of what this code is trying to do: 此代码尝试执行的操作的简要概述:

  • Given data set "data" composed of individual observations "r" 给定数据集“数据”由个人观察“r”组成
  • Estimate a value of parameter "m" which is most likely to have given rise to "data" 估计最有可能产生“数据”的参数“m”的值
    • For a given m, calculate the probability p(r|m) for observing each "r" in "data" 对于给定的m,计算观察“数据”中每个“r”的概率p(r | m)
    • For a given m, calculate the probability P(m|data) that "m" generated the data. 对于给定的m,计算“m”生成数据的概率P(m | data)。
  • Define a helper function for use with optimize.fmin. 定义一个帮助函数以与optimize.fmin一起使用。
  • Use SciPy optimize.fmin to determine the m for which helper(m|data) is maximized. 使用SciPy optimize.fmin确定帮助器(m | data)最大化的m。

The error I get when I run this code is: ValueError: zero-size array to reduction operation maximum which has no identity 我运行此代码时得到的错误是:ValueError:零大小数组到减少操作最大值没有标识

Here is a runnable snippet of code which generates the error on my machine. 这是一个可运行的代码片段,它在我的机器上生成错误。

#!/usr/bin/env python2.7

import numpy as np
from scipy import optimize

def p_of_r(m, r): ## this calculates p(r|m) for each datum r
    r_range = np.arange(0, r+1, 1, dtype='int')
    p_r = []
    p_r = np.array([0.0 for a in r_range])
    for x in r_range:
        if x == 0:
            p_r[x] = np.exp(-1 * m)
        else:
            total = 0.0
            for y in np.arange(0, x, 1, dtype='int'):
                current = ( p_r[y] ) / (x - y  + 1)
                total = current + total
            p_r[x] = ( m / x ) * total
    return p_r

def likelihood_function(m, *data): # calculates P(m|data) using entire data set
    p_r = p_of_r(m, np.ma.max(data))
    p_r_m = np.array([p_r[y] for y in data])
    bigP = np.prod(p_r_m)
    return bigP

def main():
    data = np.array( [10, 10, 7, 19, 9, 23, 26, 7, 164, 16 ] )
    median_r = np.median(data)
    def Drake(m):
        return median_r / m - np.log(m)
    m_initial = optimize.broyden1(Drake, 1) 
    def helper(x, *args):
        helper_value = -1 * likelihood_function(x, *args)
        return helper_value 

    # here is the actual optimize.fmin    
    fmin_result = optimize.fmin(helper, x0=[m_initial], args=data)
    print fmin_result

#    for i in np.arange(0.0, 25.0, 0.1):
#        print i, helper(i, data)
if __name__ == "__main__" : main()

The error itself: ValueError: zero-size array to reduction operation maximum which has no identity 错误本身:ValueError:零大小数组到减少操作最大值,没有标识

The traceback is provided below. 回溯如下所示。

ValueError                                Traceback (most recent call last)
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/utils/py3compat.pyc in execfile(fname, *where)
    176             else:
    177                 filename = fname
--> 178             __builtin__.execfile(filename, *where)

/Users/deyler/bin/MSS-likelihood-minimal.py in <module>()
     43     print fmin_result
     44 
---> 45 if __name__ == "__main__" : main()

/Users/deyler/bin/MSS-likelihood-minimal.py in main()
     40 
     41 
---> 42     fmin_result = optimize.fmin(helper, x0=[m_initial], args=data)
     43     print fmin_result
     44 

/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/optimize/optimize.pyc in fmin(func, x0, args, xtol, ftol, maxiter, maxfun, full_output, disp, retall, callback)
    371             'return_all': retall}
    372 
--> 373     res = _minimize_neldermead(func, x0, args, callback=callback, **opts)
    374     if full_output:
    375         retlist = res['x'], res['fun'], res['nit'], res['nfev'], res['status']

/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/optimize/optimize.pyc in _minimize_neldermead(func, x0, args, callback, xtol, ftol, maxiter, maxfev, disp, return_all, **unknown_options)
    436     if retall:
    437         allvecs = [sim[0]]
--> 438     fsim[0] = func(x0)
    439     nonzdelt = 0.05
    440     zdelt = 0.00025

/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/optimize/optimize.pyc in function_wrapper(*wrapper_args)
    279     def function_wrapper(*wrapper_args):
    280         ncalls[0] += 1
--> 281         return function(*(wrapper_args + args))
    282 
    283     return ncalls, function_wrapper

/Users/deyler/bin/MSS-likelihood-minimal.py in helper(x, *args)
     33     m_initial = optimize.broyden1(Drake, 1)
     34     def helper(x, *args):
---> 35         helper_value = -1 * likelihood_function(x, *args)
     36         return helper_value
     37 

/Users/deyler/bin/MSS-likelihood-minimal.py in likelihood_function(m, *data)
     21 
     22 def likelihood_function(m, *data):
---> 23     p_r = p_of_r(m, np.ma.max(data))
     24     p_r_m = np.array([p_r[y] for y in data])
     25     bigP = np.prod(p_r_m)

/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/ma/core.pyc in max(obj, axis, out, fill_value)
   5899         # If obj doesn't have a max method,
   5900         # ...or if the method doesn't accept a fill_value argument
-> 5901         return asanyarray(obj).max(axis=axis, fill_value=fill_value, out=out)
   5902 max.__doc__ = MaskedArray.max.__doc__
   5903 

/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/ma/core.pyc in max(self, axis, out, fill_value)
   5159         # No explicit output
   5160         if out is None:
-> 5161             result = self.filled(fill_value).max(axis=axis, out=out).view(type(self))
   5162             if result.ndim:
   5163                 # Set the mask

/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/_methods.pyc in _amax(a, axis, out, keepdims)
      8 def _amax(a, axis=None, out=None, keepdims=False):
      9     return um.maximum.reduce(a, axis=axis,
---> 10                             out=out, keepdims=keepdims)
     11 
     12 def _amin(a, axis=None, out=None, keepdims=False):

ValueError: zero-size array to reduction operation maximum which has no identity

Correct fmin syntax is: 正确的fmin语法是:

args: tuple, optional args:元组,可选

  Extra arguments passed to func, ie f(x,*args). 
fmin_result = optimize.fmin(helper, x0=[m_initial], args=(data,))

Is next result expected? 预计下一个结果吗?

Optimization terminated successfully.
         Current function value: -0.000000
         Iterations: 16
         Function evaluations: 32
[ 5.53610656]

暂无
暂无

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

相关问题 如何修复&#39;ValueError:零尺寸数组到没有身份的归约运算fmin&#39; - How to fix 'ValueError: zero-size array to reduction operation fmin which has no identity' 零大小数组到没有标识的最大归约操作 - zero-size array to reduction operation maximum which has no identity 具有Statsmodel ValueError的多个OLS回归:零大小数组到减少操作最大值,没有标识 - Multiple OLS Regression with Statsmodel ValueError: zero-size array to reduction operation maximum which has no identity 如何将 np.max 用于没有 ValueError 的空 numpy 数组:零大小数组到没有标识的缩减操作最大值 - how to use np.max for empty numpy array without ValueError: zero-size array to reduction operation maximum which has no identity 为什么我会得到以及如何解决 ValueError: zero-size array to reduction operation maximum which has no identity - Why am I getting and how to solve ValueError: zero-size array to reduction operation maximum which has no identity ValueError:零大小数组到没有标识的最小化操作 - ValueError: zero-size array to reduction operation minimum which has no identity Seaborn ValueError:零大小数组到减少操作最小值,没有标识 - Seaborn ValueError: zero-size array to reduction operation minimum which has no identity 零大小数组到最大归约操作,对于多输出 U-net 没有标识 - zero-size array to reduction operation maximum which has no identity for multi output U-net 如何修复 keras pad_sequences 中的“零大小数组到没有标识的最大缩减操作” - How to fix "zero-size array to reduction operation maximum which has no identity" in keras pad_sequences OLS回归存储问题:零大小数组到归约操作最大值,没有身份 - OLS regression storing problem: zero-size array to reduction operation maximum which has no identity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM