`tape` is required when a `Tensor` loss is passed

Viewed 3796

Some question about tf.

import numpy as np
import tensorflow as tf
from tensorflow import keras

x_train = [1,2,3]
y_train = [1,2,3]

W = tf.Variable(tf.random.normal([1]), name = 'weight')
b = tf.Variable(tf.random.normal([1]), name = 'bias')
hypothesis = W*x_train+b

optimizer = tf.optimizers.SGD (learning_rate=0.01)

train = tf.keras.optimizers.Adam().minimize(cost, var_list=[W, b])

As I start the last line of my code, below error comes out.

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-52-cd6e22f66d09> in <module>()
----> 1 train = tf.keras.optimizers.Adam().minimize(cost, var_list=[W, b])

1 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py in _compute_gradients(self, loss, var_list, grad_loss, tape)
    530     # TODO(josh11b): Test that we handle weight decay in a reasonable way.
    531     if not callable(loss) and tape is None:
--> 532       raise ValueError("`tape` is required when a `Tensor` loss is passed.")
    533     tape = tape if tape is not None else backprop.GradientTape()
    534 

ValueError: `tape` is required when a `Tensor` loss is passed.

I know it is related with tensorflow version 2, but don't want to modify to version 1.

Want a solution with tensorflow ver2. Thx.

1 Answers

Since you did not provided the cost function, I added one. Here is the code

import numpy as np
import tensorflow as tf
from tensorflow import keras

 
x_train = [1,2,3]
y_train = [1,2,3]

W = tf.Variable(tf.random.normal([1]), name = 'weight')
b = tf.Variable(tf.random.normal([1]), name = 'bias')
hypothesis = W*x_train+b

@tf.function
def cost():

    y_model = W*x_train+b
    error = tf.reduce_mean(tf.square(y_train- y_model))
    return error


optimizer = tf.optimizers.SGD (learning_rate=0.01)

train = tf.keras.optimizers.Adam().minimize(cost, var_list=[W, b])

tf.print(W)
tf.print(b)
Related