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 MD5文件生成码
Jan 12 Python
python高手之路python处理excel文件(方法汇总)
Jan 07 Python
python3.5 + PyQt5 +Eric6 实现的一个计算器代码
Mar 11 Python
python WindowsError的错误代码详解
Jul 23 Python
python机器学习理论与实战(五)支持向量机
Jan 19 Python
vue.js实现输入框输入值内容实时响应变化示例
Jul 07 Python
使用python对多个txt文件中的数据进行筛选的方法
Jul 10 Python
python nmap实现端口扫描器教程
May 28 Python
Django连接数据库并实现读写分离过程解析
Nov 13 Python
python与pycharm有何区别
Jul 01 Python
python空元组在all中返回结果详解
Dec 15 Python
python调试工具Birdseye的使用教程
May 25 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
要会喝咖啡也要会知道咖啡豆
2021/03/03 咖啡文化
PHP设计模式之结构模式的深入解析
2013/06/13 PHP
PHP引用符&的用法详细解析
2013/08/22 PHP
php用header函数实现301跳转代码实例
2013/11/25 PHP
PHP 快速排序算法详解
2014/11/10 PHP
IE和firefox浏览器的event事件兼容性汇总
2009/12/06 Javascript
js function使用心得
2010/05/10 Javascript
字符串的replace方法应用浅析
2011/12/06 Javascript
jquery清空textarea等输入框实现代码
2013/04/22 Javascript
使用js解决由border属性引起的div宽度问题
2013/11/26 Javascript
jQuery修改class属性和CSS样式整理
2015/01/30 Javascript
js实现a标签超链接提交form表单的方法
2015/06/24 Javascript
JavaScript基础——使用Canvas绘图
2016/11/02 Javascript
vue.js将unix时间戳转换为自定义时间格式
2017/01/03 Javascript
js仿新浪微博消息发布功能
2017/02/17 Javascript
浅谈JS对html标签的属性的干预以及对CSS样式表属性的干预
2017/06/25 Javascript
JavaScript设计模式之原型模式分析【ES5与ES6】
2018/07/26 Javascript
Angular 实现输入框中显示文章标签的实例代码
2018/11/07 Javascript
vue elementui el-form rules动态验证的实例代码详解
2019/05/23 Javascript
vue router返回到指定的路由的场景分析
2020/11/10 Javascript
python解析模块(ConfigParser)使用方法
2013/12/10 Python
python+django+sql学生信息管理后台开发
2018/01/11 Python
Python基于lxml模块解析html获取页面内所有叶子节点xpath路径功能示例
2018/05/16 Python
Python实现手写一个类似django的web框架示例
2018/07/20 Python
python 通过 socket 发送文件的实例代码
2018/08/14 Python
python NumPy ndarray二维数组 按照行列求平均实例
2019/11/26 Python
上海天奕面试题笔试题
2015/04/19 面试题
小学生国旗下演讲稿
2014/04/25 职场文书
服务承诺书怎么写
2014/05/24 职场文书
2014小学教师年度考核工作总结
2014/12/03 职场文书
社会实践单位意见
2015/06/05 职场文书
Django实现WebSocket在线聊天室功能(channels库)
2021/09/25 Python
详解python的异常捕获
2022/03/03 Python
WCG2010 星际争霸决赛 Flash vs Goojila 1 星际经典比赛回顾
2022/04/01 星际争霸
Java 垃圾回收超详细讲解记忆集和卡表
2022/04/08 Java/Android
MySQL数据库配置信息查看与修改方法详解
2022/06/25 MySQL