Python illustrating Downhill simplex method for mi

From , 5 Years ago, written in Python, viewed 207 times.
URL https://pastebin.vip/view/d902c3ce
  1. ''' x = downhill(F,xStart,side,tol=1.0e-6)
  2.    Downhill simplex method for minimizing the user-supplied
  3.    scalar function F(x) with respect to the vector x.
  4.    xStart = starting vector x.
  5.    side   = side length of the starting simplex (default is 0.1)
  6. '''
  7. from numpy import zeros,dot,argmax,argmin,sum
  8. from math import sqrt
  9.  
  10. def downhill(F,xStart,side=0.1,tol=1.0e-6):
  11.     n = len(xStart)                 # Number of variables
  12.     x = zeros((n+1,n))
  13.     f = zeros(n+1)
  14.  
  15.   # Generate starting simplex
  16.     x[0] = xStart
  17.     for i in range(1,n+1):
  18.         x[i] = xStart
  19.         x[i,i-1] = xStart[i-1] + side        
  20.   # Compute values of F at the vertices of the simplex    
  21.     for i in range(n+1): f[i] = F(x[i])
  22.  
  23.   # Main loop
  24.     for k in range(500):
  25.       # Find highest and lowest vertices
  26.         iLo = argmin(f)
  27.         iHi = argmax(f)      
  28.       # Compute the move vector d
  29.         d = (-(n+1)*x[iHi] + sum(x,axis=0))/n
  30.       # Check for convergence
  31.         if sqrt(dot(d,d)/n) < tol: return x[iLo]
  32.  
  33.       # Try reflection
  34.         xNew = x[iHi] + 2.0*d              
  35.         fNew = F(xNew)        
  36.         if fNew <= f[iLo]:        # Accept reflection
  37.             x[iHi] = xNew
  38.             f[iHi] = fNew
  39.           # Try expanding the reflection
  40.             xNew = x[iHi] + d              
  41.             fNew = F(xNew)
  42.             if fNew <= f[iLo]:    # Accept expansion
  43.                 x[iHi] = xNew
  44.                 f[iHi] = fNew
  45.         else:
  46.           # Try reflection again
  47.             if fNew <= f[iHi]:    # Accept reflection
  48.                 x[iHi] = xNew
  49.                 f[iHi] = fNew
  50.             else:
  51.               # Try contraction
  52.                 xNew = x[iHi] + 0.5*d
  53.                 fNew = F(xNew)
  54.                 if fNew <= f[iHi]: # Accept contraction
  55.                     x[iHi] = xNew
  56.                     f[iHi] = fNew
  57.                 else:
  58.                   # Use shrinkage
  59.                     for i in range(len(x)):
  60.                         if i != iLo:
  61.                             x[i] = (x[i] - x[iLo])*0.5
  62.                             f[i] = F(x[i])
  63.     print "Too many iterations in downhill"
  64.     print "Last values of x were"
  65.     return x[iLo]
  66. #//python/7431

Reply to "Python illustrating Downhill simplex method for mi"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website