# -*- coding: utf-8 -*-
"""
Created on Wed May 27 15:33:24 2020
@author: MACHENIKE
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
#himmelblau函数
def himmelblau(x):
return (x[0]**2 + x[1] -11)**2 + (x[0] + x[1]**2 - 7)**2
x = np.arange(-5,5,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)
plt.show()
#找最低点
x = tf.constant([4.,0.0])
#超参数学习率
lr = 0.01
for step in range(200):
with tf.GradientTape() as tape:
tape.watch(x)
y = himmelblau(x)
grads = tape.gradient(y,x)
x = x - lr * grads
with tf.Session():
print('极值',step,x.eval(),y.eval(),grads.eval())
函数绘图和极值