简体   繁体   中英

Trying to find a minimum of g(x) function and the x value at this minimum

I am trying to find a minimum of a created function g(alpha) and what is more important, to find value of the alpha at this minimum, or close to the minimum.

The code I use is the following: it creates function f , vectors D , avec and grad and uses it for creation of function g(alpha) , minimum of which I want to find, together with the alpha value.

The problem is that after applying solve from sympy library I don't get numerical number of alpha . Instead of I get the following error:

TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'

The code:

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)

I know that this solution may not be the best for this problem. I'm new in Python and if you have any better suggestions how to find alpha here, please tell me.

I think you are really confusing what sympy does. sympy is a module to solve and print analytical equations. You do not need to use that package at all for this task.

You actually do find the minimum of g here. You store this result in oo .

So basically, delete the last 2 lines starting alfa = ... and slv = ... and then just put print(oo) . oo is the value you are looking for, the value of alpha which minimises the function g

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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