# Code error using Gradient Tape

**URL:** <https://discuss.ai.google.dev/t/code-error-using-gradient-tape/30044>\
**Category:** General Discussion\
**Tags:** tensorflow, help\_request\
**Created:** [July 4, 2022, 2:54am UTC](https://discuss.ai.google.dev/t/code-error-using-gradient-tape/30044 "2022-07-04T02:54:46Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![tzahi\_geller](https://d1dlmcr85iqnpo.cloudfront.net/user_avatar/discuss.ai.google.dev/tzahi_geller/32/11640_2.png) [@tzahi\_geller](https://discuss.ai.google.dev/u/tzahi_geller)\
**Post date:** [July 4, 2022, 2:54am UTC](https://discuss.ai.google.dev/t/code-error-using-gradient-tape/30044/1 "2022-07-04T02:54:46Z")

</div>

Hi all,  
I tried to implement a very basic classification algorithm using tensorflow API  
the steps are:

1. creating synthetic data
2. define the architecture prediction = tf.matmul(inpurs,W) + b
3. iterate on training step

For some reason the GradientTape instance could not find W,b so I used local function variables  
the code is:

import tensorflow as tf  
input\_dims=2  
output\_dims=1

W = tf.Variable(initial\_value = tf.random.uniform((input\_dims,output\_dims)))  
b = tf.Variable(initial\_value = tf.random.uniform((output\_dims,)))

def square\_loss(preds,labels):  
loss = tf.square(preds-labels)

```
return tf.reduce_mean(loss)

```

def training\_step(data,labels,local\_W,local\_b):  
with tf.GradientTape() as g:  
predictions = tf.matmul(data,local\_W)+local\_b  
loss = square\_loss(predictions,labels)

```
grad_W,grad_b = g.gradient(loss, [local_W,local_b])
return loss,grad_W,grad_b

```

step\_size = 0.02  
loss\_val =   
for i in range(40):  
#print(W)  
(loss,grad\_W,grad\_b) = training\_step(data,targets,W,b)  
loss\_val.append(np.array(loss))  
#print(grad\_W)  
W = tf.add(W,grad\_W\*(-step\_size))  
b = tf.add(b,grad\_b\*(-step\_size))

What happens is at iteration 2 the gradients calculated by GradientTape instance are none type  
I checked the loss function (on which gradient is calculated) and it has a valid number  
Can someone please explain why the gradient calculation is not working?

---

<div class="post-metadata">

**Author:** ![Mark\_Strefford](https://d1dlmcr85iqnpo.cloudfront.net/user_avatar/discuss.ai.google.dev/mark_strefford/32/9304_2.png) [@Mark\_Strefford](https://discuss.ai.google.dev/u/Mark_Strefford)\
**Post date:** [July 11, 2022, 9:51am UTC](https://discuss.ai.google.dev/t/code-error-using-gradient-tape/30044/3 "2022-07-11T09:51:44Z")

</div>

Can you structure your `code` better. It’s partially marked with `code` and mostly not, there’s no indents, etc.

Also, this is an example of how I’ve used `gradientTape` successfully:

```auto
def step(real_x, real_y):
    with tf.GradientTape() as tape:
        # Make prediction
        pred_y = model(real_x.reshape((-1, 28, 28, 1)))
        # Calculate loss
        model_loss = tf.keras.losses.categorical_crossentropy(real_y, pred_y)
    
    # Calculate gradients
    model_gradients = tape.gradient(model_loss, model.trainable_variables)
    # Update model
    optimizer.apply_gradients(zip(model_gradients, model.trainable_variables))

```

This is from section 2.2 of [tf.GradientTape Explained for Keras Users | by Sebastian Theiler | Analytics Vidhya | Medium](https://medium.com/analytics-vidhya/tf-gradienttape-explained-for-keras-users-cc3f06276f22)

I didn’t see an `optimiser.apply_gradients()` call above, you seem to be trying to apply them manually.

---

<div class="post-metadata">

**Author:** ![tzahi\_geller](https://d1dlmcr85iqnpo.cloudfront.net/user_avatar/discuss.ai.google.dev/tzahi_geller/32/11640_2.png) [@tzahi\_geller](https://discuss.ai.google.dev/u/tzahi_geller)\
**Post date:** [July 13, 2022, 7:51am UTC](https://discuss.ai.google.dev/t/code-error-using-gradient-tape/30044/5 "2022-07-13T07:51:58Z")

</div>

So instead of using the optimizer I am just calculating the gradient and tweak the weights with a fixed learning rate  
I saw this done in a book called Deep learning with python, it implements model fit basics without usage of keras (actually the writer was one of keras developers).  
I will try to load my code better

Thanks!
