當使用scipy.optimize
的fmin
我得到一個錯誤,我不明白:SciPy的優化FMIN ValueError異常:設置一個數組元素與序列
ValueError: setting an array element with a sequence.
這裏有一個簡單的誤差平方的例子來演示:
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.
我會很感激任何幫助來解釋我哪裏出錯了。
您正在爲成本函數返回一個數組,而'fmin'只需要一個值。返回'J [0,0]'或者重寫成本函數爲'J = 1 /(2 * m)* np.sum(error ** 2)' – 2012-03-20 00:43:23