深度学习之损失函数

1.tf.nn.l2_loss

tf.nn.l2_loss(t, name=None)

L2 Loss.Computes halfthe L2 normofa tensorwithoutthesqrt:

这个函数的作用是利用 L2 范数来计算张量的误差值,但是没有开方并且只取 L2 范数的值的一半

output =sum(t **2) /2

Args:

t: A Tensor. Must beoneofthe following types: float32, float64, int64, int32, uint8, int16, int8, complex64, qint8, quint8, qint32.

Typically2-D, but may haveany dimensions.

name: A nameforthe operation (optional).

Returns:A Tensor. Hasthe same typeas t.0-D.

2.tf.nn.softmax(logits, name=None)


计算softmax
softmax[i, j] = exp(logits[i, j]) / sum_j(exp(logits[i, j]))

将神经网络前向传播得到的结果变成概率分布


tensorflow交叉熵计算函数输入中的logits都不是softmax或sigmoid的输出,而是softmax或sigmoid函数的输入,

因为它在函数内部进行sigmoid或softmax操作

3.tf.nn.softmax_cross_entropy_with_logits(logits, labels, name=None)

这个函数的作用是计算 logits 经 softmax 函数激活之后的交叉熵


注意:如果labels的每一行是one-hot表示,也就是只有一个地方为1,其他地方为0,
可以使用tf.sparse_softmax_cross_entropy_with_logits()

计算logits和labels的softmax交叉熵 logits, labels必须为相同的shape与数据类型

输入logits,shape是[batch_size, num_classes] ;labels,shape也是[batch_size, num_classes],神经网络期望的输出

output:lossshape:[batch_size]

具体的执行流程大概分为两步:

第一步是先对网络最后一层的输出做一个softmax,这一步通常是求取输出属于某一类的概率

对于单样本而言,输出就是一个num_classes大小的向量([Y1,Y2,Y3...]其中Y1,Y2,Y3...分别代表了是属于该类的概率)

第二步是softmax的输出向量[Y1,Y2,Y3...]和样本的实际标签做一个交叉熵



这个函数的返回值并不是一个数,而是一个向量,如果要求交叉熵,

我们要再做一步tf.reduce_sum操作,就是对向量里面所有元素求和,

最后才得到,如果求loss,则要做一步tf.reduce_mean操作,对向量求均值!

  1. import tensorflow as tf  
  2.   
  3. #our NN's output  
  4. logits=tf.constant([[1.0,2.0,3.0],[1.0,2.0,3.0],[1.0,2.0,3.0]])  
  5. #step1:do softmax  
  6. y=tf.nn.softmax(logits)  
  7. #true label  
  8. y_=tf.constant([[0.0,0.0,1.0],[0.0,0.0,1.0],[0.0,0.0,1.0]])  
  9. #step2:do cross_entropy  
  10. cross_entropy = -tf.reduce_sum(y_*tf.log(y))  
  11. #do cross_entropy just one step  
  12. cross_entropy2=tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(logits, y_))#dont forget tf.reduce_sum()!!  
  13.   
  14. with tf.Session() as sess:  
  15.     softmax=sess.run(y)  
  16.     c_e = sess.run(cross_entropy)  
  17.     c_e2 = sess.run(cross_entropy2)  
  18.     print("step1:softmax result=")  
  19.     print(softmax)  
  20.     print("step2:cross_entropy result=")  
  21.     print(c_e)  
  22.     print("Function(softmax_cross_entropy_with_logits) result=")  
  23.     print(c_e2)  
    1. step1:softmax result=  
    2. [[ 0.09003057  0.24472848  0.66524094]  
    3.  [ 0.09003057  0.24472848  0.66524094]  
    4.  [ 0.09003057  0.24472848  0.66524094]]  
    5. step2:cross_entropy result=  
    6. 1.22282  
    7. Function(softmax_cross_entropy_with_logits) result=  
    8. 1.2228  


4.tf.nn.sparse_softmax_cross_entropy_with_logits(_sentinel=None, labels=None, logits=None, name=None)

  1. sparse_softmax_cross_entropy_with_logits(  
  2.     _sentinel=None,  
  3.     labels=None,  
  4.     logits=None,  
  5.     name=None  
  6. )  

labels 的输入是稀疏表示的,是 [0,num_classes)中的一个数值,代表正确分类 。labels 的 shape为 [batch_size],即 有batch个数值

logits 是神经网络运行的结果(tensorflow神经网络中没有softmax层,而是在此方法会进行softmax运算)。

