himmelblau.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import numpy as np
  2. from mpl_toolkits.mplot3d import Axes3D
  3. from matplotlib import pyplot as plt
  4. import tensorflow as tf
  5. def himmelblau(x):
  6. # himmelblau函数实现
  7. return (x[0] ** 2 + x[1] - 11) ** 2 + (x[0] + x[1] ** 2 - 7) ** 2
  8. x = np.arange(-6, 6, 0.1)
  9. y = np.arange(-6, 6, 0.1)
  10. print('x,y range:', x.shape, y.shape)
  11. # 生成x-y平面采样网格点,方便可视化
  12. X, Y = np.meshgrid(x, y)
  13. print('X,Y maps:', X.shape, Y.shape)
  14. Z = himmelblau([X, Y]) # 计算网格点上的函数值
  15. # 绘制himmelblau函数曲面
  16. fig = plt.figure('himmelblau')
  17. ax = fig.gca(projection='3d')
  18. ax.plot_surface(X, Y, Z)
  19. ax.view_init(60, -30)
  20. ax.set_xlabel('x')
  21. ax.set_ylabel('y')
  22. plt.show()
  23. # 参数的初始化值对优化的影响不容忽视,可以通过尝试不同的初始化值,
  24. # 检验函数优化的极小值情况
  25. # [1., 0.], [-4, 0.], [4, 0.]
  26. # x = tf.constant([4., 0.])
  27. # x = tf.constant([1., 0.])
  28. # x = tf.constant([-4., 0.])
  29. x = tf.constant([-2., 2.])
  30. for step in range(200):# 循环优化
  31. with tf.GradientTape() as tape: #梯度跟踪
  32. tape.watch([x]) # 记录梯度
  33. y = himmelblau(x) # 前向传播
  34. # 反向传播
  35. grads = tape.gradient(y, [x])[0]
  36. # 更新参数,0.01为学习率
  37. x -= 0.01*grads
  38. # 打印优化的极小值
  39. if step % 20 == 19:
  40. print ('step {}: x = {}, f(x) = {}'
  41. .format(step, x.numpy(), y.numpy()))