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 命令行参数sys.argv
Sep 06 Python
python使用BeautifulSoup分析网页信息的方法
Apr 04 Python
python解决方案:WindowsError: [Error 2]
Aug 28 Python
python自动化脚本安装指定版本python环境详解
Sep 14 Python
TensorFlow实现Logistic回归
Sep 07 Python
解决Python一行输出不显示的问题
Dec 03 Python
django解决跨域请求的问题详解
Jan 20 Python
Python判断有效的数独算法示例
Feb 23 Python
python matplotlib拟合直线的实现
Nov 19 Python
使用Python开发个京东上抢口罩的小实例(仅作技术研究学习使用)
Mar 10 Python
为什么说python更适合树莓派编程
Jul 20 Python
Python 使用dict实现switch的操作
Apr 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学习笔记(毕业设计)
2012/02/21 PHP
PHP将XML转数组过程详解
2013/11/13 PHP
Yii2创建控制器(createController)方法详解
2016/07/23 PHP
网络图片延迟加载实现代码 超越jquery控件
2010/03/27 Javascript
理解Javascript_06_理解对象的创建过程
2010/10/15 Javascript
js实现幻灯片播放图片示例代码
2013/11/07 Javascript
JS字符串截取函数实例
2013/12/27 Javascript
jquery sortable的拖动方法示例详解
2014/01/16 Javascript
JavaScript函数的4种调用方法详解
2014/04/22 Javascript
input标签内容改变的触发事件介绍
2014/06/18 Javascript
php结合imgareaselect实现图片裁剪
2015/07/05 Javascript
vue动态改变背景图片demo分享
2018/09/13 Javascript
VuePress 快速踩坑小结
2019/02/14 Javascript
Vue项目服务器部署之子目录部署方法
2019/05/12 Javascript
JavaScript隐式类型转换代码实例
2020/05/29 Javascript
[02:40]DOTA2殁境神蚀者 英雄基础教程
2013/11/26 DOTA
Python实现抓取页面上链接的简单爬虫分享
2015/01/21 Python
Python学习笔记之if语句的使用示例
2017/10/23 Python
python+selenium实现自动抢票功能实例代码
2018/11/23 Python
Python 一键制作微信好友图片墙的方法
2019/05/16 Python
详解利用OpenCV提取图像中的矩形区域(PPT屏幕等)
2019/07/01 Python
详解Matplotlib绘图之属性设置
2019/08/23 Python
python urllib爬虫模块使用解析
2019/09/05 Python
解决margin 外边距合并问题
2019/07/03 HTML / CSS
挪威太阳镜和眼镜网上商城:SmartBuyGlasses挪威
2016/08/20 全球购物
美国在线家居装饰店:Belle&June
2018/10/24 全球购物
"引用"与指针的区别是什么
2016/09/07 面试题
大四自我鉴定
2014/02/08 职场文书
行政助理的岗位职责
2014/02/18 职场文书
党委班子剖析材料
2014/08/21 职场文书
2014年学生会部门工作总结
2014/11/07 职场文书
幼儿园老师新年寄语2015
2014/12/08 职场文书
幼儿园个人师德总结
2015/02/06 职场文书
实习推荐信格式模板
2015/03/27 职场文书
教你利用Selenium+python自动化来解决pip使用异常
2021/05/20 Python
分位数回归模型quantile regeression应用详解及示例教程
2021/11/02 Python