[{"data":1,"prerenderedAt":480},["ShallowReactive",2],{"content-query-cp2Bpeo32w":3},{"_path":4,"_dir":5,"_draft":6,"_partial":6,"_locale":7,"title":8,"description":9,"date":10,"cover":11,"type":12,"body":13,"_type":474,"_id":475,"_source":476,"_file":477,"_stem":478,"_extension":479},"/technology-blogs/zh/427","zh",false,"","技术干货 | 解决面试中80%问题，基于MindSpore实现AUC/ROC","ROC/AUC作为机器学习的评估指标非常重要，也是面试中经常出现的问题（80%都会问到）,现在想将自己的一些理解分享给大家，希望读完本篇可以彻底记住ROC/AUC的概念。","2021-03-27","https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2021/04/08/81f97a47699a46b39dd7dbe4c46e5382.png","technology-blogs",{"type":14,"children":15,"toc":465},"root",[16,24,30,35,40,49,54,59,64,69,76,81,106,113,126,131,136,141,146,151,156,161,166,171,178,183,188,193,198,203,209,217,222,229,237,242,249,262,267,274,285,290,297,303,308,327,338,343,354,359,366,373,378,384,394,399,407,415,420,428,434,442,446],{"type":17,"tag":18,"props":19,"children":21},"element","h1",{"id":20},"技术干货-解决面试中80问题基于mindspore实现aucroc",[22],{"type":23,"value":8},"text",{"type":17,"tag":25,"props":26,"children":27},"p",{},[28],{"type":23,"value":29},"ROC/AUC作为机器学习的评估指标非常重要，也是面试中经常出现的问题（80%都会问到）。其实，理解它并不是非常难，但是好多朋友都遇到了一个相同的问题，那就是：每次看书的时候都很明白，但回过头就忘了，经常容易将概念弄混。还有的朋友面试之前背下来了，但是一紧张大脑一片空白全忘了，导致回答的很差。",{"type":17,"tag":25,"props":31,"children":32},{},[33],{"type":23,"value":34},"我在之前的面试过程中也遇到过类似的问题，我的面试经验是：一般笔试题遇到选择题基本都会考这个率，那个率，或者给一个场景让你选用哪个。面试过程中也被问过很多次，比如什么是AUC/ROC？横轴纵轴都代表什么？有什么优点？为什么要使用它？",{"type":17,"tag":25,"props":36,"children":37},{},[38],{"type":23,"value":39},"我记得在我第一次回答的时候，我将准确率，精准率，召回率等概念混淆了，最后一团乱。回去以后我从头到尾梳理了一遍所有相关概念，后面的面试基本都回答地很好。现在想将自己的一些理解分享给大家，希望读完本篇可以彻底记住ROC/AUC的概念。",{"type":17,"tag":25,"props":41,"children":42},{},[43],{"type":17,"tag":44,"props":45,"children":48},"img",{"alt":46,"src":47},"image.png","https://bbs-img-cbc-cn.obs.cn-north-1.myhuaweicloud.com/data/forums/attachment/forum/202103/26/231449xvyiqjpfu0ivvvu5.png",[],{"type":17,"tag":25,"props":50,"children":51},{},[52],{"type":23,"value":53},"先来段引用",{"type":17,"tag":25,"props":55,"children":56},{},[57],{"type":23,"value":58},"ROC的全名叫做Receiver Operating Characteristic，其主要分析工具是一个画在二维平面上的曲线——ROC 曲线。平面的横坐标是false positive rate(FPR)，纵坐标是true positive rate(TPR)。对某个分类器而言，我们可以根据其在测试样本上的表现得到一个TPR和FPR点对。这样，此分类器就可以映射成ROC平面上的一个点。调整这个分类器分类时候使用的阈值，我们就可以得到一个经过(0, 0)，(1, 1)的曲线，这就是此分类器的ROC曲线。一般情况下，这个曲线都应该处于(0, 0)和(1, 1)连线的上方。因为(0, 0)和(1, 1)连线形成的ROC曲线实际上代表的是一个随机分类器。如果很不幸，你得到一个位于此直线下方的分类器的话，一个直观的补救办法就是把所有的预测结果反向，即：分类器输出结果为正类，则最终分类的结果为负类，反之，则为正类。虽然，用ROC 曲线来表示分类器的性能很直观好用。",{"type":17,"tag":25,"props":60,"children":61},{},[62],{"type":23,"value":63},"可是，人们总是希望能有一个数值来标志分类器的好坏。于是Area Under roc Curve(AUC)就出现了。顾名思义，AUC的值就是处于ROC 曲线下方的那部分面积的大小。通常，AUC的值介于0.5到1.0之间，较大的AUC代表了较好的性能。AUC（Area Under roc Curve）是一种用来度量分类模型好坏的一个标准。",{"type":17,"tag":25,"props":65,"children":66},{},[67],{"type":23,"value":68},"ROC示例曲线（二分类问题）：",{"type":17,"tag":25,"props":70,"children":71},{},[72],{"type":17,"tag":44,"props":73,"children":75},{"alt":46,"src":74},"https://bbs-img-cbc-cn.obs.cn-north-1.myhuaweicloud.com/data/forums/attachment/forum/202103/26/231531er3hhw5czsqbrwtz.png",[],{"type":17,"tag":25,"props":77,"children":78},{},[79],{"type":23,"value":80},"解读ROC图的一些概念定义：",{"type":17,"tag":82,"props":83,"children":84},"ul",{},[85,91,96,101],{"type":17,"tag":86,"props":87,"children":88},"li",{},[89],{"type":23,"value":90},"真正（True Positive , TP）被模型预测为正的正样本；",{"type":17,"tag":86,"props":92,"children":93},{},[94],{"type":23,"value":95},"假负（False Negative , FN）被模型预测为负的正样本；",{"type":17,"tag":86,"props":97,"children":98},{},[99],{"type":23,"value":100},"假正（False Positive , FP）被模型预测为正的负样本；",{"type":17,"tag":86,"props":102,"children":103},{},[104],{"type":23,"value":105},"真负（True Negative , TN）被模型预测为负的负样本。",{"type":17,"tag":107,"props":108,"children":110},"h2",{"id":109},"灵敏度特异度真正率假正率",[111],{"type":23,"value":112},"灵敏度，特异度，真正率，假正率",{"type":17,"tag":25,"props":114,"children":115},{},[116,118,124],{"type":23,"value":117},"在正式介绍ROC/AUC之前，我们需要介绍两个指标，这两个指标的选择也正是",{"type":17,"tag":119,"props":120,"children":121},"strong",{},[122],{"type":23,"value":123},"ROC和AUC可以无视样本不平衡的原因",{"type":23,"value":125},"。这两个指标分别是：灵敏度和（1-特异度），也叫做真正率（TPR）和假正率（FPR）。",{"type":17,"tag":25,"props":127,"children":128},{},[129],{"type":23,"value":130},"灵敏度（Sensitivity） = TP/(TP+FN)",{"type":17,"tag":25,"props":132,"children":133},{},[134],{"type":23,"value":135},"特异度（Specificity） = TN/(FP+TN)",{"type":17,"tag":25,"props":137,"children":138},{},[139],{"type":23,"value":140},"其实我们可以发现灵敏度和召回率是一模一样的，只是名字换了而已。",{"type":17,"tag":25,"props":142,"children":143},{},[144],{"type":23,"value":145},"由于我们比较关心正样本，所以需要查看有多少负样本被错误地预测为正样本，所以使用（1-特异度），而不是特异度。",{"type":17,"tag":25,"props":147,"children":148},{},[149],{"type":23,"value":150},"真正率（TPR） = 灵敏度 = TP/(TP+FN)",{"type":17,"tag":25,"props":152,"children":153},{},[154],{"type":23,"value":155},"假正率（FPR） = 1- 特异度 = FP/(FP+TN)",{"type":17,"tag":25,"props":157,"children":158},{},[159],{"type":23,"value":160},"下面是真正率和假正率的示意，我们发现TPR和FPR分别是基于实际表现1和0出发的，也就是说它们分别在实际的正样本和负样本中来观察相关概率问题。",{"type":17,"tag":25,"props":162,"children":163},{},[164],{"type":23,"value":165},"正因为如此，所以无论样本是否平衡，都不会被影响。比如总样本中，90%是正样本，10%是负样本。我们知道用准确率是有水分的，但是用TPR和FPR不一样。这里，TPR只关注90%正样本中有多少是被真正覆盖的，而与那10%毫无关系，同理，FPR只关注10%负样本中有多少是被错误覆盖的，也与那90%毫无关系，所以可以看出：",{"type":17,"tag":25,"props":167,"children":168},{},[169],{"type":23,"value":170},"如果我们从实际表现的各个结果角度出发，就可以避免样本不平衡的问题了，这也是为什么选用TPR和FPR作为ROC/AUC的指标的原因。",{"type":17,"tag":25,"props":172,"children":173},{},[174],{"type":17,"tag":44,"props":175,"children":177},{"alt":46,"src":176},"https://bbs-img-cbc-cn.obs.cn-north-1.myhuaweicloud.com/data/forums/attachment/forum/202103/26/231627omdt0kprv8lwilvs.png",[],{"type":17,"tag":25,"props":179,"children":180},{},[181],{"type":23,"value":182},"或者我们也可以从另一个角度考虑：条件概率。我们假设X为预测值，Y为真实值。那么就可以将这些指标按条件概率表示：",{"type":17,"tag":25,"props":184,"children":185},{},[186],{"type":23,"value":187},"精准率 = P（Y=1 | X=1）",{"type":17,"tag":25,"props":189,"children":190},{},[191],{"type":23,"value":192},"召回率 = 灵敏度 = P（X=1 | Y=1）",{"type":17,"tag":25,"props":194,"children":195},{},[196],{"type":23,"value":197},"特异度 = P（X=0 | Y=0）",{"type":17,"tag":25,"props":199,"children":200},{},[201],{"type":23,"value":202},"从上面三个公式看到：如果我们先以实际结果为条件（召回率，特异度），那么就只需考虑一种样本，而先以预测值为条件（精准率），那么我们需要同时考虑正样本和负样本。所以先以实际结果为条件的指标都不受样本不平衡的影响，相反以预测结果为条件的就会受到影响。",{"type":17,"tag":107,"props":204,"children":206},{"id":205},"roc接受者操作特征曲线",[207],{"type":23,"value":208},"ROC（接受者操作特征曲线）",{"type":17,"tag":25,"props":210,"children":211},{},[212],{"type":17,"tag":119,"props":213,"children":214},{},[215],{"type":23,"value":216},"ROC（Receiver Operating Characteristic）曲线，又称接受者操作特征曲线。该曲线最早应用于雷达信号检测领域，用于区分信号与噪声。后来人们将其用于评价模型的预测能力，ROC曲线是基于混淆矩阵得出的。",{"type":17,"tag":25,"props":218,"children":219},{},[220],{"type":23,"value":221},"ROC曲线中的主要两个指标就是真正率和假正率，上面也解释了这么选择的好处所在。其中横坐标为假正率（FPR），纵坐标为真正率（TPR），下面就是一个标准的ROC曲线图。",{"type":17,"tag":25,"props":223,"children":224},{},[225],{"type":17,"tag":44,"props":226,"children":228},{"alt":46,"src":227},"https://bbs-img-cbc-cn.obs.cn-north-1.myhuaweicloud.com/data/forums/attachment/forum/202103/26/231710g4zoucxsd214qcvp.png",[],{"type":17,"tag":82,"props":230,"children":231},{},[232],{"type":17,"tag":86,"props":233,"children":234},{},[235],{"type":23,"value":236},"ROC曲线的阈值问题",{"type":17,"tag":25,"props":238,"children":239},{},[240],{"type":23,"value":241},"与前面的P-R曲线类似，ROC曲线也是通过遍历所有阈值来绘制整条曲线的。如果我们不断的遍历所有阈值，预测的正样本和负样本是在不断变化的，相应的在ROC曲线图中也会沿着曲线滑动。",{"type":17,"tag":25,"props":243,"children":244},{},[245],{"type":17,"tag":44,"props":246,"children":248},{"alt":46,"src":247},"https://bbs-img-cbc-cn.obs.cn-north-1.myhuaweicloud.com/data/forums/attachment/forum/202103/26/231742lrob9qrjkhp90mgd.png",[],{"type":17,"tag":82,"props":250,"children":251},{},[252],{"type":17,"tag":86,"props":253,"children":254},{},[255,260],{"type":17,"tag":119,"props":256,"children":257},{},[258],{"type":23,"value":259},"如何判断ROC曲线的好坏",{"type":23,"value":261},"？",{"type":17,"tag":25,"props":263,"children":264},{},[265],{"type":23,"value":266},"改变阈值只是不断地改变预测的正负样本数，即TPR和FPR，但是曲线本身是不会变的。那么如何判断一个模型的ROC曲线是好的呢？这个还是要回归到我们的目的：FPR表示模型虚报的响应程度，而TPR表示模型预测响应的覆盖程度。我们所希望的当然是：虚报的越少越好，覆盖的越多越好。所以总结一下就是TPR越高，同时FPR越低（即ROC曲线越陡），那么模型的性能就越好。参考如下动态图进行理解。",{"type":17,"tag":25,"props":268,"children":269},{},[270],{"type":17,"tag":44,"props":271,"children":273},{"alt":46,"src":272},"https://bbs-img-cbc-cn.obs.cn-north-1.myhuaweicloud.com/data/forums/attachment/forum/202103/26/231817v1teqoc5uknonc2n.png",[],{"type":17,"tag":82,"props":275,"children":276},{},[277],{"type":17,"tag":86,"props":278,"children":279},{},[280],{"type":17,"tag":119,"props":281,"children":282},{},[283],{"type":23,"value":284},"ROC曲线无视样本不平衡",{"type":17,"tag":25,"props":286,"children":287},{},[288],{"type":23,"value":289},"前面已经对ROC曲线为什么可以无视样本不平衡做了解释，下面我们用动态图的形式再次展示一下它是如何工作的。我们发现：无论红蓝色样本比例如何改变，ROC曲线都没有影响。",{"type":17,"tag":25,"props":291,"children":292},{},[293],{"type":17,"tag":44,"props":294,"children":296},{"alt":46,"src":295},"https://bbs-img-cbc-cn.obs.cn-north-1.myhuaweicloud.com/data/forums/attachment/forum/202103/26/231854py4somrgyzupxdwl.png",[],{"type":17,"tag":107,"props":298,"children":300},{"id":299},"auc曲线下的面积",[301],{"type":23,"value":302},"AUC（曲线下的面积）",{"type":17,"tag":25,"props":304,"children":305},{},[306],{"type":23,"value":307},"为了计算 ROC 曲线上的点，我们可以使用不同的分类阈值多次评估逻辑回归模型，但这样做效率非常低。幸运的是，有一种基于排序的高效算法可以为我们提供此类信息，这种算法称为曲线下面积（Area Under Curve）。",{"type":17,"tag":25,"props":309,"children":310},{},[311,313,318,320,325],{"type":23,"value":312},"比较有意思的是，如果我们连接对角线，它的面积正好是0.5。对角线的实际含义是：随机判断响应与不响应，",{"type":17,"tag":119,"props":314,"children":315},{},[316],{"type":23,"value":317},"正负样本覆盖率应该都是50%",{"type":23,"value":319},"，表示",{"type":17,"tag":119,"props":321,"children":322},{},[323],{"type":23,"value":324},"随机效果",{"type":23,"value":326},"。ROC曲线越陡越好，所以理想值就是1，一个正方形，而最差的随机判断都有0.5，所以一般AUC的值是介于0.5到1之间的。",{"type":17,"tag":82,"props":328,"children":329},{},[330],{"type":17,"tag":86,"props":331,"children":332},{},[333],{"type":17,"tag":119,"props":334,"children":335},{},[336],{"type":23,"value":337},"AUC的一般判断标准",{"type":17,"tag":25,"props":339,"children":340},{},[341],{"type":23,"value":342},"0.5 - 0.7：效果较低，但用于预测股票已经很不错了0.7 - 0.85：效果一般0.85 - 0.95：效果很好0.95 - 1：效果非常好，但一般不太可能",{"type":17,"tag":82,"props":344,"children":345},{},[346],{"type":17,"tag":86,"props":347,"children":348},{},[349],{"type":17,"tag":119,"props":350,"children":351},{},[352],{"type":23,"value":353},"AUC的物理意义",{"type":17,"tag":25,"props":355,"children":356},{},[357],{"type":23,"value":358},"曲线下面积对所有可能的分类阈值的效果进行综合衡量。曲线下面积的一种解读方式是看作模型将某个随机正类别样本排列在某个随机负类别样本之上的概率。以下面的样本为例，逻辑回归预测从左到右以升序排列：",{"type":17,"tag":25,"props":360,"children":361},{},[362],{"type":17,"tag":44,"props":363,"children":365},{"alt":46,"src":364},"https://bbs-img-cbc-cn.obs.cn-north-1.myhuaweicloud.com/data/forums/attachment/forum/202103/26/231936pgd5q8pxs7k8qehl.png",[],{"type":17,"tag":25,"props":367,"children":368},{},[369],{"type":17,"tag":44,"props":370,"children":372},{"alt":46,"src":371},"https://bbs-img-cbc-cn.obs.cn-north-1.myhuaweicloud.com/data/forums/attachment/forum/202103/26/232008evhnmuwshipv0anp.png",[],{"type":17,"tag":25,"props":374,"children":375},{},[376],{"type":23,"value":377},"好了，原理已经讲完，上MindSpore框架的代码。",{"type":17,"tag":107,"props":379,"children":381},{"id":380},"mindspore代码实现roc",[382],{"type":23,"value":383},"MindSpore代码实现（ROC）",{"type":17,"tag":385,"props":386,"children":388},"pre",{"code":387},"\"\"\"ROC\"\"\"\nimport numpy as np\nfrom mindspore._checkparam import Validator as validator\nfrom .metric import Metric\nclass ROC(Metric):\n     \n    def __init__(self, class_num=None, pos_label=None):\n        super().__init__()\n        # 分类数为一个整数\n        self.class_num = class_num if class_num is None else validator.check_value_type(\"class_num\", class_num, [int])\n        # 确定正类的整数，对于二分类问题，它被转换为1。对于多分类问题，不应设置此参数，因为它在[0，num_classes-1]范围内迭代更改。\n        self.pos_label = pos_label if pos_label is None else validator.check_value_type(\"pos_label\", pos_label, [int])\n        self.clear()\n    def clear(self):\n        \"\"\"清除历史数据\"\"\"\n        self.y_pred = 0\n        self.y = 0\n        self.sample_weights = None\n        self._is_update = False\n    def _precision_recall_curve_update(self, y_pred, y, class_num, pos_label):\n        \"\"\"更新曲线\"\"\"\n        if not (len(y_pred.shape) == len(y.shape) or len(y_pred.shape) == len(y.shape) + 1):\n            raise ValueError(\"y_pred and y must have the same number of dimensions, or one additional dimension for\"\n                             \" y_pred.\")\n        # 二分类验证\n        if len(y_pred.shape) == len(y.shape):\n            if class_num is not None and class_num != 1:\n                raise ValueError('y_pred and y should have the same shape, but number of classes is different from 1.')\n            class_num = 1\n            if pos_label is None:\n                pos_label = 1\n            y_pred = y_pred.flatten()\n            y = y.flatten()\n        # 多分类验证\n        elif len(y_pred.shape) == len(y.shape) + 1:\n            if pos_label is not None:\n                raise ValueError('Argument `pos_label` should be `None` when running multiclass precision recall '\n                                 'curve, but got {}.'.format(pos_label))\n            if class_num != y_pred.shape[1]:\n                raise ValueError('Argument `class_num` was set to {}, but detected {} number of classes from '\n                                 'predictions.'.format(class_num, y_pred.shape[1]))\n            y_pred = y_pred.transpose(0, 1).reshape(class_num, -1).transpose(0, 1)\n            y = y.flatten()\n        return y_pred, y, class_num, pos_label\n    def update(self, *inputs):\n        \"\"\"\n        更新预测值和真实值。\n        \"\"\"\n        # 输入数量的校验\n        if len(inputs) != 2:\n            raise ValueError('ROC need 2 inputs (y_pred, y), but got {}'.format(len(inputs)))\n        # 将输入转为numpy\n        y_pred = self._convert_data(inputs[0])\n        y = self._convert_data(inputs[1])\n        # 更新曲线\n        y_pred, y, class_num, pos_label = self._precision_recall_curve_update(y_pred, y, self.class_num, self.pos_label)\n        self.y_pred = y_pred\n        self.y = y\n        self.class_num = class_num\n        self.pos_label = pos_label\n        self._is_update = True\n    def _roc_(self, y_pred, y, class_num, pos_label, sample_weights=None):\n        if class_num == 1:\n            fps, tps, thresholds = self._binary_clf_curve(y_pred, y, sample_weights=sample_weights,\n                                                          pos_label=pos_label)\n            tps = np.squeeze(np.hstack([np.zeros(1, dtype=tps.dtype), tps]))\n            fps = np.squeeze(np.hstack([np.zeros(1, dtype=fps.dtype), fps]))\n            thresholds = np.hstack([thresholds[0][None] + 1, thresholds])\n            if fps[-1] \u003C= 0:\n                raise ValueError(\"No negative samples in y, false positive value should be meaningless.\")\n            fpr = fps / fps[-1]\n            if tps[-1] \u003C= 0:\n                raise ValueError(\"No positive samples in y, true positive value should be meaningless.\")\n            tpr = tps / tps[-1]\n            return fpr, tpr, thresholds\n         \n        # 定义三个列表\n        fpr, tpr, thresholds = [], [], []\n        for c in range(class_num):\n            preds_c = y_pred[:, c]\n            res = self.roc(preds_c, y, class_num=1, pos_label=c, sample_weights=sample_weights)\n            fpr.append(res[0])\n            tpr.append(res[1])\n            thresholds.append(res[2])\n        return fpr, tpr, thresholds\n    def roc(self, y_pred, y, class_num=None, pos_label=None, sample_weights=None):\n        \"\"\"roc\"\"\"\n        y_pred, y, class_num, pos_label = self._precision_recall_curve_update(y_pred, y, class_num, pos_label)\n        return self._roc_(y_pred, y, class_num, pos_label, sample_weights)\n    def (self):\n        \"\"\"\n        计算ROC曲线。返回的是一个元组，由`fpr`、 `tpr`和 `thresholds`组成的元组。\n        \"\"\"\n        if self._is_update is False:\n            raise RuntimeError('Call the update method before calling .')\n        y_pred = np.squeeze(np.vstack(self.y_pred))\n        y = np.squeeze(np.vstack(self.y))\n        return self._roc_(y_pred, y, self.class_num, self.pos_label)\n",[389],{"type":17,"tag":390,"props":391,"children":392},"code",{"__ignoreMap":7},[393],{"type":23,"value":387},{"type":17,"tag":25,"props":395,"children":396},{},[397],{"type":23,"value":398},"使用方法如下：",{"type":17,"tag":82,"props":400,"children":401},{},[402],{"type":17,"tag":86,"props":403,"children":404},{},[405],{"type":23,"value":406},"二分类的例子",{"type":17,"tag":385,"props":408,"children":410},{"code":409},"import numpy as np\nfrom mindspore import Tensor\nfrom mindspore.nn.metrics import ROC\n# binary classification example\nx = Tensor(np.array([3, 1, 4, 2]))\ny = Tensor(np.array([0, 1, 2, 3]))\nmetric = ROC(pos_label=2)\nmetric.clear()\nmetric.update(x, y)\nfpr, tpr, thresholds = metric.()\nprint(fpr, tpr, thresholds)\n[0., 0., 0.33333333, 0.6666667, 1.]\n[0., 1, 1., 1., 1.]\n[5, 4, 3, 2, 1]\n",[411],{"type":17,"tag":390,"props":412,"children":413},{"__ignoreMap":7},[414],{"type":23,"value":409},{"type":17,"tag":25,"props":416,"children":417},{},[418],{"type":23,"value":419},"多分类的例子",{"type":17,"tag":385,"props":421,"children":423},{"code":422},"import numpy as np\nfrom mindspore import Tensor\nfrom mindspore.nn.metrics import ROC\n# multiclass classification example\nx = Tensor(np.array([[0.28, 0.55, 0.15, 0.05], [0.10, 0.20, 0.05, 0.05], [0.20, 0.05, 0.15, 0.05],0.05, 0.05, 0.05, 0.75]]))\ny = Tensor(np.array([0, 1, 2, 3]))\nmetric = ROC(class_num=4)\nmetric.clear()\nmetric.update(x, y)\nfpr, tpr, thresholds = metric.()\nprint(fpr, tpr, thresholds)\n[array([0., 0., 0.33333333, 0.66666667, 1.]), array([0., 0.33333333, 0.33333333, 1.]), array([0., 0.33333333, 1.]), array([0., 0., 1.])]\n[array([0., 1., 1., 1., 1.]), array([0., 0., 1., 1.]), array([0., 1., 1.]), array([0., 1., 1.])]\n[array([1.28, 0.28, 0.2, 0.1, 0.05]), array([1.55, 0.55, 0.2, 0.05]), array([1.15, 0.15, 0.05]), array([1.75, 0.75, 0.05])]\n",[424],{"type":17,"tag":390,"props":425,"children":426},{"__ignoreMap":7},[427],{"type":23,"value":422},{"type":17,"tag":107,"props":429,"children":431},{"id":430},"mindspore代码实现auc",[432],{"type":23,"value":433},"MindSpore代码实现（AUC）",{"type":17,"tag":385,"props":435,"children":437},{"code":436},"\"\"\"auc\"\"\"\nimport numpy as np\ndef auc(x, y, reorder=False):\n    \"\"\"\n    使用梯形法则计算曲线下面积（AUC）。这是一个一般函数，给定曲线上的点。计算ROC曲线下的面积。\n    \"\"\"\n    # 输入x是由ROC曲线得到的fpr值或者一个假阳性numpy数组。如果是多类的，这是一个这样的list numpy，每组代表一类。\n    # 输入y是由ROC曲线得到的tpr值或者一个真阳性numpy数组。如果是多类的，这是一个这样的list numpy，每组代表一类。\n    if not isinstance(x, np.ndarray) or not isinstance(y, np.ndarray):\n        raise TypeError('The inputs must be np.ndarray, but got {}, {}'.format(type(x), type(y)))\n    # 检查所有数组的第一个维度是否一致。检查数组中的所有对象是否具有相同的形状或长度。\n    _check_consistent_length(x, y)\n    # 展开列或1d numpy数组。\n    x = _column_or_1d(x)\n    y = _column_or_1d(y)\n     \n    # 进行校验\n    if x.shape[0] \u003C 2:\n        raise ValueError('At least 2 points are needed to compute the AUC, but x.shape = {}.'.format(x.shape))\n    direction = 1\n    if reorder:\n        order = np.lexsort((y, x))\n        x, y = x[order], y[order]\n    else:\n        dx = np.diff(x)\n        if np.any(dx \u003C 0):\n            if np.all(dx  1:\n        raise ValueError(\"Found input variables with inconsistent numbers of samples: {}.\"\n                         .format([int(length) for length in lengths]))\n",[438],{"type":17,"tag":390,"props":439,"children":440},{"__ignoreMap":7},[441],{"type":23,"value":436},{"type":17,"tag":25,"props":443,"children":444},{},[445],{"type":23,"value":398},{"type":17,"tag":82,"props":447,"children":448},{},[449,454],{"type":17,"tag":86,"props":450,"children":451},{},[452],{"type":23,"value":453},"利用ROC的fpr， tpr值求auc",{"type":17,"tag":86,"props":455,"children":456},{},[457],{"type":17,"tag":385,"props":458,"children":460},{"code":459},"import numpy as np\nfrom mindspore.nn.metrics import auc\nx = Tensor(np.array([[3, 0, 1], [1, 3, 0], [1, 0, 2]]))\ny = Tensor(np.array([[0, 2, 1], [1, 2, 1], [0, 0, 1]]))\nmetric = ROC(pos_label=1)\nmetric.clear()\nmetric.update(x, y)\nfpr, tpr, thre = metric.eval()\n# 利用ROC的fpr， tpr值求auc\noutput = auc(fpr, tpr)\nprint(output)\n0.45\n",[461],{"type":17,"tag":390,"props":462,"children":463},{"__ignoreMap":7},[464],{"type":23,"value":459},{"title":7,"searchDepth":466,"depth":466,"links":467},4,[468,470,471,472,473],{"id":109,"depth":469,"text":112},2,{"id":205,"depth":469,"text":208},{"id":299,"depth":469,"text":302},{"id":380,"depth":469,"text":383},{"id":430,"depth":469,"text":433},"markdown","content:technology-blogs:zh:427.md","content","technology-blogs/zh/427.md","technology-blogs/zh/427","md",1776506137313]