TransWikia.com

No gradients provided for any variable: ['Variable:0', 'Variable:0']

Data Science Asked by Ken S on March 3, 2021

I am using Python 3.6 and Tensorflow 2.0 for the following code for linear regression:

tx = tf.constant(x, dtype=tf.float32)
ty = tf.constant(y, dtype=tf.float32)
    
tw = tf.Variable(initial_value=np.random.randn(), dtype=tf.float32, trainable=True)
tb = tf.Variable(initial_value=0, dtype=tf.float32, trainable=True)
tyhat = tx * tw  + tb
    
cost = lambda: tf.reduce_mean(tf.square(tyhat-ty))
optimizer = tf.optimizers.SGD(0.01)
train = optimizer.minimize(cost, var_list = [tw,tb])

and got an error: No gradients provided for any variable: [‘Variable:0’, ‘Variable:0’]

Any help?

One Answer

tw = tf.Variable(initial_value=np.random.randn(), dtype=tf.float32, trainable=True)
tb = tf.Variable(initial_value=0, dtype=tf.float32, trainable=True)

cost =  lambda :tf.reduce_mean(tf.square(tx*tw+tb-ty))
optimizer = tf.keras.optimizers.SGD(0.01)
train = optimizer.minimize(cost, var_list = [tw,tb])

Reference to tw and tb directly in cost function rather than through yhat. It will work.

Answered by SrJ on March 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP