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中decorator使用实例
Apr 14 Python
wxPython定时器wx.Timer简单应用实例
Jun 03 Python
Python作用域用法实例详解
Mar 15 Python
windows下ipython的安装与使用详解
Oct 20 Python
python 定时器每天就执行一次的实现代码
Aug 14 Python
python针对mysql数据库的连接、查询、更新、删除操作示例
Sep 11 Python
python 实现二维字典的键值合并等函数
Dec 06 Python
python-xpath获取html文档的部分内容
Mar 06 Python
在python中修改.properties文件的操作
Apr 08 Python
python 用pandas实现数据透视表功能
Dec 21 Python
Python 如何实现文件自动去重
Jun 02 Python
Python Flask搭建yolov3目标检测系统详解流程
Nov 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 heredoc和phpwind的模板技术使用方法小结
2008/03/28 PHP
从康盛产品(discuz)提取出来的模板类
2011/06/28 PHP
定义php常量的详解
2013/06/09 PHP
PHP获取一个字符串中间一部分字符的方法
2014/08/19 PHP
Yii中render和renderPartial的区别
2014/09/03 PHP
深入解析Laravel5.5中的包自动发现Package Auto Discovery
2017/09/13 PHP
直接生成打开窗口代码,不必下载
2008/05/14 Javascript
用Juery网页选项卡实现代码
2011/06/13 Javascript
javascript动态添加、修改、删除对象的属性与方法详解
2014/01/27 Javascript
调用innerHTML之后onclick失效问题的解决方法
2014/01/28 Javascript
javascript中局部变量和全局变量的区别详解
2015/02/27 Javascript
javascript实现简单的进度条
2015/07/02 Javascript
AngularJS入门教程之双向绑定详解
2016/08/18 Javascript
微信小程序技巧之show内容展示,上传文件编码问题
2017/01/23 Javascript
Node.js如何响应Ajax的POST请求并且保存为JSON文件详解
2017/03/10 Javascript
js 去掉字符串前后空格实现代码集合
2017/03/25 Javascript
通过webpack引入第三方库的方法
2018/07/20 Javascript
vue 登录滑动验证实现代码
2018/08/24 Javascript
微信小程序拼接图片链接无底洞深入探究
2019/09/03 Javascript
小谈angular ng deploy的实现
2020/04/07 Javascript
[05:06]TI4西雅图DOTA2前线报道 海涛密探LGD训练
2014/07/09 DOTA
Python中使用hashlib模块处理算法的教程
2015/04/28 Python
python OpenCV学习笔记直方图反向投影的实现
2018/02/07 Python
python调用OpenCV实现人脸识别功能
2018/05/25 Python
pycharm内无法import已安装的模块问题解决
2020/02/12 Python
Python图像处理库PIL的ImageFont模块使用介绍
2020/02/26 Python
浅谈django 重载str 方法
2020/05/19 Python
python初步实现word2vec操作
2020/06/09 Python
配件采购员岗位职责
2013/12/03 职场文书
优秀士兵先进事迹
2014/02/06 职场文书
设备动力科岗位职责范本
2014/02/23 职场文书
2014年预备党员学习新党章思想汇报
2014/09/15 职场文书
公司领导班子对照检查存在问题整改措施
2014/10/02 职场文书
解除施工合同协议书
2014/10/17 职场文书
2015学校年度工作总结
2015/05/11 职场文书
Tomcat starup.bat 脚本实现开机自启动
2022/04/20 Servers