这篇博客介绍训练过程中的评价函数,在MXNet框架下都可以通过继承mx.metric.EvalMetric类进行实现。
    该项目的train文件夹下的metric.py定义了一个类:MultiBoxMetric,该类可以作为训练时候分类和回归损失的计算

    1. import mxnet as mx
    2. import numpy as np
    3. class MultiBoxMetric(mx.metric.EvalMetric):
    4. """Calculate metrics for Multibox training """
    5. # __init__中指定了两个损失的名称,和其他两个参数,
    6. # 最后调用了该类的reset方法重置了一些计数变量。
    7. def __init__(self, eps=1e-8):
    8. super(MultiBoxMetric, self).__init__('MultiBox')
    9. self.eps = eps
    10. self.num = 2
    11. self.name = ['CrossEntropy', 'SmoothL1']
    12. self.reset()
    13. # reset方法是重置变量的方法
    14. def reset(self):
    15. """
    16. override reset behavior
    17. """
    18. if getattr(self, 'num', None) is None:
    19. self.num_inst = 0
    20. self.sum_metric = 0.0
    21. else:
    22. self.num_inst = [0] * self.num
    23. self.sum_metric = [0.0] * self.num
    24. # update方法是每训练一个batch数据时就会运行的代码,最后返回分类的损失和回归的损失。
    25. # cls_prob是模型预测的每个anchor的类别概率,
    26. # cls_label是每个anchor的真实类别,loc_loss是回归损失。分类的损失是采用的交叉熵损失函数,
    27. # 所以只有预测的概率对应的类别是真实类别的概率才会进入损失函数计算中,
    28. # 也就是代码中的indices变量,
    29. # 另一方面,对负样本(背景)概率的预测损失是不加入到分类损失中的,也就是代码中的mask变量,
    30. # 综合起来就得到了prob变量作为交叉熵损失函数的输入。
    31. # 回归损失在symbol_builder.py中构造symbol的时候就定义好了,
    32. # 所以这里不需要过多处理,直接累加更新即可。
    33. def update(self, labels, preds):
    34. """
    35. Implementation of updating metrics
    36. """
    37. # get generated multi label from network
    38. cls_prob = preds[0].asnumpy()
    39. loc_loss = preds[1].asnumpy()
    40. cls_label = preds[2].asnumpy()
    41. valid_count = np.sum(cls_label >= 0)
    42. # overall accuracy & object accuracy
    43. label = cls_label.flatten()
    44. # in case you have a 'other' class
    45. label[np.where(label >= cls_prob.shape[1])] = 0
    46. mask = np.where(label >= 0)[0]
    47. indices = np.int64(label[mask])
    48. prob = cls_prob.transpose((0, 2, 1)).reshape((-1, cls_prob.shape[1]))
    49. prob = prob[mask, indices]
    50. self.sum_metric[0] += (-np.log(prob + self.eps)).sum()
    51. self.num_inst[0] += valid_count
    52. # smoothl1loss
    53. self.sum_metric[1] += np.sum(loc_loss)
    54. self.num_inst[1] += valid_count
    55. # 当要获取该评价函数的值时就会调用get方法,
    56. # 该方法的作用就是返回前面update方法中计算的self.sum_metric和self.num_inst值。
    57. def get(self):
    58. """Get the current evaluation result.
    59. Override the default behavior
    60. Returns
    61. -------
    62. name : str
    63. Name of the metric.
    64. value : float
    65. Value of the evaluation.
    66. """
    67. if self.num is None:
    68. if self.num_inst == 0:
    69. return (self.name, float('nan'))
    70. else:
    71. return (self.name, self.sum_metric / self.num_inst)
    72. else:
    73. names = ['%s'%(self.name[i]) for i in range(self.num)]
    74. values = [x / y if y != 0 else float('nan') \
    75. for x, y in zip(self.sum_metric, self.num_inst)]
    76. return (names, values)