如何在 Tensorflow 中设置我的损失操作的名称? [英] How can I set the name of my loss operation in Tensorflow?

查看:29
本文介绍了如何在 Tensorflow 中设置我的损失操作的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Tensorflow 中,我可以为操作和张量分配名称,以便稍后检索它们.例如在我可以做的一个功能中

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

我开始相信这有助于使我的 tf 代码尽可能模块化.

I came to believe that this is handy for making my tf code as modular as possible.

我希望能够对我的损失做同样的事情,但我如何为该操作指定一个自定义名称?问题在于内置损失函数(例如,tf.losses.mean_squared_error) 没有名称参数(与 tf.placeholder、tf.variable 等相反).

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?

推荐答案

我知道这不完全是答案,但它是一个可以为您工作的解决方案.

I know that this is not exactly THE answer but it's a fix that could work for you.

鉴于,正如您所指出的,tf.losses.mean_squared_error 函数没有 name 参数,您可以实现自己的 MSE(当然基于 TF 操作)

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)

直接替换

tf_loss = tf.losses.mean_squared_error(labels,predictions)

custom_loss = tf.reduce_mean(tf.squared_difference(labels,predictions),name='loss')

并且由于 reduce_mean 接受 name 参数,您可以获得您想要的.

And as reduce_mean does accept a name parameter you could get what you want.

完整示例代码可用 这里

这篇关于如何在 Tensorflow 中设置我的损失操作的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