import  numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
import tensorflow as tf

def himmelblau(x):
# z=(x^2+y-11)^2+(x+y^2-7)^2
return (x[0] ** 2 + x[1] - 11) ** 2 + (x[0] + x[1] ** 2 - 7) ** 2

#该注释部分为画出曲面图像的代码
# x=np.arange(-6,6,0.1)
# y=np.arange(-6,6,0.1)
# X,Y=np.meshgrid(x,y)
# Z=himmelblau([X,Y])
#
# fig = plt.figure('himmelblau')
# ax = fig.gca(projection='3d')
# ax.plot_surface(X, Y, Z)
# ax.view_init(60, -30)
# ax.set_xlabel('x')
# ax.set_ylabel('y')
# plt.show()


# [1., 0.], [-4, 0.], [4, 0.]
# 有3个点进行初始化,不同初始化的点,最后结果也可能不一样,所以梯度下降法可能找到局部最优解,而非全局最优解
x = tf.constant([4., 0.])

for step in range(200):

with tf.GradientTape() as tape:
tape.watch([x])
y = himmelblau(x)
#计算梯度
grads = tape.gradient(y, [x])[0]
#向最低点靠近
x -= 0.01*grads



if step % 20 == 0:
print ('step {}: x = {}, f(x) = {}'
.format(step, x.numpy(), y.numpy()))