函数优化实战
Himmelblau function
- f(x,y)=(x2+y−11)2+(x+y2−7)2f(x,y)=(x2+y−11)2+(x+y2−7)2
Minima
- f(3.0,2.0)=0.0
- f(-2.8,3.1)=0.0
- f(-3.7,-3.2)=0.0
- f(3.5,-1.84)=0.0
Plot
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def himmeblau(x):
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)
print(f'x_shape: {x.shape},y_shape: {y.shape}')
# 生成坐标点
X, Y = np.meshgrid(x, y)
print(f'X_shape: {X.shape},Y_shape: {Y.shape}')
Z = himmeblau([X, Y])
fig = plt.figure('himmelblau')
ax = Axes3D(fig)
ax.plot_surface(X, Y, Z)
ax.view_init(60, -30)
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.show()
x_shape: (120,),y_shape: (120,)
X_shape: (120, 120),Y_shape: (120, 120)
Gradient Descent
import tensorflow as tf
x = tf.constant([-4.,0.])
for step in range(200):
with tf.GradientTape() as tape:
tape.watch([x])
y = himmeblau(x)
grads = tape.gradient(y,[x])[0]
x -= 0.01 * grads
if step % 20 == 0:
print(f'step: {step}, x: {x}, f(x): {y}')
step: 0, x: [-2.98 -0.09999999], f(x): 146.0
step: 20, x: [-3.6890159 -3.1276689], f(x): 6.054703235626221
step: 40, x: [-3.7793102 -3.283186 ], f(x): 0.0
step: 60, x: [-3.7793102 -3.283186 ], f(x): 0.0
step: 80, x: [-3.7793102 -3.283186 ], f(x): 0.0
step: 100, x: [-3.7793102 -3.283186 ], f(x): 0.0
step: 120, x: [-3.7793102 -3.283186 ], f(x): 0.0
step: 140, x: [-3.7793102 -3.283186 ], f(x): 0.0
step: 160, x: [-3.7793102 -3.283186 ], f(x): 0.0
step: 180, x: [-3.7793102 -3.283186 ], f(x): 0.0
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!
2019-12-11 214 Redis数据类型之散列表
2019-12-11 020 使用Tornado和协程爬取博客园文章
2019-12-11 213 Redis数据类型之列表操作
2019-12-11 212 Redis之安装
2019-12-11 02-29 朴素贝叶斯(垃圾邮件分类)
2019-12-11 02-30 线性可分支持向量机
2019-12-11 02-28 scikit-learn库之线朴素贝叶斯