[英]For a given function f, is it possible to find the value of x where f(x) is minimum (Python)?
[英]Trying to find a minimum of g(x) function and the x value at this minimum
我试图找到一个已创建函数g(alpha)的最小值,更重要的是,找到此最小值或接近最小值的alpha值。
我使用的代码如下:它创建函数f ,向量D , avec和grad ,并将其用于创建函数g(alpha) ,我想找到其中的最小值以及alpha值。
问题是在从sympy库中应用求解后 ,我没有得到alpha的数字。 而不是我得到以下错误:
TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'
编码:
import numpy as np
from scipy.optimize import fmin
from sympy import Symbol, solve
from scipy import interpolate
Emax = 10
bins = 200
x = np.linspace(1, Emax, num = Emax, dtype=np.int) #create grid of indexes
y = np.linspace(1, bins, num = bins, dtype=np.int)
z = np.random.rand(bins, Emax) # random matrix
f = interpolate.interp2d(x,y,z, kind='cubic') # make the matrix continious
D= np.zeros(bins)
D = 2*f(1.5, y) # create vector
avec = np.array([4.0, 16.0])
grad = np.array([1e-5,1e-5])
g= lambda alpha: np.sum(np.square(np.subtract(D, (avec[0]-alpha*grad[0])*f((avec[1]-
alpha*grad[1]),y))))
oo= fmin(g,(0.0))
alfa = Symbol("alfa")
slv= solve((np.sum(np.square(np.subtract(D, (avec[0]-alfa*grad[0])*f((avec[1]-
alfa*grad[1]),y)))) - oo), alfa)
我知道此解决方案可能不是解决此问题的最佳方法。 我是Python的新手,如果您对如何在此处找到alpha有更好的建议,请告诉我。
我认为您真的对sympy
工作感到困惑。 sympy
是解决和打印解析方程的模块。 您完全不需要为该任务使用该软件包。
您实际上确实在这里找到g
的最小值。 您将此结果存储在oo
。
因此,基本上,删除以alfa = ...
和slv = ...
开头的最后两行,然后仅放置print(oo)
。 oo
是您要寻找的值,即使函数g
最小化的alpha值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.