Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

# GRADED FUNCTION: TripletLossFn def TripletLossFn ( v 1 , v 2 , margin = 0 . 2 5 ) : Custom

# GRADED FUNCTION: TripletLossFn
def TripletLossFn(v1, v2, margin=0.25):
"""Custom Loss function.
Args:
v1(numpy.ndarray or Tensor): Array with dimension (batch_size, model_dimension) associated to Q1.
v2(numpy.ndarray or Tensor): Array with dimension (batch_size, model_dimension) associated to Q2.
margin (float, optional): Desired margin. Defaults to 0.25.
Returns:
triplet_loss (numpy.ndarray or Tensor)
"""
### START CODE HERE ###
# use `tf.linalg.matmul` to take the dot product of the two batches.
# Don't forget to transpose the second argument using `transpose_b=True`
scores = None
# calculate new batch size and cast it as the same datatype as scores.
batch_size = tf.cast(tf.shape(v1)[0], scores.dtype)
# use `tf.linalg.diag_part` to grab the cosine similarity of all positive examples
positive = None
# subtract the diagonal from scores. You can do this by creating a diagonal matrix with the values
# of all positive examples using `tf.linalg.diag`
negative_zero_on_duplicate = None
# use `tf.math.reduce_sum` on `negative_zero_on_duplicate` for `axis=1` and divide it by `(batch_size -1)`
mean_negative = None
# create a composition of two masks:
#the first mask to extract the diagonal elements,
# the second mask to extract elements in the negative_zero_on_duplicate matrix that are larger than the elements in the diagonal
mask_exclude_positives = tf.cast((None)|(None),
scores.dtype)
# multiply `mask_exclude_positives` with 2.0 and subtract it out of `negative_zero_on_duplicate`
negative_without_positive = None
# take the row by row `max` of `negative_without_positive`.
# Hint: `tf.math.reduce_max(negative_without_positive, axis = None)`
closest_negative = None
# compute `tf.maximum` among 0.0 and `A`
# A = subtract `positive` from `margin` and add `closest_negative`
triplet_loss1= None
# compute `tf.maximum` among 0.0 and `B`
# B = subtract `positive` from `margin` and add `mean_negative`
triplet_loss2= None
# add the two losses together and take the `tf.math.reduce_sum` of it
triplet_loss = None
### END CODE HERE ###
return triplet_loss

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Building The Data Lakehouse

Authors: Bill Inmon ,Mary Levins ,Ranjeet Srivastava

1st Edition

1634629663, 978-1634629669

More Books

Students also viewed these Databases questions