[关闭]
@cleardusk 2015-11-13T17:03:21.000000Z 字数 587 阅读 1370

GD

GjzCVCode


算法部分

  1. # coding:utf-8
  2. '''Gradient desent algo, take F(x) = x^4-3x^3+2 for example'''
  3. def F(x):
  4. return x**4 - 3 * x**3 + 2
  5. def f_derivative(x):
  6. return 4 * x**3 - 9 * x**2
  7. pass
  8. def gd(x_new=None):
  9. '''
  10. x_new is the guess number
  11. '''
  12. # parameter
  13. gamma = 0.01 # step size
  14. precision = 0.00001
  15. x_old = 0
  16. # iteration
  17. while abs(x_new - x_old) > precision:
  18. x_old = x_new
  19. x_new = x_old - gamma * f_derivative(x_old)
  20. return x_new
  21. pass
  22. if __name__ == '__main__':
  23. x = gd(2)
  24. print 'Local minum occurs at', x

测试部分

  1. from gd import *
  2. def test():
  3. x_guess = 6
  4. x = gd(x_guess)
  5. print 'guess x:', x_guess
  6. print 'x:', x
  7. print 'function value:', F(x)
  8. print 'derivative value:', f_derivative(x)
  9. if __name__ == '__main__':
  10. test()
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注