Example #1
0
    def test_unweighted(self):
        num_data = 10
        feat_dim = 6
        margin = 1.0
        num_classes = 4

        embedding = np.random.rand(num_data, feat_dim).astype(np.float32)
        labels = np.random.randint(0, num_classes, size=(num_data))

        # Reshape labels to compute adjacency matrix.
        # TODO: https://github.com/PyCQA/pylint/issues/3139
        # pylint: disable=E1136
        labels_reshaped = np.reshape(labels.astype(np.float32),
                                     (labels.shape[0], 1))
        # pylint: enable=E1136
        # Compute the loss in NP.
        adjacency = np.equal(labels_reshaped, labels_reshaped.T)

        pdist_matrix = pairwise_distance_np(embedding, squared=True)
        loss_np = 0.0
        num_positives = 0.0
        for i in range(num_data):
            for j in range(num_data):
                if adjacency[i][j] > 0.0 and i != j:
                    num_positives += 1.0

                    pos_distance = pdist_matrix[i][j]
                    neg_distances = []

                    for k in range(num_data):
                        if adjacency[i][k] == 0:
                            neg_distances.append(pdist_matrix[i][k])

                    # Sort by distance.
                    neg_distances.sort()
                    chosen_neg_distance = neg_distances[0]

                    for l in range(len(neg_distances)):
                        chosen_neg_distance = neg_distances[l]
                        if chosen_neg_distance > pos_distance:
                            break

                    loss_np += np.maximum(
                        0.0, margin - chosen_neg_distance + pos_distance)

        loss_np /= num_positives

        # Compute the loss in TF.
        y_true = tf.constant(labels)
        y_pred = tf.constant(embedding)
        cce_obj = triplet.TripletSemiHardLoss()
        loss = cce_obj(y_true, y_pred)
        self.assertAlmostEqual(self.evaluate(loss), loss_np, 3)
Example #2
0
def test_semihard_tripled_loss_angular(dtype, dist_func, dist_metric):
    num_data = 10
    feat_dim = 6
    margin = 1.0
    num_classes = 4

    embedding = np.random.rand(num_data, feat_dim).astype(np.float32)
    labels = np.random.randint(0, num_classes, size=(num_data))

    # Compute the loss in NP.
    loss_np = triplet_semihard_loss_np(labels, embedding, margin, dist_func)

    # Compute the loss in TF.
    y_true = tf.constant(labels)
    y_pred = tf.constant(embedding, dtype=dtype)
    cce_obj = triplet.TripletSemiHardLoss(distance_metric=dist_metric)
    loss = cce_obj(y_true, y_pred)
    test_utils.assert_allclose_according_to_type(loss.numpy(), loss_np)
Example #3
0
def test_serialization_semihard():
    loss = triplet.TripletSemiHardLoss()
    tf.keras.losses.deserialize(tf.keras.losses.serialize(loss))
Example #4
0
 def test_serialization(self):
     loss = triplet.TripletSemiHardLoss()
     new_loss = tf.keras.losses.deserialize(tf.keras.losses.serialize(loss))