问题
In Tensorflow I can assign names to operations and tensors to retrieve them later. For example in one function I can do
input_layer=tf.placeholder(tf.float32, shape= [None,300], name='input_layer')
And then in another function later, I can do
input_layer=get_tensor_by_name('input_layer:0')
I came to believe that this is handy for making my tf code as modular as possible.
I would like to be able to do the same with my loss but how can I assign a custom name to that operation? The problem is that the build in loss functions (e.g., tf.losses.mean_squared_error) do not have a parameter for the name (in contrast to tf.placeholder, tf.variable and so on).
The way I refer to my loss at the moment is
tf.get_collection(tf.GraphKeys.LOSSES)[-1]
(retrieving the last loss operation that has been added to the graph). Am I missing something obvious?
回答1:
I know that this is not exactly THE answer but it's a fix that could work for you.
Given that, as you pointed, the tf.losses.mean_squared_error function doesn't have a name
parameter you could implement your own MSE (based on TF operations of course)
Just replace
tf_loss = tf.losses.mean_squared_error(labels,predictions)
With
custom_loss = tf.reduce_mean(tf.squared_difference(labels,predictions),name='loss')
And as reduce_mean
does accept a name
parameter you could get what you want.
Full example code available here
回答2:
I guess using a non trainable Variable should do the trick:
labels = np.random.normal(size=10)
predictions = np.random.normal(size=10)
sess = tf.Session()
loss_var = tf.Variable(10.0, name='mse_loss', trainable=False, dtype=tf.float32)
loss = tf.losses.mean_squared_error(labels, predictions)
mse_loss = loss_var.assign(loss)
sess.run(mse_loss)
print(sess.run(tf.get_default_graph().get_tensor_by_name('mse_loss:0')))
回答3:
I've found that the shortest way to do this is by using tf.identity
.
loss = tf.losses.mean_squared_error(labels, predictions)
loss = tf.identity(loss, name = "loss")
来源:https://stackoverflow.com/questions/46258166/how-can-i-set-the-name-of-my-loss-operation-in-tensorflow