# Load the pre-trained word embedding model embedding_layer = hub.load(base_model_url) # Create a Keras layer from the loaded embedding model shared_embedding_layer = hub.KerasLayer(embedding_layer, trainable=True) # Define the inputs to the model left_input = keras.Input(shape=(), dtype=tf.string) right_input = keras.Input(shape=(), dtype=tf.string) # Pass the inputs through the shared embedding layer embedding_left_output = shared_embedding_layer(left_input) embedding_right_output = shared_embedding_layer(right_input) # Compute the cosine similarity between the embedding vectors cosine_similarity = tf.keras.layers.Dot(axes=-1, normalize=True)( [embedding_left_output, embedding_right_output] ) # Convert the cosine similarity to angular distance pi = tf.constant(math.pi, dtype=tf.float32) clip_cosine_similarities = tf.clip_by_value( cosine_similarity, -0.99999, 0.99999 ) acos_distance = 1.0 - (tf.acos(clip_cosine_similarities) / pi) # Package the model encoder = tf.keras.Model([left_input, right_input], acos_distance) # Compile the model encoder.compile( optimizer=tf.keras.optimizers.Adam( learning_rate=0.00001, beta_1=0.9, beta_2=0.9999, epsilon=0.0000001, amsgrad=False, clipnorm=1.0, name="Adam", ), loss=tf.keras.losses.MeanSquaredError( reduction=keras.losses.Reduction.AUTO, name="mean_squared_error" ), metrics=[ tf.keras.metrics.MeanAbsoluteError(), tf.keras.metrics.MeanAbsolutePercentageError(), ], ) # Print the model summary encoder.summary()