Tensorflow: Error when calling optimizer to minimize loss

Viewed 326

I am trying to get tensorflow to minimize a loss function with respect to a variable, however, I keep getting an error and I am unsure of the cause. I have created a minimal example:

import tensorflow as tf

def loss_func(x, target):
    return tf.pow(x - target, 2) 

x = tf.Variable(initial_value=1., name='x', dtype=tf.float32)
target = tf.constant(value=10., dtype=tf.float32)
adam = tf.train.AdamOptimizer()
loss = lambda: loss_func(x, target)
adam_op = adam.minimize(loss, var_list=tf.trainable_variables)

When running this piece of code I get the error

AttributeError: 'function' object has no attribute '_id'

The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "test.py", line 19, in <module>
    adam_op = adam.minimize(loss, var_list=tf.trainable_variables)
  File "C:...\optimizer.py", line 403, in minimize
    grad_loss=grad_loss)
  File "C:...\optimizer.py", line 461, in compute_gradients
    tape.watch(var_list)
  File "C:...\backprop.py", line 808, in watch
    tape.watch(self._tape, t)
  File "C:...\tape.py", line 59, in watch
    pywrap_tensorflow.TFE_Py_TapeWatch(tape._tape, tensor)  # pylint: disable=protected-access
SystemError: <built-in function TFE_Py_TapeWatch> returned a result with an error set

Does anyone know what it is I am doing wrong? Thank you. I am using tensorflow version 1.13.1

1 Answers

I don't quite understand what you are doing. It appears you are trying to optimize x towards 10. If this is the case you can just assign it to 10. Alternatively, if you will have more than one target, you can take an some sort average of those targets and assign x to that. I believe the problem in the code is that there x the input is also a trainable variable.

Related