[关闭]
@kailaix 2016-09-03T11:06:02.000000Z 字数 2030 阅读 2554

拉格朗日松弛方法

拉格朗日松弛方法的基本思想是将“顽固”的约束(通常是等式约束)整合到目标函数中去。如果原来目标函数是一个线性函数,等式约束是一个线性约束,拉格朗日方法要求我们能够轻松求解给定区域下的线性目标函数问题。

拉格朗日方法的理论基础是凸优化中的对偶原理,需要注意的是,即使最后取得 max min 时候的极值点(argmin argmax )不是原来函数的极值点,但是在一定条件下,我们能得到一样的函数值。

另一个需要注意的是,对于去掉线性约束后约束区域无界的情况,需要小心处理(见以下笔记);虽然在数学上容易处理,但是在实践中很容易造成溢出。

下面的代码是上面两个问题的求解,注意这里我们是手动求最小值,也可以借助现有优化包例如scipy.optimize

  1. from scipy import optimize as opt
  2. import numpy as np
  3. from math import pi,cos,sin
  4. import cPickle
  5. class ILRSolver(object):
  6. def __init__(self,f,marker):
  7. self.f = f
  8. self.stepsize = 1.0
  9. self.cnt = 0
  10. self.iter_cnt = 0
  11. self.mu = 0.0
  12. self.marker = marker
  13. self.L = []
  14. def _fmin(self):
  15. if self.marker == 1:
  16. if self.mu >= 1:
  17. self.x = np.array([0,0,0]);return
  18. else:
  19. self.x = np.array([1,1,1]);return
  20. if self.marker == 2:
  21. if self.mu < 1:
  22. self.x = np.array([1,1,1]);return
  23. elif self.mu<2:
  24. self.x = np.array([0,1,1]);return
  25. elif self.mu<3:
  26. self.x = np.array([0,0,1]);return
  27. else:
  28. self.x = np.array([0,0,0]);return
  29. def update_coef(self):
  30. delta = self.x.sum() - 1.5
  31. if delta > 0:
  32. self.mu += self.stepsize
  33. elif delta < 0:
  34. self.mu -= self.stepsize
  35. def update(self):
  36. self.update_coef()
  37. self._fmin()
  38. self.fx_old = self.fx
  39. self.fx = self.f(self.x)
  40. if self.fx == self.fx_old:
  41. self.cnt += 1
  42. if self.cnt >= 10 or self.iter_cnt % 10==0:
  43. self.cnt = 0
  44. self.stepsize /= 2.0
  45. def _nonstop(self):
  46. print "---------------------\n Current infomation:"
  47. print "iter: "+ str(self.iter_cnt)
  48. print "stepsize: "+str(self.stepsize)
  49. print "x: "+ str(self.x)
  50. print "mu: "+str(self.mu)
  51. print "f(x): "+ str(self.fx)
  52. print "g(x): " + str(self.x.sum() - 1.5)
  53. obj_func = lambda x:self.f(x)+self.mu*(x[0]+x[1]+x[2]-1.5)
  54. print "objf(x): "+str(obj_func(self.x))
  55. self.L.append(obj_func(self.x))
  56. self.iter_cnt += 1
  57. # raw_input('press to continue')
  58. if self.stepsize <= 1e-5:
  59. print 'STEPSIZE TOO SMALL'
  60. return False
  61. if self.x[0]+self.x[1]+self.x[2] == 1.5:
  62. print 'OPTIMAL'
  63. return False
  64. return True
  65. def iterate(self):
  66. self._fmin()
  67. self.fx = self.f(self.x)
  68. while self._nonstop():
  69. self.update()
  70. def save_data(self):
  71. with open(str(self.marker)+'.dat','wb') as fp:
  72. cPickle.dump(self.L, fp)
  73. f1 = lambda x: - ( x[0]**2 + x[1]**2 + x[2]**2 )
  74. f2 = lambda x: - (x[0]+2*x[1]+3*x[2])
  75. ilr1 = ILRSolver(f1,1)
  76. ilr2 = ILRSolver(f2,2)
  77. ilr1.iterate()
  78. ilr1.save_data()
  79. ilr2.iterate()
  80. ilr2.save_data()

下面是两个对偶函数最大值的收敛形态。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注