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 25 Python
使用Python处理BAM的方法
Sep 28 Python
python爬虫简单的添加代理进行访问的实现代码
Apr 04 Python
pandas 数据索引与选取的实现方法
Jun 21 Python
解决Pycharm的项目目录突然消失的问题
Jan 20 Python
python实现电子词典
Mar 03 Python
PyCharm 无法 import pandas 程序卡住的解决方式
Mar 09 Python
浅谈keras中自定义二分类任务评价指标metrics的方法以及代码
Jun 11 Python
简单了解Django项目应用创建过程
Jul 06 Python
Python爬虫爬取糗事百科段子实例分享
Jul 31 Python
在Django中使用MQTT的方法
May 10 Python
python开发制作好看的时钟效果
May 02 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
CodeIgniter框架过滤HTML危险代码
2014/06/12 PHP
PHP反射API示例分享
2016/10/08 PHP
javascript 密码强度验证规则、打分、验证(给出前端代码,后端代码可根据强度规则翻译)
2010/05/18 Javascript
JQuery slideshow的一个小问题(如何发现及解决过程)
2013/02/06 Javascript
jQuery实现密保互斥问题解决方案
2013/08/16 Javascript
html文件中jquery与velocity变量中的$冲突的解决方法
2013/11/01 Javascript
jquery 判断滚动条到达了底部和顶端的方法
2014/04/02 Javascript
实用框架(iframe)操作代码
2014/10/23 Javascript
JQuery异步获取返回值中文乱码的解决方法
2015/01/29 Javascript
javascript禁止访客复制网页内容的实现代码
2015/08/05 Javascript
Jquery中request和request.form和request.querystring的区别
2015/11/26 Javascript
js友好的时间返回函数
2016/08/24 Javascript
BootStrap 超链接变按钮的实现方法
2016/09/25 Javascript
JavaScript自定义函数实现查找两个字符串最长公共子串的方法
2016/11/24 Javascript
JavaScript trim 实现去除字符串首尾指定字符的简单方法
2016/12/27 Javascript
vue2.0实战之基础入门(1)
2017/03/27 Javascript
JS实现加载和读取XML文件的方法详解
2017/04/24 Javascript
jQuery手风琴的简单制作
2017/05/12 jQuery
微信小程序 开发MAP(地图)实例详解
2017/06/27 Javascript
Javascript中Promise的四种常用方法总结
2017/07/14 Javascript
weui框架实现上传、预览和删除图片功能代码
2017/08/24 Javascript
实例详解ztree在vue项目中使用并且带有搜索功能
2018/08/24 Javascript
JS实现求5的阶乘示例
2019/01/21 Javascript
JS拖拽排序插件Sortable.js用法实例分析
2019/02/20 Javascript
JavaScript实现无限级递归树的示例代码
2019/03/29 Javascript
vue+koa2搭建mock数据环境的详细教程
2020/05/18 Javascript
[06:53]DOTA2每周TOP10 精彩击杀集锦vol.3
2014/06/25 DOTA
Python解决抛小球问题 求小球下落经历的距离之和示例
2018/02/01 Python
Python中多个数组行合并及列合并的方法总结
2018/04/12 Python
python程序中的线程操作 concurrent模块使用详解
2019/09/23 Python
序列化Python对象的方法
2020/08/01 Python
英国最大的百货公司:Harrods
2016/08/18 全球购物
美术师范毕业生自荐信
2013/11/16 职场文书
党员廉洁自律个人总结
2015/02/13 职场文书
公司业务员管理制度
2015/08/05 职场文书
《弟子规》读后感:知廉耻、明是非、懂荣辱、辨善恶
2019/12/03 职场文书