def __init__(self, bins=10, momentum=0.0, mu=0.02): super(GHMRLoss, self).__init__() self.bins = bins self.momentum = momentum self.mu = mu edges_left = np.array([float(x) / bins for x in range(bins)], dtype=np.float32) self.edges_left = Tensor(edges_left.reshape((bins, 1, 1, 1, 1))) edges_right = np.array([float(x) / bins for x in range(1, bins + 1)], dtype=np.float32) edges_right[-1] += 1e-4 self.edges_right = Tensor(edges_right.reshape((bins, 1, 1, 1, 1))) if momentum >= 0: self.acc_sum = Parameter(initializer(0, [bins], mstype.float32)) self.abs = ops.Abs() self.sqrt = ops.Sqrt() self.cast = ops.Cast() self.select = ops.Select() self.reshape = ops.Reshape() self.reduce_sum = ops.ReduceSum() self.max = ops.Maximum() self.less = ops.Less() self.equal = ops.Equal() self.greater = ops.Greater() self.logical_and = ops.LogicalAnd() self.greater_equal = ops.GreaterEqual() self.zeros_like = ops.ZerosLike() self.expand_dims = ops.ExpandDims()
def test_float_mask(self): net = MaskedFill(123.0) inputs = Tensor([1., 2., 3.], mindspore.float32) mask = Tensor([0., 0., 1.], mindspore.float32) outputs = net(inputs, mask) assert all(P.Equal()(outputs, Tensor([1., 2., 123.], mindspore.float32)))
def test_boolean_mask(self): net = MaskedFill(123.0) inputs = Tensor([1., 2., 3.], mindspore.float32) mask = Tensor([False, False, True], mindspore.float32) outputs = net(inputs, mask) assert all(P.Equal()(outputs, Tensor([1., 2., 123.], mindspore.float32)))
def __init__(self, kernel=3, enable_nms_fp16=True): super(NMS, self).__init__() self.pad = (kernel - 1) // 2 self.cast = ops.Cast() self.dtype = ops.DType() self.equal = ops.Equal() self.max_pool = nn.MaxPool2d(kernel, stride=1, pad_mode="same") self.enable_fp16 = enable_nms_fp16
def __init__(self, alpha=2, beta=4): super(FocalLoss, self).__init__() self.alpha = alpha self.beta = beta self.pow = ops.Pow() self.log = ops.Log() self.select = ops.Select() self.equal = ops.Equal() self.less = ops.Less() self.cast = ops.Cast() self.fill = ops.Fill() self.dtype = ops.DType() self.shape = ops.Shape() self.reduce_sum = ops.ReduceSum()
def construct(self, inputs, targets): """ Args: - inputs: feature matrix with shape (batch_size, feat_dim) - targets: ground truth labels with shape (num_classes) """ n = inputs.shape[0] # Compute pairwise distance, replace by the official when merged pow = P.Pow() sum = P.ReduceSum(keep_dims=True) expand = P.BroadcastTo((n, n)) transpose = P.Transpose() mul = P.Mul() add = P.Add() sqrt = P.Sqrt() equal = P.Equal() cat = P.Concat() ones_like = P.OnesLike() dist = pow(inputs, 2) dist = sum(dist, axis=1) dist = expand(dist) dist = dist + transpose(dist, (1, 0)) temp1 = P.matmul(inputs, transpose(inputs, (1, 0))) temp1 = mul(-2, temp1) dist = add(dist, temp1) dist = P.composite.clip_by_value( dist, clip_value_min=1e-12, clip_value_max=100000000 ) # for numerical stability, clip_value_max=? why must set? dist = sqrt(dist) # For each anchor, find the hardest positive and negative targets = expand(targets) mask = equal(targets, transpose(targets, (1, 0))) dist_ap = [] dist_an = [] # only for debugging ##################### # print("dist is") # print(dist.shape) # print(dist) # print("mask is") # print(mask.shape) # print(mask) # print(mask[0]) ##################### for i in range(n): minval = -1.0 maxval = -1.0 for j in range(n): if mask[i][j] and dist[i][j] > maxval: maxval = dist[i][j] if not mask[i][j] and (dist[i][j] < minval or minval == -1): minval = dist[i][j] if (not isinstance(minval, Tensor) or not isinstance(maxval, Tensor) or minval == -1.0 or maxval == -1.0): if self.error_msg is not None: print("Error Msg", file=self.error_msg) print("mask {} is".format(i), file=self.error_msg) print(mask[i], file=self.error_msg) print("dist is:", file=self.error_msg) print(dist[i], file=self.error_msg) print(maxval, file=self.error_msg) print(minval, file=self.error_msg) print(type(maxval), file=self.error_msg) print(type(minval), file=self.error_msg) self.error_msg.flush() # assert minval != -1.0 and isinstance(minval, Tensor) # assert maxval != -1.0 and isinstance(maxval, Tensor) dist_ap.append(maxval.asnumpy()) dist_an.append(minval.asnumpy()) dist_ap = Tensor(dist_ap, ms.float32) dist_an = Tensor(dist_an, ms.float32) # only for debugging ##################### # print(dist_ap) # print(dist_ap.shape) # print(dist_an) ##################### # Compute ranking hinge loss y = ones_like(dist_an) loss = self.ranking_loss(dist_an, dist_ap, y) # # compute accuracy # correct = torch.ge(dist_an, dist_ap).sum().item() return loss # class GradOriTripletLoss(nn.Cell) # def __init__(self, net): # super(GradOriTripletLoss, self).__init__() # self.net = net # self.grad_op = P.GradOperation(get_all=True) # # def construct(self, inputs, targets): # gradient_function = self.grad_op(self.net) # return gradient_function(inputs, targets)