i want to solve this equation (4X + 2 = 0) using TensorFlow, i have two questions about this code:
import tensorflow as tf
x = tf.Variable(0.0)
for i in range(10000):
with tf.GradientTape() as tape:
y = 4 * x + 2
loss = tf.square(y)
gradient=tape.gradient(loss,[x])
tf.optimizers.SGD(learning_rate=0.01).apply_gradients(zip(gradient,[x]))
print(x.numpy())
my first question is :
why if i declare the equation and its loss function outside the for loop it will lead to an error
y = 4 * x + 2
loss = tf.square(y)
i mean those variable every iteration will initiate a new address in the memory, so i wanted to put them away of for loop.
the second question is:
why should i make the cost function (4X + 2 )^2, then i differentiate the equation again?