TensorFlow2.0之Himmelblau 函数优化实战
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
def himmelblau(x):
# himmelblau函数实现,传入参数x为2个元素的List
return (x[0] ** 2 + x[1] - 11) ** 2 + (x[0] + x[1] ** 2 - 7) ** 2
# 可视化的x坐标范围为-6~6
x = np.arange(-6, 6, 0.1)
# 可视化的y坐标范围为-6~6
y = np.arange(-6, 6, 0.1)
print('x,y range:', x.shape, y.shape)
# 生成x-y平面采样网格点,方便可视化
X, Y = np.meshgrid(x, y)
print('X,Y maps:', X.shape, Y.shape)
# 计算网格点上的函数值
# Z = himmelblau([X, Y])
# # 绘制himmelblau函数曲面
# fig = plt.figure('himmelblau')
# # 设置3D坐标轴
# ax = fig.gca(projection='3d')
# # print(Z.shape)
# # 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.]
# 初始化参数
x = tf.constant([4., 0.])
# 循环优化200次
for step in range(200):
# 梯度跟踪
with tf.GradientTape() as tape:
# 加入梯度跟踪列表
tape.watch([x])
# 前向传播
y = himmelblau(x)
# 反向传播
grads = tape.gradient(y, [x])[0]
# 更新参数,学习率为0.01
x -= 0.01*grads
# 打印优化的最小值
if step % 20 == 19:
print('Step {}: x= {}, f(x) = {}'.format(step, x.numpy(), y.numpy()))