在实际应用中,我们经常会需要采用if-elif-else控制语句以根据不同条件,作出不同的操作。if-elif-else固然可以,但是它也存在冗余的缺点,特别是当条件较多时这一缺点尤为明显。因此,本文考虑采用字典来处理这一情况。

Python的字典是由键值对构成,键是唯一的,并且每个键都有唯一的值对应。因此,我们可以将条件控制语句中的条件作为,将相应条件下的操作作为。如果“操作”较为复杂时,我们可以将其打包为一个函数,并将此函数作为字典的“值”。

举例如下:

import numpy as np
np.random.seed(1234)
true_label = np.random.choice(np.array([0,1]),
size=10000, p = [0.5, 0.5],
replace=True)
pred_prob = np.random.rand(10000) metric = 'precision'
perform = np.zeros_like(pred_prob)
for j, thres in enumerate(pred_prob):
pred_label = np.where(pred_prob>=thres, 1, 0)
if metric == 'recall':
perform[j] = np.logical_and(pred_label, true_label).sum()/true_label.sum()
elif metric == 'precision':
perform[j] = np.logical_and(pred_label, true_label).sum()/pred_label.sum()
elif metric == 'accuracy':
perform[j] = 1 - np.logical_xor(pred_label, true_label).sum()/pred_label.shape[0]

上述代码是利用条件控制语句,根据需要计算"召回率"、"精准率"、“准确率”,具体需要即由变量metric控制。与之对应的字典版本即为

def recall(pred_label, true_label):
return np.logical_and(pred_label, true_label).sum()/true_label.sum()
def precision(pred_label, true_label):
return np.logical_and(pred_label, true_label).sum()/pred_label.sum()
def accuracy(pred_label, true_label):
return 1 - np.logical_xor(pred_label, true_label).sum()/pred_label.shape[0] metric_dict = {'recall' : recall,
'precision': precision,
'accuracy' : accuracy}
metric = 'precision'
evalua = np.zeros_like(pred_prob)
for i, thres in enumerate(pred_prob):
pred_label = np.where(pred_prob>=thres, 1, 0)
evalua[i] = metric_dict.get(metric, None)(pred_label, true_label)

可以看到,条件控制语句中的操作被打包成了函数,并作为字典中的值。接下来根据键,对字典的值进行索取即可,而这里的键值即为条件,也由变量metric控制。

最新文章

  1. 深入理解this机制系列第一篇——this的4种绑定规则
  2. Eclipse调试 : step into,step over,step return 说明
  3. react native TextInput
  4. An invalid form control with name='' is not focusable.
  5. C# 中的 Static
  6. C# 缓存学习总结
  7. 【Java Tips】boolean的类型与string类型的转换
  8. stringstream 与空格 (大家讨论一下代码结果的原因)
  9. Android4.0设置接口变更摘要(四)
  10. Sql Sever语句 (续2)
  11. crossdomain 可用
  12. 跨域CORS
  13. ajax中的suceess函数使用this
  14. DeepLearning.ai学习笔记(二)改善深层神经网络:超参数调试、正则化以及优化--Week2优化算法
  15. jquery怎么选择嵌套的第一层的li
  16. https跨域到http问题解决
  17. Git使用教程:最详细、最傻瓜、最浅显、真正手把手教!
  18. javascript使用误区(switch、this)
  19. java正则表达式:验证字符串数字
  20. HDU_6033_Add More Zero

热门文章

  1. Vue2安装less版本过高问题,需要降级
  2. ImGui窗口标题栏的高度
  3. listview自定义适配器
  4. mysql转DM的日期函数转换
  5. 将python2.7项目转为Python3问题记录
  6. Column count doesn't match value count at row 1存储的数据与数据库表的字段类型定义不相匹配
  7. winfrom快捷键
  8. CF单机版终极猎手30人版安装教程
  9. 【Linux命令】在Linux服务器上与windows通过SCP命令互传文件时出现的问题排查过程
  10. case语法案例