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学习手册中的python多态示例代码
Jan 21 Python
python获得一个月有多少天的方法
Jun 04 Python
在Django的模板中使用认证数据的方法
Jul 23 Python
解决python中无法自动补全代码的问题
Dec 04 Python
Python根据当前日期取去年同星期日期
Apr 14 Python
python制作图片缩略图
Apr 30 Python
使用selenium模拟登录解决滑块验证问题的实现
May 10 Python
利用Python进行图像的加法,图像混合(附代码)
Jul 14 Python
python将数组n等分的实例
Dec 02 Python
python 对任意数据和曲线进行拟合并求出函数表达式的三种解决方案
Feb 18 Python
python实现从尾到头打印单链表操作示例
Feb 22 Python
刚学完怎么用Python实现定时任务,转头就跑去撩妹!
Jun 05 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中Date获取时间不正确怎么办
2008/06/05 PHP
php下网站防IP攻击代码,超级实用
2010/10/24 PHP
PHP获取时间排除周六、周日的两个方法
2014/06/30 PHP
Linux系统下使用XHProf和XHGui分析PHP运行性能
2015/12/08 PHP
PHP计算日期相差天数实例分析
2016/02/23 PHP
使用JS操作页面表格,元素的一些技巧
2007/02/02 Javascript
javascript 无提示关闭窗口脚本
2009/08/17 Javascript
用jQuery打造TabPanel效果代码
2010/05/22 Javascript
javascript中兼容主流浏览器的动态生成iframe方法
2014/05/05 Javascript
JavaScript匿名函数与委托使用示例
2014/07/22 Javascript
javascript实现详细时间提醒信息效果的方法
2015/03/11 Javascript
JavaScript获取并更改input标签name属性的方法
2015/07/02 Javascript
理解Javascript的call、apply
2015/12/16 Javascript
图片懒加载插件实例分享(含解析)
2017/01/09 Javascript
Vue插件写、用详解(附demo)
2017/03/20 Javascript
angular2+node.js express打包部署的实战
2017/07/27 Javascript
微信小程序实现拖拽功能
2019/09/26 Javascript
微信小程序实用代码段(收藏版)
2019/12/17 Javascript
基于vue-draggable 实现三级拖动排序效果
2020/01/10 Javascript
详解Python程序与服务器连接的WSGI接口
2015/04/29 Python
Python Web程序部署到Ubuntu服务器上的方法
2018/02/22 Python
Python 利用pydub库操作音频文件的方法
2019/01/09 Python
python 表格打印代码实例解析
2019/10/12 Python
Pytorch DataLoader 变长数据处理方式
2020/01/08 Python
python实现飞行棋游戏
2020/02/05 Python
python pandas.DataFrame.loc函数使用详解
2020/03/26 Python
pytorch Dataset,DataLoader产生自定义的训练数据案例
2021/03/03 Python
Laura官网:加拿大女性的顶级时尚目的地
2019/09/20 全球购物
令人啧啧称赞的经理推荐信
2013/11/07 职场文书
高级护理专业毕业生推荐信
2013/12/25 职场文书
领导欢迎词范文
2015/01/26 职场文书
Mysql数据库命令大全
2021/05/26 MySQL
安装配置mysql及Navicat prenium的详细流程
2021/06/10 MySQL
mysql如何配置白名单访问
2021/06/30 MySQL
python自动化八大定位元素讲解
2021/07/09 Python
Tomcat项目启动失败的原因和解决办法
2022/04/20 Servers