美文网首页
类别不均衡以及自定义loss函数

类别不均衡以及自定义loss函数

作者: 夕宝爸爸 | 来源:发表于2019-02-28 11:56 被阅读0次

计算标签权重

def calculating_class_weights(y_true):
    from sklearn.utils.class_weight import compute_class_weight
    number_dim = np.shape(y_true)[1]
    weights = np.empty([number_dim, 2])
    for i in range(number_dim):
        weights[i] = compute_class_weight('balanced', [0.,1.], y_true[:, i])
    return weights
y_true = np.array([[0,1,1,1,0,1],[0,0,0,1,1,1],[1,0,0,0,1,0],[1,1,0,0,1,0]])
print(y_true)
print(weights)
[[0 1 1 1 0 1]
 [0 0 0 1 1 1]
 [1 0 0 0 1 0]
 [1 1 0 0 1 0]]
[[1.         1.        ]
 [1.         1.        ]
 [0.66666667 2.        ]
 [1.         1.        ]
 [2.         0.66666667]
 [1.         1.        ]]

构建定制化的loss函数

import tensorflow as tf
from keras import backend as K
def get_weighted_loss(weights):
    def weighted_loss(y_true, y_pred):
        return K.mean((weights[:,0]**(1-y_true))*(weights[:,1]**(y_true))*K.binary_crossentropy(tf.convert_to_tensor(y_true,np.float32), tf.convert_to_tensor(y_pred,np.float32)), axis=-1)
    return weighted_loss
model.compile(optimizer=Adam(), loss=get_weighted_loss(class_weights))

这里有一点注意,需要将numpy array转换为tensor,转换的方式为:

import tensorflow as tf
import numpy as np

data = [[1,2,3],[4,5,6]]
data_np = np.asarray(data, np.float32)

data_tf = tf.convert_to_tensor(data_np, np.float32)

否则将会报错

AttributeError: 'numpy.dtype' object has no attribute 'base_dtype'

相关文章

  • 类别不均衡以及自定义loss函数

    计算标签权重 构建定制化的loss函数 这里有一点注意,需要将numpy array转换为tensor,转换的方式...

  • 07.17

    评分函数(score function),它是原始图像数据到类别分值的映射。损失函数(loss function)...

  • 如何load自己定制的loss函数模型

    处理已保存模型中的自定义层或其他自定义对象自己在使用magpie的时候定义了一个loss函数,为了解决类别不平衡的问题

  • (13)目标检测的Loss

    faster-RCNN、SSD目标函数分为两个部分:对应默认框的位置loss(loc)和类别置信度loss(con...

  • Keras多输出模型构建

    1、多输出模型 使用keras函数式API构建网络: 2、自定义loss函数 3、批量训练 4、调试 在自定义的l...

  • Keras 自定义loss函数 focal loss + tri

    上一节中已经阐述清楚了,keras.Model的输入输出与loss的关系。 一、自定义loss损失函数 https...

  • loss函数之MultiMarginLoss, MultiLab

    MultiMarginLoss 多分类合页损失函数(hinge loss),对于一个样本不是考虑样本输出与真实类别...

  • Pytorch自定义Loss函数

    方案一:只定义loss函数的前向计算公式 在pytorch中定义了前向计算的公式,在训练时它会自动帮你计算反向传播...

  • keras的零碎笔记

    1、keras自定义目标损失函数 2、keras绘制acc-loss曲线 定义一个LossHistory类,保存l...

  • 逻辑回归

    逻辑回归: 公式 loss函数 非凸函数,容易造成局部最优 Minimizing the loss corresp...

网友评论

      本文标题:类别不均衡以及自定义loss函数

      本文链接:https://www.haomeiwen.com/subject/xldhuqtx.html