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列表推导式的使用方法
Nov 21 Python
在Mac OS上部署Nginx和FastCGI以及Flask框架的教程
May 02 Python
python爬虫入门教程--HTML文本的解析库BeautifulSoup(四)
May 25 Python
详解tensorflow载入数据的三种方式
Apr 24 Python
Python实现绘制双柱状图并显示数值功能示例
Jun 23 Python
Python使用itchat模块实现群聊转发,自动回复功能示例
Aug 26 Python
Python实现随机生成任意数量车牌号
Jan 21 Python
Python3 hashlib密码散列算法原理详解
Mar 30 Python
如何使用Cython对python代码进行加密
Jul 08 Python
Python configparser模块应用过程解析
Aug 14 Python
基于python实现复制文件并重命名
Sep 16 Python
python中PyQuery库用法分享
Jan 15 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+javascript的日历控件
2009/11/19 PHP
php切割页面div内容的实现代码分享
2012/07/31 PHP
PHP实现微信公众平台音乐点播
2014/03/20 PHP
javascript 冒号 使用说明
2009/06/06 Javascript
JS判断元素为数字的奇异写法分享
2012/08/01 Javascript
jQuery方法简洁实现隔行换色及toggleClass的使用
2013/03/15 Javascript
js编写一个简单的产品放大效果代码
2016/06/27 Javascript
jQuery on()方法绑定动态元素的点击事件无响应的解决办法
2016/07/07 Javascript
JS完成画圆圈的小球
2017/03/07 Javascript
Bootstrap Table快速完美搭建后台管理系统
2017/09/20 Javascript
Vue.js通用应用框架-Nuxt.js的上手教程
2017/12/25 Javascript
JS实现运动缓冲效果的封装函数示例
2018/02/18 Javascript
js实现点击图片在屏幕中间弹出放大效果
2019/09/11 Javascript
vue 解决setTimeOut和setInterval函数无效报错的问题
2020/07/30 Javascript
vue中的.$mount('#app')手动挂载操作
2020/09/02 Javascript
[03:07]【DOTA2亚洲邀请赛】我们,梦开始的地方
2017/03/07 DOTA
[01:00]一分钟回顾2018DOTA2亚洲邀请赛现场活动
2018/04/07 DOTA
Python安装第三方库的3种方法
2015/06/21 Python
Python聚类算法之凝聚层次聚类实例分析
2015/11/20 Python
Python复数属性和方法运算操作示例
2017/07/21 Python
Python下调用Linux的Shell命令的方法
2018/06/12 Python
关于Python3 类方法、静态方法新解
2019/08/30 Python
Pycharm插件(Grep Console)自定义规则输出颜色日志的方法
2020/05/27 Python
用CSS3实现瀑布流布局的示例代码
2017/11/10 HTML / CSS
html2canvas把div保存图片高清图的方法示例
2018/03/05 HTML / CSS
应届生服装设计自我评价
2013/09/20 职场文书
个人实用的自我评价范文
2013/11/23 职场文书
医药代表个人的求职信分享
2013/12/08 职场文书
土建资料员岗位职责
2014/01/04 职场文书
20岁生日感言
2014/01/13 职场文书
2014财务年度工作总结
2014/11/11 职场文书
2014年乡镇卫生院工作总结
2014/11/24 职场文书
2015教师节通讯稿
2015/07/20 职场文书
《最后一头战象》读后感:动物也有感情
2020/01/02 职场文书
Python字符串对齐方法使用(ljust()、rjust()和center())
2021/04/26 Python
Android基于Fresco实现圆角和圆形图片
2022/04/01 Java/Android