本文介绍了Scipy优化fmin ValueError:设置一个带有序列的数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用scipy.optimizefmin时出现错误,我不明白:

When using scipy.optimize's fmin I'm getting an error I don't understand:

ValueError: setting an array element with a sequence.

这是一个简单的平方误差示例,用于演示:

Here's a simple squared error example to demonstrate:

import numpy as np
from scipy.optimize import fmin

def cost_function(theta, X, y):
    m = X.shape[0]
    error = X.dot(theta) - y
    J = 1/(2*m) * error.T.dot(error)
    return J

X = np.array([[1., 1.],
              [1., 2.],
              [1., 3.],
              [1., 4.]])

y = np.array([[2],[4],[6],[8]])
initial_theta = np.ones((X.shape[1], 1)) * 0.01

# test cost_function
print cost_function(initial_theta, X, y)
# [[ 14.800675]] seems okay...

# but then error here...
theta = fmin(cost_function, initial_theta, args=(X, y))

#Traceback (most recent call last):
#  File "C:\Users\me\test.py", line 21, in <module>
#    theta = fmin(cost_function, initial_theta, args=(X, y))
#  File "C:\Python27\lib\site-packages\scipy\optimize\optimize.py", line 278, in fmin
#    fsim[0] = func(x0)
#ValueError: setting an array element with a sequence.

如果能帮助我解释我要去哪里错了,我将不胜感激.

I'd be grateful for any help to explain where I'm going wrong.

推荐答案

原因是您赋予fmin的起点(initial_theta)不是1D数组,而是2D数组.因此,在第二次迭代中,fmin传递了一个1D数组(这就是它应该起作用的方式),结果变成了非标量.

The reason is that the starting point (initial_theta) you gave to fmin is not a 1D array but a 2D array. So on a second iteration fmin passes a 1D array (that's how it supposed to work) and the result becomes non-scalar.

因此,您应该重构成本函数,以将1d数组作为第一个参数.

So you should refactor your cost function to accept 1d arrays as a first argument.

最简单的更改是使代码正常工作,是先将initial_theta展平,然后传递给fmin,然后根据需要将cost_function中的theta整形为(X.shape [1],1).

The simplest change is to make the code working is to flatten the initial_theta before passing to fmin and reshape theta inside cost_function to (X.shape[1],1) if you like.

这篇关于Scipy优化fmin ValueError:设置一个带有序列的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-05 20:07