zoukankan      html  css  js  c++  java
  • 深度学习常用函数记录(tensorflow)

    持续更新。。。

    一、损失函数

    loss:预测值(y)与已知答案(y_)之间的差距

    NN优化目标:

    1、均方差mse

     tensorflow2实现

    loss_mse = tf.reduce_mean(tf.square(y_-y))

    y_代表label,已知答案,y代表预测值

    2、自定义损失函数

      tensorflow2实现

                                 y>y_?              True              False

    loss_custom = tf.reduce_sum(tf.where(tf.greater(y,y_),(y-y_)*COST,(y_-y)*PROFIT))

    tf.greater(x,y) ==  x > y?

    tf.where(条件,真返回A,假返回B)

     3、交叉熵 ce,cross entropy

    表征两个概率分布之间的距离

      tensorflow2实现

    tf.losses.categorical_crossentropy(y_,y)#tensorflow内置的
    
    loss_crossentropy =- tf.reduce_sum(y_*tf.math.log(tf.clip_by_value(y,0.1,1.0)))#根据公式实现的

    tf.clip_by_value(x,start,end)#控制值在一个范围里[start,end]

    例子

    import tensorflow as tf
    y_ = [[1,0],[2,3]]
    y = [[0.6,0.4],[0.3,0.7]]
    # loss_ce1 = tf.losses.categorical_crossentropy([1, 0], [0.6, 0.4])
    loss_ce1 = tf.losses.categorical_crossentropy(y_,y)
    loss_ce11 = -tf.reduce_sum(y_*tf.math.log(tf.clip_by_value(y,0.1,1.0)),axis=1)
    print("loss_ce1:", loss_ce1)
    print(loss_ce11)
    输出
    loss_ce1: tf.Tensor([0.5108256 3.4779706], shape=(2,), dtype=float32)
    loss_ce11:tf.Tensor([0.5108256 3.4779706], shape=(2,), dtype=float32)

     4、softmax和交叉熵的结合

    输出先过softmax函数,在计算y与y_的交叉熵损失函数

    tensorflow实现

    tf.nn.softmax_cross_entropy_with_logits(y_,y)
     1 # softmax与交叉熵损失函数的结合
     2 import tensorflow as tf
     3 import numpy as np
     4 
     5 y_ = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0]])
     6 y = np.array([[12, 3, 2], [3, 10, 1], [1, 2, 5], [4, 6.5, 1.2], [3, 6, 1]])
     7 y_pro = tf.nn.softmax(y)
     8 loss_ce1 = tf.losses.categorical_crossentropy(y_,y_pro)
     9 loss_ce2 = tf.nn.softmax_cross_entropy_with_logits(y_, y)
    10 
    11 print('分步计算的结果:
    ', loss_ce1)
    12 print('结合计算的结果:
    ', loss_ce2)
    输出
    分步计算的结果:
     tf.Tensor(
    [1.68795487e-04 1.03475622e-03 6.58839038e-02 2.58349207e+00
     5.49852354e-02], shape=(5,), dtype=float64)
    结合计算的结果:
     tf.Tensor(
    [1.68795487e-04 1.03475622e-03 6.58839038e-02 2.58349207e+00
     5.49852354e-02], shape=(5,), dtype=float64)

    第7、8行等于第9行

  • 相关阅读:
    在不申请第三方变量的情况下交换a和b
    指针(pointer)的使用
    数组和链表(arrary & linkedlist)
    Python的学习计划
    Python——函数
    Python——文件操作
    Python——深浅Copy
    我发现的新大陆——好用的~
    我发现的新大陆——好吃儿的
    我发现的新大陆——好玩儿的
  • 原文地址:https://www.cnblogs.com/qqw-1995/p/13308827.html
Copyright © 2011-2022 走看看