Tensorflow - Come gradiente di set di un processo esterno (py_func)?
-
16-10-2019 - |
Domanda
sto calcolo e l'ottimizzazione di alcune variabili che vengono utilizzate in un processo esterno, ma ottengo l'errore "No Gradient".
Un pesantemente semplificato (non testato) la versione del codice, ma è possibile ottenere l'idea:
def external_process (myvar):
subprocess.call("process.sh", myvar)
with open('result.json', 'r') as f:
result = json.load(data, f)
return np.array(result["result"])
myvar = tf.Variable(1.0, dtype = 'float32', trainable = True)
loss = tf.reduce_sum( tf.py_func(external_process, [myvar], [tf.float32])[0] )
optimizer = tf.train.AdamOptimizer(0.05)
train_step = optimizer.minimize(loss)
sess.run(train_step)
ho visto questa discussione, ma io non lo comprendiamo pienamente: https://github.com / tensorflow / tensorflow / temi / 1095
Grazie!
Soluzione 2
La risposta corretta è: "un processo esterno non è differenziabile (a meno che non si conosce ogni dettaglio, ciò che è impossibile in questo caso), quindi questo problema dovrebbe essere affrontato come un problema Reinforcement Learning"
Altri suggerimenti
https://www.tensorflow.org/versions /r0.9/api_docs/python/framework.html (ricerca gradient_override_map
) è un esempio su gradient_override_map
:
@tf.RegisterGradient("CustomSquare")
def _custom_square_grad(op, grad):
# ...
with tf.Graph().as_default() as g:
c = tf.constant(5.0)
s_1 = tf.square(c) # Uses the default gradient for tf.square.
with g.gradient_override_map({"Square": "CustomSquare"}):
s_2 = tf.square(s_2) # Uses _custom_square_grad to compute the
# gradient of s_2.
Quindi, una possibile soluzione potrebbe essere:
@tf.RegisterGradient("ExternalGradient")
def _custom_external_grad(unused_op, grad):
# I don't know yet how to compute a gradient
# From Tensorflow documentation:
return grad, tf.neg(grad)
def external_process (myvar):
subprocess.call("process.sh", myvar)
with open('result.json', 'r') as f:
result = json.load(data, f)
return np.array(result["result"])
myvar = tf.Variable(1.0, dtype = 'float32', trainable = True)
g = tf.get_default_graph()
with g.gradient_override_map({"PyFunc": "ExternalGradient"}):
external_data = tf.py_func(external_process, [myvar], [tf.float32])[0]
loss = tf.reduce_sum(external_data)
optimizer = tf.train.AdamOptimizer(0.05)
train_step = optimizer.minimize(loss)
sess.run(train_step)