如何通过更新变量来改变张量的输出? [英] How do I change the output from a tensor by updating a variable?
问题描述
我有一个依赖于某些变量的损失函数,然后我想更改该变量并获取更新的损失.损失是作为函数的输入给我的,所以我不能简单地将该行移到 tf.control_dependencies 下(这确实给了我想要的东西).那么我该如何在以后更新变量和损失呢?
I have a loss function which is dependant on some variable, then I want to change that variable and get the updated loss. The loss is given to me as an input to a function, so I can't simply move that line under tf.control_dependencies (which does give me what I want). So how do I go about updating the variable and loss afterwards?
X = tf.Variable(1.0) #Dummy parameters of a neural network
loss = (X+1.0)**2 #Dummy Loss function given to me as input
add = tf.assign(X,X+1.0) #Me changing the parameters of the network
with tf.control_dependencies( [ add ] ):
updated_loss = loss #Me wanting the updated loss
print(K.eval(updated_loss )) #Me not getting the updated loss :(
推荐答案
使损失变量具有初始值时,并不能使函数每次调用时都重新评估损失
When you make the loss variable, you are giving it an initial value, this doesn't make it a function that will reevaluate the loss every time it is called.
我们可以创建一个损失函数,每次调用它来计算损失
We can make a loss function that is called to calculate the loss each time
我更改了下面的代码,以将值重新分配给loss tensorflow变量,而不是返回新变量.
I changed the code below to reassign a value to the loss tensorflow variable rather than returning a new variable.
import tensorflow as tf
import tensorflow.keras.backend as K
# Function that updates the loss
@tf.function
def update_loss(X, loss):
loss.assign((X+1.0)**2)
def test():
# Initialise a value of loss
loss = tf.Variable(0.0)
print(K.eval(loss))
# Initialise variable
X = tf.Variable(2.0)
# Update loss
update_loss(X, loss)
print(K.eval(loss))
# Change network by adding 1.0
X.assign_add(1.0)
# Update loss
update_loss(X, loss)
print(K.eval(loss))
这篇关于如何通过更新变量来改变张量的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!