繁体   English   中英

使用scipy.optimize最小化功能

[英]Minimising a function using scipy.optimize

在此处输入图片说明

我需要使用scipy最小化上述功能。

我的输入数据

np.random.seed(1234)
m = 500    #500
n = 100    #100
A = np.asmatrix(np.random.randint(low=-10,high=1,size=(n,m)))     
b = np.asmatrix(np.random.randint(low=500,high=1000,size=(m,1)))  
c = np.asmatrix(np.random.randint(low=0.1,high=2,size=(n,1)))
x = np.asmatrix(np.random.randint(low=1,high=10,size=(n,1)))

功能

我的功能和渐变:

def func(x, A, b, c):
    fx = np.dot(c.T, x) - np.sum(np.log10((b - np.dot(A.T, x))))
    return fx

def grad(x, A, b, c):
    gradient = A * (1.0/(b - A.transpose()*x)) + c
    return gradient

这就是我试图运行的

scipy.optimize.fmin_cg(func(x + t*grad(x, A, b, c),A, b, c), x, args=(A,b,c,x))

我不确定您要做什么

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 ,第四个参数是ffprime其他参数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内的fmin_cgx正在从(100, 1) np.matrix (100, 1) np.matrix转换为(100,) 1D np.ndarray 对于np.ndarray*运算符执行元素乘法而不是矩阵乘法,这将失败,因为xA.transpose()维数不兼容。


基本上你是对的事实,跑起来np.matrix没有完全通过numpy的和SciPy的许多功能,包括预期的支持np.ndarray 我强烈建议您从使用np.matrix切换到np.ndarray 正式建议不要使用np.matrix ,并且在不远的将来可能会不推荐使用。

您的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))

暂无
暂无

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

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