logits 的shape是 [batch_size,num_classes],即 batch数*类别数的矩阵

sparse_softmax_cross_entropy_with_logits 直接用标签上计算交叉熵,

而 softmax_cross_entropy_with_logits 是标签的onehot向量参与计算。

softmax_cross_entropy_with_logits 的 labels 是 sparse_softmax_cross_entropy_with_logits 的

labels 的一个独热版本(one hot version)。

一般的使用

[python]  view plain  copy
  1. # 损失函数  
  2.     cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.argmax(y_, 1), logits=y)  
  3.     cross_entropy_mean = tf.reduce_mean(cross_entropy) 

5.tf.nn.sigmoid_cross_entropy_with_logits(_sentinel=None,labels=None, logits=None, name=None)

argument:    

_sentinel:本质上是不用的参数,不用填

logits:一个数据类型(type)是float32或float64;shape:[batch_size,num_classes],单样本是[num_classes]

labels:和logits具有相同的type(float)和shape的张量(tensor),

name:操作的名字,可填可不填

output:

loss,shape:[batch_size,num_classes]

Note:

它对于输入的logits先通过sigmoid函数计算,再计算它们的交叉熵,但是它对交叉熵的计算方式进行了优化,使得结果不至于溢出

它适用于每个类别相互独立但互不排斥的情况:例如一幅图可以同时包含一条狗和一只大象

output不是一个数,而是一个batch中每个样本的loss,所以一般配合tf.reduce_mean(loss)使用


Python 程序:

importtensorflowas tf

import numpy asnp
def sigmoid(x):
    return 1.0/(1+np.exp(-x))
y = np.array([[1,0,0],[0,1,0],[0,0,1],[1,1,0],[0,1,0]] 

# 5个样本三分类问题,且一个样本可以同时拥有多类

logits = np.array([[12,3,2],[3,10,1],[1,2,5],[4,6.5,1.2],[3,6,1]])

y_pred = sigmoid(logits)
E1 = -y*np.log(y_pred)-( 1-y)*np.log( 1-y_pred)
print(E1)  按计算公式计算的结果
sess =tf.Session()
y = np.array(y).astype(np.float64)  # labels是float64的数据类型
E2 = sess.run(tf.nn.sigmoid_cross_entropy_with_logits( labels=y, logits=logits))
print(E2)

6.tf.nn.weighted_cross_entropy_with_logits(labels,logits, pos_weight, name=None) 

计算具有权重的sigmoid交叉熵sigmoid_cross_entropy_with_logits()

argument:

_sentinel:本质上是不用的参数,不用填

logits:一个数据类型(type)是float32或float64;

shape:[batch_size,num_classes],单样本是[num_classes]

labels:和logits具有相同的type(float)和shape的张量(tensor),

pos_weight:正样本的一个系数

name:操作的名字,可填可不填

output:

loss,shape:[batch_size,num_classes]


7.tf.losses.absolute_difference

绝对差分公式(也称为L1损失)

absolute_difference(
    labels
,
    predictions
,
    weights
=1.0,
    scope
=None,
    loss_collection
=tf.GraphKeys.LOSSES,
    reduction
=Reduction.SUM_BY_NONZERO_WEIGHTS
)

Adds an Absolute Difference loss to the training procedure.

weights acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value.

If weights is a Tensor of shape [batch_size], then the total loss for each sample of the batch is

rescaled by the corresponding element in the weights vector.

If the shape of weights matches the shape of predictions, then the loss of each measurable element of predictions

 is scaled by the corresponding value of weights.

Args:

· labels: The ground truth output tensor, same dimensions as 'predictions'.

· predictions: The predicted outputs.

· weights: Optional Tensor whose rank is either 0, or the same rank as labels, and must be broadcastable to labels (i.e., all dimensions must be either 1, or the same as the corresponding losses dimension).

· scope: The scope for the operations performed in computing the loss.

· loss_collection: collection to which this loss will be added.

· reduction: Type of reduction to apply to loss.

Returns:

Weighted loss float Tensor. If reduction is NONE, this has the same shape as labels; otherwise, it is scalar.

8.tf.losses.mean_squared_error(predictions, targets)

使用均方误差(MSE;也称为L2损耗)

9.tf.losses.hinge_loss

Hinge损失是0-1损失函数的一种代理函数,Hinge损失的具体形式如下:

max(0,1-m)

参考来自:

http://blog.csdn.net/mao_xiao_feng/article/details/53382790

http://blog.csdn.net/QW_sunny/article/details/72885403





  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值