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字符串中的单双引
Feb 16 Python
Python中super函数的用法
Nov 17 Python
pycharm 在windows上编辑代码用linux执行配置的方法
Oct 27 Python
python训练数据时打乱训练数据与标签的两种方法小结
Nov 08 Python
对python文件读写的缓冲行为详解
Feb 13 Python
python3应用windows api对后台程序窗口及桌面截图并保存的方法
Aug 27 Python
python验证码图片处理(二值化)
Nov 01 Python
python文件操作seek()偏移量,读取指正到指定位置操作
Jul 05 Python
python 实现简单的计算器(gui界面)
Nov 11 Python
Python爬虫入门教程01之爬取豆瓣Top电影
Jan 24 Python
Python中的流程控制详解
Feb 18 Python
Python快速优雅的批量修改Word文档样式
May 20 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无刷新上传文件实现代码
2011/09/19 PHP
php session实现多级目录存放实现代码
2016/02/03 PHP
Alliance vs Liquid BO3 第二场2.13
2021/03/10 DOTA
JQuery UI的拖拽功能实现方法小结
2012/03/14 Javascript
jquery实现上下左右滑动的方法
2015/02/09 Javascript
jQuery控制文本框只能输入数字和字母及使用方法
2016/05/26 Javascript
JavaScript中匿名函数的用法及优缺点详解
2016/06/01 Javascript
JavaScript来实现打开链接页面的简单实例
2016/06/02 Javascript
javascript特效实现——当前时间和倒计时效果的简单实例
2016/07/20 Javascript
总结十个Angular.js由浅入深的面试问题
2016/08/26 Javascript
angularjs 实现带查找筛选功能的select下拉框实例
2017/01/11 Javascript
jquery表单验证插件validation使用方法详解
2017/01/20 Javascript
Angularjs自定义指令Directive详解
2017/05/27 Javascript
nginx部署访问vue-cli搭建的项目的方法
2018/02/12 Javascript
原生js实现获取form表单数据代码实例
2019/03/27 Javascript
如何使用CSS3和JQuery easing 插件制作绚丽菜单
2019/06/18 jQuery
vue 实现特定条件下绑定事件
2019/11/09 Javascript
extjs图形绘制之饼图实现方法分析
2020/03/06 Javascript
微信小程序学习总结(四)事件与冒泡实例分析
2020/06/04 Javascript
Python实现二维有序数组查找的方法
2016/04/27 Python
Python使用win32 COM实现Excel的写入与保存功能示例
2018/05/03 Python
python读取文件名并改名字的实例
2019/01/07 Python
python3实现的zip格式压缩文件夹操作示例
2019/08/17 Python
Python获取一个用户名的组ID过程解析
2019/09/03 Python
Python如何在循环内使用list.remove()
2020/06/01 Python
Python使用正则表达式实现爬虫数据抽取
2020/08/17 Python
维珍澳洲航空官网:Virgin Australia
2017/09/08 全球购物
Lovedrobe官网:英国领先的大码服装品牌
2019/09/19 全球购物
毕业生的自我评价
2013/12/30 职场文书
毕业生写求职信的要点
2014/03/04 职场文书
就业意向书范文
2014/04/01 职场文书
网站美工岗位职责
2014/04/02 职场文书
基层党员干部四风问题整改方向和措施
2014/09/25 职场文书
2015年小学图书室工作总结
2015/05/18 职场文书
导游词之澳门玫瑰圣母堂
2019/12/03 职场文书
一篇文章学会Vue中间件管道
2021/06/20 Vue.js