Keras自定义IOU方式


Posted in Python onJune 10, 2020

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

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方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python中的高级函数map/reduce使用实例
Apr 13 Python
Python中字符串的格式化方法小结
May 03 Python
Python 如何访问外围作用域中的变量
Sep 11 Python
python函数式编程学习之yield表达式形式详解
Mar 25 Python
linux安装Python3.4.2的操作方法
Sep 28 Python
Python文件如何引入?详解引入Python文件步骤
Dec 10 Python
python实现统计文本中单词出现的频率详解
May 20 Python
Python虚拟环境的原理及使用详解
Jul 02 Python
Python爬虫抓取技术的一些经验
Jul 12 Python
python内置模块collections知识点总结
Dec 19 Python
win10下python3.8的PIL库安装过程
Jun 08 Python
Python3.9最新版下载与安装图文教程详解(Windows系统为例)
Nov 28 Python
Python实现在线批量美颜功能过程解析
Jun 10 #Python
浅谈keras中的目标函数和优化函数MSE用法
Jun 10 #Python
keras 解决加载lstm+crf模型出错的问题
Jun 10 #Python
使用Keras加载含有自定义层或函数的模型操作
Jun 10 #Python
keras 获取某层的输入/输出 tensor 尺寸操作
Jun 10 #Python
Python 字典中的所有方法及用法
Jun 10 #Python
在keras 中获取张量 tensor 的维度大小实例
Jun 10 #Python
You might like
php可应用于面包屑导航的递归寻找家谱树实现方法
2015/02/02 PHP
PHP使用NuSOAP调用Web服务的方法
2015/07/18 PHP
在Thinkphp中使用ajax实现无刷新分页的方法
2016/10/25 PHP
PHP各种常见经典算法总结【排序、查找、翻转等】
2019/08/05 PHP
如何在Laravel5.8中正确地应用Repository设计模式
2019/11/26 PHP
javascript 有趣而诡异的数组
2009/04/06 Javascript
js时间戳格式化成日期格式的多种方法
2013/11/11 Javascript
javascript模拟枚举的简单实例
2014/03/06 Javascript
Eclipse配置Javascript开发环境图文教程
2015/01/29 Javascript
jQuery结合HTML5制作的爱心树表白动画
2015/02/01 Javascript
javascript实现简单的全选和反选功能
2016/01/05 Javascript
由浅入深剖析Angular表单验证
2016/07/14 Javascript
jQuery实现定位滚动条位置
2016/08/05 Javascript
Vue内容分发slot(全面解析)
2017/08/19 Javascript
解决VUE框架 导致绑定事件的阻止冒泡失效问题
2018/02/24 Javascript
Vue自定义全局弹窗组件操作
2020/08/11 Javascript
Webpack3+React16代码分割的实现
2021/03/03 Javascript
在Python中使用next()方法操作文件的教程
2015/05/24 Python
Python使用urllib2模块实现断点续传下载的方法
2015/06/17 Python
Python编程修改MP3文件名称的方法
2017/04/19 Python
TF-IDF与余弦相似性的应用(二) 找出相似文章
2017/12/21 Python
selenium+python 去除启动的黑色cmd窗口方法
2018/05/22 Python
bluepy 一款python封装的BLE利器简单介绍
2019/06/25 Python
python顺序执行多个py文件的方法
2019/06/29 Python
Python操作excel的方法总结(xlrd、xlwt、openpyxl)
2019/09/02 Python
Python实现直播推流效果
2019/11/26 Python
python 实现rolling和apply函数的向下取值操作
2020/06/08 Python
Python sorted对list和dict排序
2020/06/09 Python
pytorch使用horovod多gpu训练的实现
2020/09/09 Python
端午节粽子促销活动方案
2014/02/02 职场文书
最新大学生创业计划书写作攻略
2014/04/02 职场文书
党的群众路线教育实践活动宣传标语口号
2014/06/06 职场文书
贸易经济专业自荐书
2014/06/29 职场文书
民用住房租房协议书
2014/10/29 职场文书
杭白菊导游词
2015/02/10 职场文书
律师催款函范文
2015/06/24 职场文书