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连接mongodb操作数据示例(mongodb数据库配置类)
Dec 31 Python
讲解Python中if语句的嵌套用法
May 14 Python
详解Python中的strftime()方法的使用
May 22 Python
Python中的字典与成员运算符初步探究
Oct 13 Python
Python执行时间的计算方法小结
Mar 17 Python
python的Crypto模块实现AES加密实例代码
Jan 22 Python
在python下使用tensorflow判断是否存在文件夹的实例
Jun 10 Python
Python学习笔记之Zip和Enumerate用法实例分析
Aug 14 Python
Django 404、500页面全局配置知识点详解
Mar 10 Python
python selenium操作cookie的实现
Mar 18 Python
撤回我也能看到!教你用Python制作微信防撤回脚本
Jun 11 Python
Python自动化测试PO模型封装过程详解
Jun 22 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/12/29 PHP
ThinkPHP采用GET方式获取中文参数查询无结果的解决方法
2014/06/26 PHP
PHP获取input输入框中的值去数据库比较显示出来
2016/11/16 PHP
PHP通过get方法获得form表单数据方法总结
2018/09/12 PHP
JS二维数组的定义说明
2014/03/03 Javascript
原生JavaScript生成GUID的实现示例
2014/09/05 Javascript
javascript如何操作HTML下拉列表标签
2015/08/20 Javascript
jquery对象访问是什么及使用方法介绍
2016/05/03 Javascript
AngularJS ng-controller 指令简单实例
2016/08/01 Javascript
jquery手机触屏滑动拼音字母城市选择器的实例代码
2017/12/11 jQuery
前端插件之Bootstrap Dual Listbox使用教程
2019/07/23 Javascript
Vue 实例事件简单示例
2019/09/19 Javascript
使用Python编写一个简单的tic-tac-toe游戏的教程
2015/04/16 Python
Python实现自动登录百度空间的方法
2017/06/10 Python
解决已经安装requests,却依然提示No module named requests问题
2018/05/18 Python
使用Python AIML搭建聊天机器人的方法示例
2018/07/09 Python
python树莓派红外反射传感器
2019/01/21 Python
python中如何使用分步式进程计算详解
2019/03/22 Python
详解pandas中MultiIndex和对象实际索引不一致问题
2019/07/23 Python
Python SELENIUM上传文件或图片实现过程
2019/10/28 Python
wxPython窗体拆分布局基础组件
2019/11/19 Python
在Python中预先初始化列表内容和长度的实现
2019/11/28 Python
Pytorch之Variable的用法
2019/12/31 Python
pycharm部署、配置anaconda环境的教程
2020/03/24 Python
pytorch实现查看当前学习率
2020/06/24 Python
数字漫画:comiXology
2020/06/13 全球购物
广州盈通面试题
2015/12/05 面试题
Java软件工程师综合面试题笔试题
2013/09/08 面试题
建筑工程实习自我鉴定
2013/09/19 职场文书
银行纠风工作实施方案
2014/06/08 职场文书
助学贷款贫困证明
2014/09/23 职场文书
党员“四风”方面存在问题及整改措施
2014/09/24 职场文书
社区党员群众路线教育实践活动心得体会
2014/11/03 职场文书
遇事可以测出您的见识与格局
2019/09/16 职场文书
CSS3实现列表无限滚动/轮播效果
2021/06/23 HTML / CSS
nginx之内存池的实现
2022/06/28 Servers