[{"data":1,"prerenderedAt":283},["ShallowReactive",2],{"content-query-12jqTWYz38":3},{"_path":4,"_dir":5,"_draft":6,"_partial":6,"_locale":7,"title":8,"description":9,"date":10,"cover":11,"type":12,"state":13,"body":14,"_type":277,"_id":278,"_source":279,"_file":280,"_stem":281,"_extension":282},"/activities/zh/402","zh",false,"","跟着MindSpore闹元宵：涨知识，练舞蹈，领礼品！","小伙伴们元宵节快乐呀，无论在哪儿过节都要记得好好爱自己哦~","2021-02-26","https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2021/02/26/f7df990682dd4e4a9dd38bb66da98635.png","activities",1,{"type":15,"children":16,"toc":270},"root",[17,25,30,35,44,49,79,86,91,96,108,113,127,134,146,151,155,162,167,172,184,190,209,216,221,227,237,242,250,255],{"type":18,"tag":19,"props":20,"children":22},"element","h1",{"id":21},"跟着mindspore闹元宵涨知识练舞蹈领礼品",[23],{"type":24,"value":8},"text",{"type":18,"tag":26,"props":27,"children":28},"p",{},[29],{"type":24,"value":9},{"type":18,"tag":26,"props":31,"children":32},{},[33],{"type":24,"value":34},"跟大家同步一个好消息！",{"type":18,"tag":26,"props":36,"children":37},{},[38],{"type":18,"tag":39,"props":40,"children":43},"img",{"alt":41,"src":42},"image.png","https://bbs-img-cbc-cn.obs.cn-north-1.myhuaweicloud.com/data/forums/attachment/forum/202102/26/125153biraq5lw4kr4c5pr.png",[],{"type":18,"tag":26,"props":45,"children":46},{},[47],{"type":24,"value":48},"图 『MindSpore抖音舞蹈接力赛』最新进展",{"type":18,"tag":26,"props":50,"children":51},{},[52,54,60,62,77],{"type":24,"value":53},"由于许多想参与『MindSpore抖音舞蹈接力赛』的小伙伴反馈需要多点时间来练习，用最美的舞姿参赛，MindSpore社区经过深思熟虑，决定应该鼓励大家积极锻炼努力完成目标的心愿，",{"type":18,"tag":55,"props":56,"children":57},"strong",{},[58],{"type":24,"value":59},"『MindSpore抖音舞蹈接力赛』活动延长至2021年3月14日",{"type":24,"value":61},"，并将在3月15日进入公众号全网拉票活动，投票数排名第一的将获得",{"type":18,"tag":55,"props":63,"children":64},{},[65,67,75],{"type":24,"value":66},"第一届MindSpore舞王称号",{"type":18,"tag":55,"props":68,"children":69},{},[70],{"type":18,"tag":55,"props":71,"children":72},{},[73],{"type":24,"value":74},"和",{"type":24,"value":76},"价值1000+的****MindSpore 定制机械键盘礼品",{"type":24,"value":78},"！",{"type":18,"tag":26,"props":80,"children":81},{},[82],{"type":18,"tag":39,"props":83,"children":85},{"alt":41,"src":84},"https://bbs-img-cbc-cn.obs.cn-north-1.myhuaweicloud.com/data/forums/attachment/forum/202102/26/125252wzliisz0lswhmkwj.png",[],{"type":18,"tag":26,"props":87,"children":88},{},[89],{"type":24,"value":90},"动作简单易学，既能减去多余的赘肉，又能赢得荣誉，来跟着小孢子一起舞起来吧！",{"type":18,"tag":26,"props":92,"children":93},{},[94],{"type":24,"value":95},"参与方式如下↓",{"type":18,"tag":26,"props":97,"children":98},{},[99],{"type":18,"tag":100,"props":101,"children":105},"a",{"href":102,"rel":103},"https://mp.weixin.qq.com/s?__biz=MzAxMDA1MDM0NQ==&mid=2247510444&idx=2&sn=cb455da69def0d87567925121418cee1&chksm=9b54a7eaac232efc5c52b84a82e4acae0d1345b9a0e97c15a08aa4052315c6a0d30cd4101445&scene=21#wechat_redirect",[104],"nofollow",[106],{"type":24,"value":107},"干饭人动起来！一起锻炼赢机械键盘啦！",{"type":18,"tag":26,"props":109,"children":110},{},[111],{"type":24,"value":112},"今天给大家带来的技术干货文章是Occlusion Sensitivity这个评价指标。",{"type":18,"tag":114,"props":115,"children":116},"blockquote",{},[117,122],{"type":18,"tag":26,"props":118,"children":119},{},[120],{"type":24,"value":121},"本文来源于：知乎",{"type":18,"tag":26,"props":123,"children":124},{},[125],{"type":24,"value":126},"作者：李嘉琪",{"type":18,"tag":26,"props":128,"children":129},{},[130],{"type":18,"tag":39,"props":131,"children":133},{"alt":41,"src":132},"https://bbs-img-cbc-cn.obs.cn-north-1.myhuaweicloud.com/data/forums/attachment/forum/202102/26/125336j9qtm38rpxyxmmrg.png",[],{"type":18,"tag":26,"props":135,"children":136},{},[137,139],{"type":24,"value":138},"Occlusion Sensitivity来源于论文《Visualizing and Understanding Convolutional Networks》ECCV’14. （",{"type":18,"tag":100,"props":140,"children":143},{"href":141,"rel":142},"https://ieeexplore.ieee.org/document/8237336%EF%BC%89%E3%80%82",[104],[144],{"type":24,"value":145},"https://ieeexplore.ieee.org/document/8237336）。",{"type":18,"tag":26,"props":147,"children":148},{},[149],{"type":24,"value":150},"Birju正在阅读一篇关于卷积神经网络可视化技术的论文，在其中他遇到了遮挡敏感的想法。如果您遮挡或遮挡图像的一部分，这将如何影响网络的概率得分？以及结果如何取决于您遮挡的那一部分？",{"type":18,"tag":26,"props":152,"children":153},{},[154],{"type":24,"value":150},{"type":18,"tag":156,"props":157,"children":159},"h2",{"id":158},"occlusion-sensitivity-原理定义",[160],{"type":24,"value":161},"Occlusion Sensitivity 原理定义",{"type":18,"tag":26,"props":163,"children":164},{},[165],{"type":24,"value":166},"在训练一个神经网络进行图片分类的时候，我们希望知道这个模型是能够定位出图片中主要目标的位置来进行分类，或只是通过一些周边的context来进行分类。",{"type":18,"tag":26,"props":168,"children":169},{},[170],{"type":24,"value":171},"通过对图片进行部分遮挡来观察输入修改后的图片后，网络中间层的情况以及预测值的变化。这个可以有助于理解为什么网络会做出某些决策。",{"type":18,"tag":26,"props":173,"children":174},{},[175,177,182],{"type":24,"value":176},"所以我们可以得出一个具体的定义：",{"type":18,"tag":55,"props":178,"children":179},{},[180],{"type":24,"value":181},"遮挡敏感度（Occlusion Sensitivity）是指给定预测的概率如何随图像被遮挡部分的变化而变化",{"type":24,"value":183},"。",{"type":18,"tag":156,"props":185,"children":187},{"id":186},"occlusion-sensitivity-结果判定",[188],{"type":24,"value":189},"Occlusion Sensitivity 结果判定",{"type":18,"tag":26,"props":191,"children":192},{},[193,195,200,202,207],{"type":24,"value":194},"对于结果，",{"type":18,"tag":55,"props":196,"children":197},{},[198],{"type":24,"value":199},"输出概率是一个区域的概率",{"type":24,"value":201},"，",{"type":18,"tag":55,"props":203,"children":204},{},[205],{"type":24,"value":206},"是某一输出的概率减去被遮挡区域的输出概率",{"type":24,"value":208},"。输出图像中的值越高，确定度下降越大，说明遮挡区域在决策过程中更为重要。",{"type":18,"tag":26,"props":210,"children":211},{},[212],{"type":18,"tag":39,"props":213,"children":215},{"alt":41,"src":214},"https://bbs-img-cbc-cn.obs.cn-north-1.myhuaweicloud.com/data/forums/attachment/forum/202102/26/125444bg7qpocv8v9udfm7.png",[],{"type":18,"tag":26,"props":217,"children":218},{},[219],{"type":24,"value":220},"好了，原理已经讲完，话不多说，我们开始上代码。使用的是MindSpore框架实现的代码。",{"type":18,"tag":156,"props":222,"children":224},{"id":223},"mindspore代码实现",[225],{"type":24,"value":226},"MindSpore代码实现",{"type":18,"tag":228,"props":229,"children":231},"pre",{"code":230},"\"\"\"OcclusionSensitivity.\"\"\"\nfrom collections.abc import Sequence\nimport numpy as np\nfrom mindspore import nn\nfrom mindspore.common.tensor import Tensor\nfrom mindspore._checkparam import Validator as validator\nfrom .metric import Metric\ntry:\n    from tqdm import trange\nexcept (ImportError, AttributeError):\n    trange = range\nclass OcclusionSensitivity(Metric):\n    \"\"\"\n    该函数用于计算给定图像模型的遮挡灵敏度。\n    \"\"\"\n    def __init__(self, pad_val=0.0, margin=2, n_batch=128, b_box=None):\n        super().__init__()\n        # 当遮挡图像的一部分时，我们应该在图像中输入哪些值？默认0.0\n        self.pad_val = validator.check_value_type(\"pad_val\", pad_val, [float])\n        # 围绕要遮挡的体素创建长方体/立方体。默认2\n        self.margin = validator.check_value_type(\"margin\", margin, [int, Sequence])\n        # 推断前一批中的图像数，默认128\n        self.n_batch = validator.check_value_type(\"n_batch\", n_batch, [int])\n        # 要在其上执行分析的边界框。输出图像的大小也将匹配。除批次外，所有维度都应有最小值和最大值：`[min1，max1，min2，max2，…]``。\n        self.b_box = b_box if b_box is None else validator.check_value_type(\"b_box\", b_box, )\n        self.clear()\n    def clear(self):\n        \"\"\"清除历史数据\"\"\"\n        self._baseline = 0\n        self._sensitivity_im = 0\n        self._is_update = False\n    def _check_input_bounding_box(self, b_box, im_shape):\n        \"\"\"检查边界框（如果提供）是否如预期的那样。\"\"\"\n        # 如果未提供边界框，请将“最小值”和“最大值”设置为“无”\n        if b_box is None:\n            b_box_min = b_box_max = None\n        # 已提供边界框\n        else:\n            # “b_box”中的元素数应是“im_shape”中元素数的两倍\n            if len(b_box) != 2 * len(im_shape):\n                raise ValueError(\"Bounding box should contain upper and lower for all dimensions (except batch number)\")\n            # 如果任何最小值或最大值为-ve，则分别将它们设置为0和im_shape-1。\n            b_box_min = np.array(b_box[::2])\n            b_box_max = np.array(b_box[1::2])\n            b_box_min[b_box_min \u003C 0] = 0\n            b_box_max[b_box_max \u003C 0] = im_shape[b_box_max \u003C 0] - 1\n            # 检查所有最大值是否小于im_shape\n            if np.any(b_box_max >= im_shape):\n                raise ValueError(\"Max bounding box should be \u003C image size for all values\")\n            # 检查所有最小值是否大于最大值\n            if np.any(b_box_min > b_box_max):\n                raise ValueError(\"Min bounding box should be \u003C= max for all values\")\n        return b_box_min, b_box_max\n    def _append_to_sensitivity_im(self, model, batch_images, batch_ids, sensitivity_im):\n        \"\"\"对于给定数量的图像，得到预测给定标签的概率。附上以前的评估。\"\"\"\n        batch_images = np.vstack(batch_images)\n        batch_ids = np.expand_dims(batch_ids, 1)\n        model_numpy = model(Tensor(batch_images)).asnumpy()\n        first_indices = np.arange(batch_ids.shape[0])[:, None]\n        scores = model_numpy[first_indices, batch_ids]\n        if sensitivity_im.size == 0:\n            return np.vstack(scores)\n        return np.vstack((sensitivity_im, scores))\n    def update(self, *inputs):\n        \"\"\"\n        更新输入，包括要使用的模型，预测值和真实值。\n        \"\"\"\n        # 校验输入个数是否是3个\n        if len(inputs) != 3:\n            raise ValueError('occlusion_sensitivity need 3 inputs (model, y_pred, y), but got {}'.format(len(inputs)))\n        model = inputs[0]\n        # 输入转为numpy\n        y_pred = self._convert_data(inputs[1])\n        label = self._convert_data(inputs[2])\n        model = validator.check_value_type(\"model\", model, [nn.Cell])\n        # 检查输入图像是否符合预期\n        if y_pred.shape[0] > 1:\n            raise RuntimeError(\"Expected batch size of 1.\")\n        # 检查输入标签是否如预期的那样。\n        if isinstance(label, int):\n            label = np.array([[label]], dtype=int)\n        # 如果标签是张量，请确保只有一个元素\n        elif np.prod(label.shape) != y_pred.shape[0]:\n            raise RuntimeError(\"Expected as many labels as batches.\")\n        y_pred_shape = np.array(y_pred.shape[1:])\n        b_box_min, b_box_max = self._check_input_bounding_box(self.b_box, y_pred_shape)\n        temp = model(Tensor(y_pred)).asnumpy()\n        # 得到一个概率\n        self._baseline = temp[0, label].item()\n        # 定义两个列表\n        batch_images = []\n        batch_ids = []\n        sensitivity_im = np.empty(0, dtype=float)\n        # 如果未提供边界框，则输出形状与输入形状相同。如果存在边界框，则形状为max-min+1\n        output_im_shape = y_pred_shape if self.b_box is None else b_box_max - b_box_min + 1\n        num_required_predictions = np.prod(output_im_shape)\n        # 在图像上循环1D\n        for i in trange(num_required_predictions):\n            # 获取相应的索引\n            idx = np.unravel_index(i, output_im_shape)\n            # 如果正在使用边界框，我们需要添加最小值以移动到感兴趣区域的开始\n            if b_box_min is not None:\n                idx += b_box_min\n            # 获取要遮挡的框的最小和最大索引\n            min_idx = [max(0, i - self.margin) for i in idx]\n            max_idx = [min(j, i + self.margin) for i, j in zip(idx, y_pred_shape)]\n            occlu_im = y_pred.copy()\n            occlu_im[(...,) + tuple(slice(i, j) for i, j in zip(min_idx, max_idx))] = self.pad_val\n            batch_images.append(occlu_im)\n            batch_ids.append(label)\n            # 一旦批处理完成（或在最后一次迭代中）\n            if len(batch_images) == self.n_batch or i == num_required_predictions - 1:\n                # 做预测并附加到灵敏度的map上\n                sensitivity_im = self._append_to_sensitivity_im(model, batch_images, batch_ids, sensitivity_im)\n                # 清空list\n                batch_images = []\n                batch_ids = []\n        # 调整输出图像的大小\n        self._sensitivity_im = sensitivity_im.reshape(output_im_shape)\n        self._is_update = True\n    def eval(self):\n        \"\"\"\n         Computes the occlusion_sensitivity.\n         Returns:\n             A numpy ndarray.\n        \"\"\"\n        if not self._is_update:\n            raise RuntimeError('Call the update method before calling eval.')\n        # 上面输出的概率减去被遮挡区域的输出概率\n        sensitivity = self._baseline - np.squeeze(self._sensitivity_im)\n        return sensitivity\n",[232],{"type":18,"tag":233,"props":234,"children":235},"code",{"__ignoreMap":7},[236],{"type":24,"value":230},{"type":18,"tag":26,"props":238,"children":239},{},[240],{"type":24,"value":241},"使用方法如下：",{"type":18,"tag":228,"props":243,"children":245},{"code":244},"import numpy as np\nfrom mindspore import nn\nfrom mindspore.nn.metrics import OcclusionSensitivity\nclass DenseNet(nn.Cell):\n    def init(self):\n        super(DenseNet, self).init()\n        w = np.array([[0.1, 0.8, 0.1, 0.1],[1, 1, 1, 1]]).astype(np.float32)\n        b = np.array([0.3, 0.6]).astype(np.float32)\n        self.dense = nn.Dense(4, 2, weight_init=Tensor(w), bias_init=Tensor(b))\n    def construct(self, x):\n        return self.dense(x)\nmodel = DenseNet()\ntest_data = np.array([[0.1, 0.2, 0.3, 0.4]]).astype(np.float32)\nlabel = np.array(1).astype(np.int32)\nmetric = OcclusionSensitivity()\nmetric.clear()\nmetric.update(model, test_data, label)\nscore = metric.eval()\nprint(score)\n[0.29999995    0.6    1    0.9]\n",[246],{"type":18,"tag":233,"props":247,"children":248},{"__ignoreMap":7},[249],{"type":24,"value":244},{"type":18,"tag":26,"props":251,"children":252},{},[253],{"type":24,"value":254},"返回结果是一个numpy，对于返回结果的大小：使用方法如下：",{"type":18,"tag":256,"props":257,"children":258},"ul",{},[259,265],{"type":18,"tag":260,"props":261,"children":262},"li",{},[263],{"type":24,"value":264},"如果没有提供边界框，则大小与输入图像相同；",{"type":18,"tag":260,"props":266,"children":267},{},[268],{"type":24,"value":269},"如果使用边界框，则输出图像将被裁剪为该大小。",{"title":7,"searchDepth":271,"depth":271,"links":272},4,[273,275,276],{"id":158,"depth":274,"text":161},2,{"id":186,"depth":274,"text":189},{"id":223,"depth":274,"text":226},"markdown","content:activities:zh:402.md","content","activities/zh/402.md","activities/zh/402","md",1776506035558]