首页 > 解决方案 > 在不知道底层函数的情况下,使用 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)))

标签: pythonnumpytensorflowoptimizationscipy

解决方案


推荐阅读