Keras自定义IOU方式

作者:Nick Blog 时间:2022-12-24 07:48:27 

我就废话不多说了,大家还是直接看代码吧!


def iou(y_true, y_pred, label: int):
 """
 Return the Intersection over Union (IoU) for a given label.
 Args:
   y_true: the expected y values as a one-hot
   y_pred: the predicted y values as a one-hot or softmax output
   label: the label to return the IoU for
 Returns:
   the IoU for the given label
 """
 # extract the label values using the argmax operator then
 # calculate equality of the predictions and truths to the label
 y_true = K.cast(K.equal(K.argmax(y_true), label), K.floatx())
 y_pred = K.cast(K.equal(K.argmax(y_pred), label), K.floatx())
 # calculate the |intersection| (AND) of the labels
 intersection = K.sum(y_true * y_pred)
 # calculate the |union| (OR) of the labels
 union = K.sum(y_true) + K.sum(y_pred) - intersection
 # avoid divide by zero - if the union is zero, return 1
 # otherwise, return the intersection over union
 return K.switch(K.equal(union, 0), 1.0, intersection / union)

def mean_iou(y_true, y_pred):
 """
 Return the Intersection over Union (IoU) score.
 Args:
   y_true: the expected y values as a one-hot
   y_pred: the predicted y values as a one-hot or softmax output
 Returns:
   the scalar IoU value (mean over all labels)
 """
 # get number of labels to calculate IoU for
 num_labels = K.int_shape(y_pred)[-1] - 1
 # initialize a variable to store total IoU in
 mean_iou = K.variable(0)

# iterate over labels to calculate IoU for
 for label in range(num_labels):
   mean_iou = mean_iou + iou(y_true, y_pred, label)

# divide total IoU by number of labels to get mean IoU
 return mean_iou / num_labels

补充知识:keras 自定义评估函数和损失函数loss训练模型后加载模型出现ValueError: Unknown metric function:fbeta_score

keras自定义评估函数

有时候训练模型,现有的评估函数并不足以科学的评估模型的好坏,这时候就需要自定义一些评估函数,比如样本分布不均衡是准确率accuracy评估无法判定一个模型的好坏,这时候需要引入精确度和召回率作为评估标准,不幸的是keras没有这些评估函数。

以下是参考别的文章摘取的两个自定义评估函数

召回率:


def recall(y_true, y_pred):
 true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
 possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
 recall = true_positives / (possible_positives + K.epsilon())
 return recall

精确度:


def precision(y_true, y_pred):
 true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
 predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
 precision = true_positives / (predicted_positives + K.epsilon())
 return precision

自定义了评估函数,一般在编译模型阶段加入即可:

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy', precision, recall])

自定义了损失函数focal_loss一般也在编译阶段加入:

model.compile(optimizer=Adam(lr=0.0001), loss=[focal_loss],
metrics=['accuracy',fbeta_score], )

其他的没有特别要注意的点,直接按照原来的思路训练一版模型出来就好了,关键的地方在于加载模型这里,自定义的函数需要特殊的加载方式,不然会出现加载没有自定义函数的问题:ValueError: Unknown loss function:focal_loss

解决方案:


model_name = 'test_calssification_model.h5'
model_dfcw = load_model(model_name,
           custom_objects={'focal_loss': focal_loss,'fbeta_score':fbeta_score})

注意点:将自定义的损失函数和评估函数都加入到custom_objects里,以上就是在自定义一个损失函数从编译模型阶段到加载模型阶段出现的所有的问题。

来源:https://blog.csdn.net/xijuezhu8128/article/details/86608333

标签:Keras,自定义,IOU
0
投稿

猜你喜欢

  • Python实现将数据库一键导出为Excel表格的实例

    2024-01-19 19:47:27
  • 基于pytorch的保存和加载模型参数的方法

    2023-02-07 00:24:12
  • 详解Python中的数据精度问题

    2022-08-17 13:36:22
  • vue 集成jTopo 处理方法

    2024-05-09 15:17:42
  • python中使用.py配置文件的方法详解

    2022-02-13 19:57:22
  • 深入理解Python中的super()方法

    2022-11-07 05:10:45
  • Python中多线程thread与threading的实现方法

    2021-08-24 08:34:38
  • python读取查看npz/npy文件数据以及数据完全显示方法实例

    2022-05-15 15:45:36
  • js 中将多个逗号替换为一个逗号的代码

    2024-04-16 10:32:48
  • python连接clickhouse数据库的两种方式小结

    2024-01-24 19:25:02
  • 详解使用Vue Router导航钩子与Vuex来实现后退状态保存

    2024-05-05 09:24:27
  • go语言import报错处理图文详解

    2024-02-06 17:01:51
  • MySQL最基本的命令使用汇总

    2024-01-28 06:18:30
  • SQL批量插入数据几种方案的性能详细对比

    2024-01-13 11:06:32
  • selenium+python配置chrome浏览器的选项的实现

    2022-06-24 11:56:31
  • 浅谈Python实现Apriori算法介绍

    2021-09-14 19:10:22
  • Asp中通过简单的例子理解下ByVal和ByRef的用法

    2011-02-20 10:57:00
  • Python os和os.path模块详情

    2022-12-08 12:53:45
  • 网页布局的位置重心与位置间的对比关系

    2007-10-15 19:20:00
  • 详解如何在cmd命令窗口中搭建简单的python开发环境

    2021-08-21 08:03:08
  • asp之家 网络编程 m.aspxhome.com