tensorflow中的4X+2=0

2024-04-28 22:11:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用TensorFlow解这个方程(4X+2=0),关于这个代码我有两个问题:

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())

我的第一个问题是:

为什么如果我在for循环之外声明等式及其损失函数,会导致错误

y = 4 * x + 2
loss = tf.square(y)

我的意思是每次迭代这些变量都会在内存中启动一个新地址,所以我想把它们放在for循环之外

第二个问题是:

为什么我要使成本函数(4X+2)^2,然后我再次微分方程


Tags: 函数代码inimportfortftensorflowas
2条回答

关于StackOverflow,最好在帖子中只问一个问题。在这个回答中,我将看一下你的第一个问题。对于第二个问题,请随意提问。一旦您编辑了您的问题,我将编辑此答案并删除该部分

why if I declare the equation and its loss function outside the for loop it will lead to an error

自TF2以来,tensorflow的默认设计是渴望执行。这意味着使用tensorflow进行编码与使用本机python进行开发的方式非常接近。 如果我们用本机python编写此tensorflow代码,我们将有:

learning_rate = 0.01
x = 0.0
training_steps = 100
for _ in range(training_steps):
    # We calculate Y with the current value of X
    y = 4*x + 2
    # we calculate the mean squared error
    error = (y-0)**2
    # We calculate the gradient. 
    # In TF, this is done with a call to tape.gradient
    # dy = 4 * dx
    gradient = 4 * error
    # We correct x with the new gradient. 
    # In TF this is done by calling the optimizer
    x = x - (learning_rate*gradient)
print(x)
# this code results in x=-0.4853790481319223. Not bad!

在本机python代码中,很清楚为什么我们必须在循环中重新计算y的值:在更改x的值时,我们还需要更新y的值!这种行为在TF抽象下有点隐藏,但我希望现在它更清晰一些

why if i declare the equation and its loss function outside the for loop it will lead to an error

我想你是在问关于循环的具体问题,但是你可以像这样声明函数

@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())

-0.49999997

相关问题 更多 >