擅长:python、mysql、java
<blockquote>
<p>why if i declare the equation and its loss function outside the for
loop it will lead to an error</p>
</blockquote>
<p>我想你是在问关于循环的具体问题,但是你可以像这样声明函数</p>
<pre><code>@tf.function
def f(x):
Y = 4 * x + 2
Y = tf.square(Y)
return Y
x = tf.Variable(0.0)
opt = tf.keras.optimizers.SGD(learning_rate=0.01)
loss_fn = lambda: f(x)
var_list = [x]
for _ in range(10000):
opt.minimize(loss_fn, var_list)
print(x.numpy())
</code></pre>
<blockquote>
<p>-0.49999997</p>
</blockquote>