Keras自定义IOU方式

 更新时间:2020年06月10日 14:51:32   作者:Nick Blog  
这篇文章主要介绍了Keras自定义IOU方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

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

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里,以上就是在自定义一个损失函数从编译模型阶段到加载模型阶段出现的所有的问题。

以上这篇Keras自定义IOU方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 30秒学会30个超实用Python代码片段【收藏版】

    30秒学会30个超实用Python代码片段【收藏版】

    许多人在数据科学、机器学习、web开发、脚本编写和自动化等领域中都会使用Python,它是一种十分流行的语言。本文将简要介绍30个简短的、且能在30秒内掌握的代码片段,感兴趣的朋友一起看看吧
    2019-10-10
  • 利用Python如何将数据写到CSV文件中

    利用Python如何将数据写到CSV文件中

    在数据分析中经常需要从csv格式的文件中存取数据以及将数据写书到csv文件中。下面这篇文章主要给大家介绍了关于利用Python如何将数据写到CSV文件中的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2018-06-06
  • Python实现简单的索引排序与搜索功能

    Python实现简单的索引排序与搜索功能

    这篇文章主要介绍了Python实现简单的索引排序与搜索功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-04-04
  • python的re模块应用实例

    python的re模块应用实例

    这篇文章主要介绍了python的re模块应用实例,包括了常见的正则匹配技巧,需要的朋友可以参考下
    2014-09-09
  • python递归查询菜单并转换成json实例

    python递归查询菜单并转换成json实例

    本篇文章主要介绍了python递归查询菜单并转换成json实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
    2017-03-03
  • python3操作微信itchat实现发送图片

    python3操作微信itchat实现发送图片

    这篇文章主要为大家详细介绍了python3操作微信itchat实现发送图片,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-02-02
  • 运行tensorflow python程序,限制对GPU和CPU的占用操作

    运行tensorflow python程序,限制对GPU和CPU的占用操作

    今天小编就为大家分享一篇运行tensorflow python程序,限制对GPU和CPU的占用操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-02-02
  • Python利用Matplotlib库实现绘制饼形图

    Python利用Matplotlib库实现绘制饼形图

    这篇文章主要为大家分享了基于python+matplotlib库的饼形图绘制,具体内容涉及一般的饼图、分裂饼图、以及环形图,感兴趣的小伙伴可以了解一下
    2022-04-04
  • Python爬虫实现爬取下载网站数据的几种方法示例

    Python爬虫实现爬取下载网站数据的几种方法示例

    这篇文章主要为大家介绍了Python爬虫实现爬取下载网站数据的几种方法示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-11-11
  • python数据可视化Seaborn画热力图

    python数据可视化Seaborn画热力图

    这篇文章主要介绍了数据可视化Seaborn画热力图,热力图的想法其实很简单,用颜色替换数字,下面我们来看看文章对操作过程的具体介绍吧,需要的小伙伴可以参考一下具体内容,希望对你有所帮助
    2022-01-01

最新评论