如何在 Tensorflow 中编写自定义损失函数? [英] How to write a custom loss function in Tensorflow?

查看:41
本文介绍了如何在 Tensorflow 中编写自定义损失函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 tensorflow 的新手.我想编写自己的自定义损失函数.有没有关于这个的教程?例如,铰链损失或 sum_of_square_loss(尽管这已经在 tf 中)?可以直接用python做还是得自己写cpp代码?

I am new to tensorflow. I want to write my own custom loss function. Is there any tutorial about this? For example, the hinge loss or a sum_of_square_loss(though this is already in tf)? Can I do it directly in python or I have to write the cpp code?

推荐答案

我们需要写下损失函数.例如,我们可以使用基本均方误差作为预测 y 和目标 y_ 的损失函数:

We need to write down the loss function. For example, we can use basic mean square error as our loss function for predicted y and target y_:

 loss_mse = 1/n(Sum((y-y_)^2))

张量有一些基本函数,例如 tf.add(x,y), tf.sub(x,y), tf.square(x), tf.reduce_sum(x),.

There are basic functions for tensors like tf.add(x,y), tf.sub(x,y), tf.square(x), tf.reduce_sum(x), etc.

然后我们可以在 Tensorflow 中定义我们的损失函数,如:

Then we can define our loss function in Tensorflow like:

cost = tf.reduce_mean(tf.square(tf.sub(y,y_)))

注意:y 和 y_ 是张量.

Note: y and y_ are tensors.

此外,如果我们可以写下方程,我们可以定义任何其他损失函数.对于一些训练算子(最小化器),损失函数应该满足一些条件(平滑、可微……).

Moreover, we can define any other loss functions if we can write down the equations. For some training operators (minimizers), the loss function should satisfy some conditions (smooth, differentiable ...).

一句话,Tensorflow 将数组、常量、变量定义为张量,使用 tf 函数定义计算,并使用 session 来运行图形.我们可以定义任何我们喜欢的并最终运行它.

In one word, Tensorflow define arrays, constants, variables into tensors, define calculations using tf functions, and use session to run though graph. We can define whatever we like and run it in the end.

这篇关于如何在 Tensorflow 中编写自定义损失函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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