I want to write a custom loss function for comparing the generated 2D curves corresponding to y_prediction and y_true, and calculate the signed distance function of them. And for the loss, compare these signed distance functions together.
For curve generation, I used Where to find Python implementation of Chaikin's corner cutting algorithm?. All the functions are the same. For the main function, and conversion to Signed distance function, I write the following codes:
def Chaikin_curve(points):
temp_coords= []
Cartesian_coords_list= []
for k in range (len(points)):
temp_coords.append([points[k,0], points[k,1]])
Cartesian_coords_list=temp_coords
Cartesian_coords_list.append(temp_coords[0])
obj = Object(Cartesian_coords_list)
Smoothed_obj = obj.Smooth_by_Chaikin(number_of_refinements = 4)
return(np.array(Smoothed_obj))
def SDF_conversion(points):
smoothed_obj= Chaikin_curve(points)
polygon = Polygon(smoothed_obj)
resolution= 32
data = np.zeros((resolution, resolution))
for x in range(resolution):
for y in range(resolution):
min_d= 10000
for p in smoothed_obj:
d = math.sqrt((p[0] - x)**2 + (p[1] - y)**2)
if (d < min_d) :
min_d= d
point= Point(x, y)
sign= polygon.contains(point)
real_dist=0
if not sign:
real_dist = min_d
if sign:
real_dist = -1 * min_d
data[x, y] = float(real_dist)
return tf.convert_to_tensor(data)
and finally, my custom loss function is:
def custom_loss(y_true, y_pred):
yy_true= tf.map_fn(SDF_conversion, y_true, dtype=tf.float64)
yy_pred= tf.map_fn(SDF_conversion, y_pred, dtype=tf.float64)
difference= tf.square(yy_true- yy_pred)
return tf.reduce_mean(difference)
This loss function does not work and I got an error: "No gradients provided for any variable".
Do you know how can I fix this?