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中的数据类型
May 05 Python
python实现连接mongodb的方法
May 08 Python
Python中列表、字典、元组数据结构的简单学习笔记
Mar 20 Python
Python Numpy库安装与基本操作示例
Jan 08 Python
浅谈Python 多进程默认不能共享全局变量的问题
Jan 11 Python
python将字符串转换成json的方法小结
Jul 09 Python
Python处理session的方法整理
Aug 29 Python
解决Python二维数组赋值问题
Nov 28 Python
解决Pycharm的项目目录突然消失的问题
Jan 20 Python
Python第三方包PrettyTable安装及用法解析
Jul 08 Python
详解Django中异步任务之django-celery
Nov 05 Python
python爬取抖音视频的实例分析
Jan 19 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 IPV6正则表达式验证代码
2010/02/16 PHP
Admin generator, filters and I18n
2011/10/06 PHP
php定义参数数量可变的函数用法实例
2015/03/16 PHP
JQuery AJAX实现目录浏览与编辑的代码
2008/10/21 Javascript
用JQuery实现全选与取消的两种简单方法
2014/02/22 Javascript
jQuery获取iframe的document对象的方法
2014/10/10 Javascript
JQuery显示隐藏DIV的方法及代码实例
2015/04/16 Javascript
手机Web APP如何实现分享多平台功能
2016/08/19 Javascript
jquery 属性选择器(匹配具有指定属性的元素)
2016/09/06 Javascript
Angular.js中ng-if、ng-show和ng-hide的区别介绍
2017/01/20 Javascript
JavaScript阻止表单提交方法(附代码)
2017/08/15 Javascript
JS实现问卷星自动填问卷脚本并在两秒自动提交功能
2020/06/17 Javascript
HTML5开发Kinect体感游戏的实例应用
2017/09/18 Javascript
微信小程序实现红包功能(后端PHP实现逻辑)
2018/07/11 Javascript
Vue 莹石摄像头直播视频实例代码
2018/08/31 Javascript
Vue+Node服务器查询Mongo数据库及页面数据传递操作实例分析
2019/12/20 Javascript
[37:50]VP vs TNC Supermajor小组赛B组 BO3 第一场 6.2
2018/06/03 DOTA
python中使用mysql数据库详细介绍
2015/03/27 Python
python友情链接检查方法
2015/07/08 Python
python 按照固定长度分割字符串的方法小结
2018/04/30 Python
django 修改server端口号的方法
2018/05/14 Python
Sanic框架Cookies操作示例
2018/07/17 Python
Python装饰器用法实例分析
2019/01/14 Python
pyMySQL SQL语句传参问题,单个参数或多个参数说明
2020/06/06 Python
Python如何把字典写入到CSV文件的方法示例
2020/08/23 Python
Python3.9.1中使用match方法详解
2021/02/08 Python
详解HTML5中rel属性的prefetch预加载功能使用
2016/05/06 HTML / CSS
资生堂英国官网:Shiseido英国
2020/12/30 全球购物
初三家长会邀请函
2014/01/18 职场文书
师生聚会感言
2014/01/26 职场文书
中国好声音华少广告词
2014/03/17 职场文书
食品安全承诺书范文
2014/08/29 职场文书
机关作风建设自查报告及整改措施
2014/10/21 职场文书
龙猫观后感
2015/06/09 职场文书
小学三年级语文教学反思
2016/03/03 职场文书
Oracle表空间与权限的深入讲解
2021/11/17 Oracle