(x, z_x)
return -corr_d
Loss based on the distance between elements in a batch
Loss based on the distance between elements in a batch
Loss based on the distance between elements in a batch
def distance_loss_corr(x, z_x):
    """Loss based on the distance between elements in a batch"""

    # flatten data
    x = tf.keras.layers.Flatten()(x)
    z_x = tf.keras.layers.Flatten()(z_x)

    ## z score data
    def z_score(x):
        return (x - tf.reduce_mean(x)) / tf.math.reduce_std(x)

    x = z_score(x)
    z_x = z_score(z_x)

    # clip distances to 10 standard deviations for stability
    x = tf.clip_by_value(x, -10, 10)
    z_x = tf.clip_by_value(z_x, -10, 10)

    dx = tf.math.reduce_euclidean_norm(x[1:] - x[:-1], axis=1)
    dz = tf.math.reduce_euclidean_norm(z_x[1:] - z_x[:-1], axis=1)

    # jitter dz to prevent mode collapse
    dz = dz + tf.random.uniform(dz.shape) * 1e-10

    # compute correlation
    corr_d = tf.squeeze(
        tensorflow_probability.stats.correlation(
            x=tf.expand_dims(dx, -1), y=tf.expand_dims(dz, -1)
        )
    )
    if tf.math.is_nan(corr_d):
        raise ValueError("NaN values found in correlation loss.")

    return -corr_d
def distance_loss_corr ( x , z_x ) : # flatten data x = tf . keras . layers . Flatten ( ) ( x ) z_x = tf . keras . layers . Flatten ( ) ( z_x ) ## z score data def z_score ( x ) : return ( x - tf . reduce_mean ( x ) ) / tf . math . reduce_std ( x ) x = z_score ( x ) z_x = z_score ( z_x ) # clip distances to 10 standard deviations for stability x = tf . clip_by_value ( x , - 10 , 10 ) z_x = tf . clip_by_value ( z_x , - 10 , 10 ) dx = tf . math . reduce_euclidean_norm ( x [ 1 : ] - x [ : - 1 ] , axis = 1 ) dz = tf . math . reduce_euclidean_norm ( z_x [ 1 : ] - z_x [ : - 1 ] , axis = 1 ) # jitter dz to prevent mode collapse dz = dz + tf . random . uniform ( dz . shape ) * 1e-10 # compute correlation corr_d = tf . squeeze ( tensorflow_probability . stats . correlation ( x = tf . expand_dims ( dx , - 1 ) , y = tf . expand_dims ( dz , - 1 ) ) ) if tf . math . is_nan ( corr_d ) : raise ValueError ( "NaN values found in correlation loss." ) return - corr_d