python - 在不知道底层函数的情况下,使用 TensorFlow 以数值方式最小化量化值图来查找位置
问题描述
我有一个函数值的量化二维映射,我不知道它的函数。我想找到这张地图最小值的连续位置。
我可以使用 TensorFlow 轻松完成此操作scipy
,但我想为此使用 TensorFlow,因为实际上,我有一个非常复杂的计算图,我想自动导出它,它就像使用 TF 的魅力一样。这基本上需要数值和解析梯度计算的混合。
在下文中,您将找到一个非常小的示例,它以 Rosenbrock 函数的形式捕获了我无法在 TF 中表达但在scipy
.
使用 scipy:
import tensorflow as tf
import numpy as np
from scipy.ndimage import map_coordinates
from scipy.optimize import minimize
xx, yy = np.meshgrid(np.linspace(-2., 2., 1000),
np.linspace(-3., 1., 1000))
x0 = np.array([-1.5, -.5])
origin = np.array([-2, -3])
spacing = np.array([4. / 1000, 4. / 1000])
# the quantized function I want to minimize, can be anything
rosenbrock = ((1 - xx)**2 + 100*(yy - xx**2)**2).T
# it is NOT that simple ;)
print('Quantized min at: ',
spacing * np.unravel_index(np.argmin(rosenbrock), rosenbrock.shape)
+ origin)
def rosen(x):
idx = ((x - origin) / spacing).reshape(1, 2)
return map_coordinates(rosenbrock, idx.T)
rosenbrock_grad0, rosenbrock_grad1 = np.gradient(rosenbrock)
def rosen_der(x):
idx = ((x - origin) / spacing).reshape(1, 2)
return np.array([map_coordinates(rosenbrock_grad0, idx.T)[0],
map_coordinates(rosenbrock_grad1, idx.T)[0]])
res = minimize(rosen, x0, method='BFGS', jac=rosen_der, options={'disp': True})
print('Print continuous BFGS result:', res)
但是如何使用张量流?
x_tf = tf.Variable(x0)
idx_tf = (x_tf - origin) / spacing
# how to express this as an OP where I can supply gradients
# in form a numerical derivatives?
f_tf = ???
opt_tf = tf.train.AdamOptimizer().minimize(f_tf)
with tf.Session() as session:
for i in range(100):
session.run(opt_tf)
print('%i: f=%f x=%s' % (i + 1, session.run(f_tf), session.run(x_tf)))
解决方案
推荐阅读
- r - Rstudio 的“在文件中查找”中的正则表达式
- ios - HERE iOS sdk - 操作本地化
- javascript - 在 Javascript 中初始化数组的更聪明的方法
- django - DRF 中具有实例 ID 的 FileField
- c# - 如何通过 C# 创建 GMSA 帐户
- c++ - 无法更改位于另一个窗口内的窗口的背景颜色
- vb.net - 将 32 位有符号整数转换为 64 位整数,同时保留精确位
- alias - 如何同时替换“:”和“;” 换行?
- npm - 自定义 npm 包中客户端的可覆盖配置
- javascript - 如何遍历我的表单字段并将它们添加到规则/消息对象?