我不是河畔e你想要做什么
func(x + t*grad(x, A, b, c), A, b, c)
什么是t
?
在任何情况下,你的fmin_cg
调用不正确 - 的fmin_cg
签名
fmin_cg(f, x0, fprime=None, args=(), ...)
的第一个参数必须是你的目标函数,func
,第二需求是你最初的猜测x
,第三个(可选)参数是您的渐变函数grad
,第四个是附加参数的集合f
和fprime
(不包括x
)。
的调用应该是这样的:
scipy.optimize.fmin_cg(func, x, fprime=grad, args=(A, b, c))
然而,这仍然不会因为你的阵列尺寸的问题的工作:
<ipython-input-49-bf5fa71345fe> in grad(x, A, b, c)
1 def grad(x, A, b, c):
----> 2 gradient = A * (1.0/(b - A.transpose()*x)) + c
3 return gradient
4
/home/alistair/.venvs/core/local/lib/python2.7/site-packages/numpy/matrixlib/defmatrix.pyc in __mul__(self, other)
341 if isinstance(other, (N.ndarray, list, tuple)) :
342 # This promotes 1-D vectors to row vectors
--> 343 return N.dot(self, asmatrix(other))
344 if isscalar(other) or not hasattr(other, '__rmul__') :
345 return N.dot(self, other)
ValueError: shapes (500,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
要弄清楚这是为什么发生,我们可以在grad
设置一个断点:
import pdb
def grad(x, A, b, c):
pdb.set_trace()
gradient = A * (1.0/(b - A.transpose()*x)) + c
return gradient
在第一次调用grad
,我们看到:
(Pdb) type(x)
<type 'numpy.ndarray'>
(Pdb) !x.shape
(100,)
内的某处fmin_cg
,x
正在从(100, 1)
np.matrix
转换为(100,)
1D np.ndarray
。对于np.ndarray
,运算符执行元素乘法而不是矩阵乘法,这将失败,因为x
和A.transpose()
具有不兼容的维度。
基本上你是对的事实,np.matrix
尚未完全通过numpy的和SciPy的许多功能,包括预期的np.ndarray
支持的跑起来。我强烈建议您从使用np.matrix
切换到np.ndarray
- 使用np.matrix
为officially discouraged,并且在不久的将来可能会被弃用。
你grad
功能可以改写为:
def grad(x, A, b, c):
gradient = A.dot(1.0/(b - A.T.dot(x))) + c
return gradient
...和你的初始参数为:
np.random.seed(1234)
m = 500 #500
n = 100 #100
A = np.random.randint(low=-10, high=1, size=(n, m))
b = np.random.randint(low=500, high=1000, size=m)
c = np.random.randint(low=0.1, high=2, size=n)
x = np.random.randint(low=1, high=10, size=n)
...现在你到fmin_cg
调用应该工作:
res = scipy.optimize.fmin_cg(func, x, fprime=grad, args=(A, b, c))
由于您在函数中使用'np.dot',因此不要使用'np.asmatrix'使事情复杂化。坚持常规阵列。如果需要添加一个维度(使用'newaxis','reshape'或'atleast_2d')。 – hpaulj