Tensorflow最小化整数

时间:2019-03-19 14:15:57

标签: tensorflow minimize minimization

我正在尝试实现一个函数,该函数使参数由数组条目给出的函数最小化。我尝试了示例代码:

z = tf.Variable(6., trainable=True)

A=np.linspace(-1,1,50)
data_tf = tf.convert_to_tensor(A, np.float32)

f_x = data_tf[tf.cast(tf.clip_by_value(z,0,25),tf.int32)]

loss = f_x
opt = tf.train.GradientDescentOptimizer(1).minimize(f_x)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(100):
        print(sess.run([z,loss]))
        sess.run(opt)

这给了我错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-35-278fa6e8507a> in <module>()
14 
15 loss = f_x
---> 16 opt = tf.train.GradientDescentOptimizer(1).minimize(f_x)
17 
18 with tf.Session() as sess:

~\Anaconda3\lib\site-packages\tensorflow\python\training\optimizer.py in 
minimize(self, loss, global_step, var_list, gate_gradients, 
aggregation_method, colocate_gradients_with_ops, name, grad_loss)
405           “No gradients provided for any variable, check your graph for 
ops”
406           “ that do not support gradients, between variables %s and loss 
%s.” %
--> 407           ([str(v) for _, v in grads_and_vars], loss))
408 
409     return self.apply_gradients(grads_and_vars, global_step=global_step,

ValueError: No gradients provided for any variable, check your graph for ops 
that 
do not support gradients, between variables ["<tf.Variable 'Variable:0' 
shape=() 
dtype=float32_ref>",

有人有主意吗?

1 个答案:

答案 0 :(得分:0)

错误消息指出,您要最小化的功能是不可区分的。区域切片操作根本无法连接到您已定义的tf.Variable。 此示例将起作用

z = tf.Variable(6., trainable=True)
e = tf.Variable(0., trainable=True)

A = np.linspace(-1, 1, 50)
data_tf = tf.convert_to_tensor(A, np.float32)

idx = tf.cast(tf.clip_by_value(z,0,25),tf.int32)
f_x = tf.slice(data_tf, [idx],[1]) 

f_x = tf.reduce_sum(f_x - e)

loss = f_x
opt = tf.train.GradientDescentOptimizer(1).minimize(f_x)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(100):
        sess.run(opt)
        print(sess.run([z,loss]))

编辑:您可以像这样添加z的副本

zz = tf.identity(z)

,但是它将其值绑定到原始变量,因此您仍然需要在最终操作中添加它(在这种情况下为reduce_sum)以使其具有可区分性。这是因为,如果将其强制转换为int并作为索引传递,它将停止可区分。为了进行更改,您需要在原始值和f_x之间建立连接。希望这可以使它更清楚。