Tensorflow datatypes

In one of the programming exercises I found that I had to cast the datatypes to avoid error. Once I did that, value I obtained was incorrect.
I am trying to replicate this equation attached below:

Both these methods don’t produce the correct results:

Method 1
factor = 0.25/tf.cast((n_C * n_H * n_W) ** 2, tf.float32)
J_style_layer = factor * tf.reduce_sum(tf.square(GS - GG))

Method 2
J_style_layer = tf.reduce_sum(tf.square(GS - GG)) / (4.0 * tf.cast((n_H * n_W * n_C)**2, tf.float32))

Hi @krithika_govindaraj

Can you share the results too from both of the two methods?

Hi @krithika_govindaraj ,

There are two summations in the formula, but not in your code.
‘Also, for your method1, the factor calculation is incorrect, if you are going to use fraction, it should be 0.25 multiplying not dividing.’ - Your factor calculation is correct, I have missed read it.

I tried both your methods and they worked for me. My guess is that your bug is in the way you compute the Gram Matrices: it does not work if you simply reshape the a_S and a_G to the shapes you want, because that scrambles the data. Here’s a thread which explains why. You may need to read some of the earlier posts on that thread to get the full context.

And here’s a thread that explains why the integers need to be cast to floats depending on how you write the code.