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将ip地址转换成整数的方法
Mar 17 Python
简析Python的闭包和装饰器
Feb 26 Python
python3学习之Splash的安装与实例教程
Jul 09 Python
学生信息管理系统python版
Oct 17 Python
Python的Tkinter点击按钮触发事件的例子
Jul 19 Python
基于Django ORM、一对一、一对多、多对多的全面讲解
Jul 26 Python
Pycharm 2019 破解激活方法图文详解
Oct 11 Python
Python通过文本和图片生成词云图
May 21 Python
Python打印不合法的文件名
Jul 31 Python
Python 处理日期时间的Arrow库使用
Aug 18 Python
Python .py生成.pyd文件并打包.exe 的注意事项说明
Mar 04 Python
python 爬取天气网卫星图片
Jun 07 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中删除变量时unset()和null的区别分析
2011/01/27 PHP
用js实现的一个Flash滚动轮换显示图片代码生成器
2007/03/14 Javascript
javascript中直接写php代码的方法
2013/07/31 Javascript
jQuery简易图片放大特效示例代码
2014/06/09 Javascript
javascript实现避免页面按钮重复提交
2015/01/08 Javascript
javascript实现手机震动API代码
2015/08/05 Javascript
JS实现的不规则TAB选项卡效果代码
2015/09/18 Javascript
js简单设置与使用cookie的方法
2016/01/22 Javascript
完美实现js焦点轮播效果(二)(图片可滚动)
2017/03/07 Javascript
jQuery ajax实现省市县三级联动
2021/03/07 Javascript
Centos6.8下Node.js安装教程
2017/05/12 Javascript
微信小程序 支付功能(前端)的实现
2017/05/24 Javascript
React Native 集成jpush-react-native的示例代码
2017/08/16 Javascript
Validform验证时可以为空否则按照指定格式验证
2017/10/20 Javascript
nuxt框架中路由鉴权之Koa和Session的用法
2018/05/09 Javascript
jQuery移动端跑马灯抽奖特效升级版(抽奖概率固定)实现方法
2019/01/18 jQuery
基于vue通用表单解决方案的思考与分析
2019/03/16 Javascript
Postman环境变量全局变量使用方法详解
2020/08/13 Javascript
[05:48]DOTA2英雄梦之声vol21 屠夫
2014/06/20 DOTA
[01:13]2015国际邀请赛线下观战现场
2015/08/08 DOTA
[48:47]VGJ.S vs NB 2018国际邀请赛小组赛BO2 第一场 8.18
2018/08/19 DOTA
[38:42]完美世界DOTA2联赛循环赛 Matador vs Forest BO2第二场 11.05
2020/11/05 DOTA
[00:59]PWL开团时刻DAY7——我在赶
2020/11/06 DOTA
举例讲解Python程序与系统shell交互的方式
2015/04/09 Python
python中私有函数调用方法解密
2016/04/29 Python
Python基于回溯法子集树模板解决马踏棋盘问题示例
2017/09/11 Python
python爬虫 正则表达式使用技巧及爬取个人博客的实例讲解
2017/10/20 Python
浅谈Series和DataFrame中的sort_index方法
2018/06/07 Python
python简单贪吃蛇开发
2019/01/28 Python
Canvas 像素处理之改变透明度的实现代码
2019/01/08 HTML / CSS
年度献血先进个人事迹材料
2014/02/14 职场文书
《将心比心》教学反思
2014/04/08 职场文书
村干部群众路线教育活动对照检查材料
2014/10/01 职场文书
违反单位工作制度检讨书
2014/10/25 职场文书
中标通知书
2015/04/17 职场文书
Vue3中的Refs和Ref详情
2021/11/11 Vue.js