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操作时间和日期之asctime()方法的使用
May 22 Python
qpython3 读取安卓lastpass Cookies
Jun 19 Python
python中执行shell的两种方法总结
Jan 10 Python
mac下pycharm设置python版本的图文教程
Jun 13 Python
浅谈python requests 的put, post 请求参数的问题
Jan 02 Python
详解python中@的用法
Mar 27 Python
python pandas cumsum求累计次数的用法
Jul 29 Python
python3应用windows api对后台程序窗口及桌面截图并保存的方法
Aug 27 Python
Python3实现发送邮件和发送短信验证码功能
Jan 07 Python
Python制作简易版小工具之计算天数的实现思路
Feb 13 Python
python如何导出微信公众号文章方法详解
Aug 31 Python
python3 kubernetes api的使用示例
Jan 12 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简单静态页生成过程
2008/03/27 PHP
PHP 解决session死锁的方法
2013/06/20 PHP
php密码生成类实例
2014/09/24 PHP
php实现的中秋博饼游戏之掷骰子并输出结果功能详解
2017/11/06 PHP
记录Yii2框架开发微信公众号遇到的问题及解决方法
2018/07/20 PHP
utf-8编码引起js输出中文乱码的解决办法
2010/06/23 Javascript
jquery下动态显示jqGrid以及jqGrid的属性设置容易出现问题的解决方法
2010/10/22 Javascript
用于节点操作的API,颠覆原生操作HTML DOM节点的API
2010/12/11 Javascript
ajax请求get与post的区别总结
2013/11/04 Javascript
Node.js模块加载详解
2014/08/16 Javascript
javascript实现画不相交的圆
2015/04/07 Javascript
jQuery 获取跨域XML(RSS)数据的相关总结分析
2016/05/18 Javascript
jQuery UI结合Ajax创建可定制的Web界面
2016/06/22 Javascript
JS判断一个数是否是水仙花数
2017/06/11 Javascript
详解webpack 入门总结和实践(按需异步加载,css单独打包,生成多个入口文件)
2017/06/20 Javascript
解决Vue打包之后文件路径出错的问题
2018/03/06 Javascript
nodejs取得当前执行路径的方法
2018/05/13 NodeJs
Vue 进阶之路(三)
2019/04/18 Javascript
[02:01]大师之路——DOTA2完美大师赛11月论剑上海
2017/11/06 DOTA
python中解析json格式文件的方法示例
2017/05/03 Python
对tensorflow 的模型保存和调用实例讲解
2018/07/28 Python
python pandas消除空值和空格以及 Nan数据替换方法
2018/10/30 Python
分析经典Python开发工程师面试题
2019/04/08 Python
Python values()与itervalues()的用法详解
2019/11/27 Python
解决Tensorflow 内存泄露问题
2020/02/05 Python
Python中return函数返回值实例用法
2020/11/19 Python
如何做好总经理助理
2013/11/12 职场文书
竞选部门副经理的自荐书范文
2014/02/11 职场文书
小学运动会班级口号
2014/06/09 职场文书
自查自纠工作总结
2014/10/15 职场文书
2014年话务员工作总结
2014/11/19 职场文书
2014年小学英语教师工作总
2014/12/03 职场文书
高三英语复习计划
2015/01/19 职场文书
好好学习保证书
2015/02/26 职场文书
2016年教师反腐倡廉心得体会
2016/01/13 职场文书
七年级生物教学反思
2016/02/20 职场文书